| 4 | import type { CodebuffFileSystem } from '@codebuff/common/types/filesystem' |
| 5 | |
| 6 | export async function listDirectory(params: { |
| 7 | directoryPath: string |
| 8 | projectPath: string |
| 9 | fs: CodebuffFileSystem |
| 10 | }): Promise<CodebuffToolOutput<'list_directory'>> { |
| 11 | const { directoryPath, projectPath, fs } = params |
| 12 | |
| 13 | try { |
| 14 | const resolvedPath = path.resolve(projectPath, directoryPath) |
| 15 | |
| 16 | if (!resolvedPath.startsWith(projectPath)) { |
| 17 | return [ |
| 18 | { |
| 19 | type: 'json', |
| 20 | value: { |
| 21 | errorMessage: `Invalid path: Path '${directoryPath}' is outside the project directory.`, |
| 22 | }, |
| 23 | }, |
| 24 | ] |
| 25 | } |
| 26 | |
| 27 | const entries = await fs.readdir(resolvedPath, { |
| 28 | withFileTypes: true, |
| 29 | }) |
| 30 | |
| 31 | const files: string[] = [] |
| 32 | const directories: string[] = [] |
| 33 | |
| 34 | for (const entry of entries) { |
| 35 | if (entry.isDirectory()) { |
| 36 | directories.push(entry.name) |
| 37 | } else if (entry.isFile()) { |
| 38 | files.push(entry.name) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | return [ |
| 43 | { |
| 44 | type: 'json', |
| 45 | value: { |
| 46 | files, |
| 47 | directories, |
| 48 | path: directoryPath, |
| 49 | }, |
| 50 | }, |
| 51 | ] |
| 52 | } catch (error) { |
| 53 | const errorMessage = error instanceof Error ? error.message : String(error) |
| 54 | return [ |
| 55 | { |
| 56 | type: 'json', |
| 57 | value: { |
| 58 | errorMessage: `Failed to list directory: ${errorMessage}`, |
| 59 | }, |
| 60 | }, |
| 61 | ] |
| 62 | } |
| 63 | } |