( directory: string, options?: FolderStructureOptions, )
| 296 | * @returns A promise resolving to the formatted folder structure string. |
| 297 | */ |
| 298 | export async function getFolderStructure( |
| 299 | directory: string, |
| 300 | options?: FolderStructureOptions, |
| 301 | ): Promise<string> { |
| 302 | const resolvedPath = path.resolve(directory); |
| 303 | const mergedOptions: MergedFolderStructureOptions = { |
| 304 | maxItems: options?.maxItems ?? MAX_ITEMS, |
| 305 | ignoredFolders: options?.ignoredFolders ?? DEFAULT_IGNORED_FOLDERS, |
| 306 | fileIncludePattern: options?.fileIncludePattern, |
| 307 | fileService: options?.fileService, |
| 308 | fileFilteringOptions: |
| 309 | options?.fileFilteringOptions ?? DEFAULT_FILE_FILTERING_OPTIONS, |
| 310 | }; |
| 311 | |
| 312 | try { |
| 313 | // 1. Read the structure using BFS, respecting maxItems |
| 314 | const structureRoot = await readFullStructure(resolvedPath, mergedOptions); |
| 315 | |
| 316 | if (!structureRoot) { |
| 317 | return `Error: Could not read directory "${resolvedPath}". Check path and permissions.`; |
| 318 | } |
| 319 | |
| 320 | // 2. Format the structure into a string |
| 321 | const structureLines: string[] = []; |
| 322 | // Pass true for isRoot for the initial call |
| 323 | formatStructure(structureRoot, '', true, true, structureLines); |
| 324 | |
| 325 | // 3. Build the final output string |
| 326 | function isTruncated(node: FullFolderInfo): boolean { |
| 327 | if (node.hasMoreFiles || node.hasMoreSubfolders || node.isIgnored) { |
| 328 | return true; |
| 329 | } |
| 330 | for (const sub of node.subFolders) { |
| 331 | if (isTruncated(sub)) { |
| 332 | return true; |
| 333 | } |
| 334 | } |
| 335 | return false; |
| 336 | } |
| 337 | |
| 338 | let summary = `Showing up to ${mergedOptions.maxItems} items (files + folders).`; |
| 339 | |
| 340 | if (isTruncated(structureRoot)) { |
| 341 | summary += ` Folders or files indicated with ${TRUNCATION_INDICATOR} contain more items not shown, were ignored, or the display limit (${mergedOptions.maxItems} items) was reached.`; |
| 342 | } |
| 343 | |
| 344 | return `${summary}\n\n${resolvedPath}${path.sep}\n${structureLines.join('\n')}`; |
| 345 | } catch (error: unknown) { |
| 346 | console.error(`Error getting folder structure for ${resolvedPath}:`, error); |
| 347 | return `Error processing directory "${resolvedPath}": ${getErrorMessage(error)}`; |
| 348 | } |
| 349 | } |
no test coverage detected