| 1 | import { |
| 2 | ContextItem, |
| 3 | ContextProviderDescription, |
| 4 | ContextProviderExtras, |
| 5 | } from "../../index.js"; |
| 6 | import { walkDir } from "../../indexing/walkDir.js"; |
| 7 | import { findUriInDirs, getUriPathBasename } from "../../util/uri.js"; |
| 8 | import { BaseContextProvider } from "../index.js"; |
| 9 | |
| 10 | interface Directory { |
| 11 | name: string; |
| 12 | files: string[]; |
| 13 | directories: Directory[]; |
| 14 | } |
| 15 | |
| 16 | function formatFileTree(tree: Directory, indentation = ""): string { |
| 17 | let result = ""; |
| 18 | for (const file of tree.files) { |
| 19 | result += `${indentation}${file}\n`; |
| 20 | } |
| 21 | |
| 22 | for (const directory of tree.directories) { |
| 23 | result += `${indentation}${directory.name}/\n`; |
| 24 | result += formatFileTree(directory, `${indentation} `); |
| 25 | } |
| 26 | |
| 27 | return result; |
| 28 | } |
| 29 | |
| 30 | class FileTreeContextProvider extends BaseContextProvider { |
| 31 | static description: ContextProviderDescription = { |
| 32 | title: "tree", |
| 33 | displayTitle: "File Tree", |
| 34 | description: "Attach a representation of the file tree", |
| 35 | type: "normal", |
| 36 | renderInlineAs: "", |
| 37 | }; |
| 38 | |
| 39 | async getContextItems( |
| 40 | query: string, |
| 41 | extras: ContextProviderExtras, |
| 42 | ): Promise<ContextItem[]> { |
| 43 | const workspaceDirs = await extras.ide.getWorkspaceDirs(); |
| 44 | const trees = []; |
| 45 | |
| 46 | for (const workspaceDir of workspaceDirs) { |
| 47 | const subDirTree: Directory = { |
| 48 | name: getUriPathBasename(workspaceDir), |
| 49 | files: [], |
| 50 | directories: [], |
| 51 | }; |
| 52 | |
| 53 | const uris = await walkDir(workspaceDir, extras.ide, { |
| 54 | source: "get context items - file tree", |
| 55 | }); |
| 56 | const relativePaths = uris.map( |
| 57 | (uri) => findUriInDirs(uri, [workspaceDir]).relativePathOrBasename, |
| 58 | ); |
| 59 | |
| 60 | for (const path of relativePaths) { |
| 61 | const parts = path.split("/"); |
| 62 | |
| 63 | let currentTree = subDirTree; |
| 64 | for (const part of parts.slice(0, -1)) { |
| 65 | if (!currentTree.directories.some((d) => d.name === part)) { |
| 66 | currentTree.directories.push({ |
| 67 | name: part, |
| 68 | files: [], |
| 69 | directories: [], |
| 70 | }); |
| 71 | } |
| 72 | |
| 73 | currentTree = currentTree.directories.find((d) => d.name === part)!; |
| 74 | } |
| 75 | |
| 76 | currentTree.files.push(parts.pop()!); |
| 77 | } |
| 78 | |
| 79 | trees.push(formatFileTree(subDirTree)); |
| 80 | } |
| 81 | |
| 82 | return [ |
| 83 | { |
| 84 | content: `Here is a file tree of the current workspace:\n\n${trees.join( |
| 85 | "\n\n", |
| 86 | )}`, |
| 87 | name: "File Tree", |
| 88 | description: "File Tree", |
| 89 | }, |
| 90 | ]; |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | export default FileTreeContextProvider; |