(
folderPath: string,
relativePath: string,
options: { recursive: boolean; reverseFiles?: boolean }
)
| 28 | } |
| 29 | |
| 30 | async function buildMarkdownFolderTree( |
| 31 | folderPath: string, |
| 32 | relativePath: string, |
| 33 | options: { recursive: boolean; reverseFiles?: boolean } |
| 34 | ): Promise<FileNode | null> { |
| 35 | if (!(await fileExists(folderPath))) { |
| 36 | return null; |
| 37 | } |
| 38 | |
| 39 | const stats = await fs.stat(folderPath); |
| 40 | if (!stats.isDirectory()) { |
| 41 | return null; |
| 42 | } |
| 43 | |
| 44 | const entries = await fs.readdir(folderPath, { withFileTypes: true }); |
| 45 | const childFolders = options.recursive |
| 46 | ? entries |
| 47 | .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".")) |
| 48 | .sort((a, b) => a.name.localeCompare(b.name)) |
| 49 | : []; |
| 50 | const childFiles = entries |
| 51 | .filter((entry) => entry.isFile() && !entry.name.startsWith(".") && entry.name.endsWith(".md")) |
| 52 | .sort((a, b) => |
| 53 | options.reverseFiles ? b.name.localeCompare(a.name) : a.name.localeCompare(b.name) |
| 54 | ); |
| 55 | |
| 56 | const children: FileNode[] = []; |
| 57 | |
| 58 | for (const folder of childFolders) { |
| 59 | const childPath = `${relativePath}/${folder.name}`; |
| 60 | const childTree = await buildMarkdownFolderTree( |
| 61 | path.join(folderPath, folder.name), |
| 62 | childPath, |
| 63 | options |
| 64 | ); |
| 65 | if (childTree) { |
| 66 | children.push(childTree); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | for (const file of childFiles) { |
| 71 | children.push({ |
| 72 | name: file.name, |
| 73 | path: `${relativePath}/${file.name}`, |
| 74 | type: "file", |
| 75 | }); |
| 76 | } |
| 77 | |
| 78 | if (children.length === 0) { |
| 79 | return null; |
| 80 | } |
| 81 | |
| 82 | return { |
| 83 | name: path.basename(relativePath), |
| 84 | path: relativePath, |
| 85 | type: "folder", |
| 86 | children, |
| 87 | }; |
no test coverage detected