(
files: vscode.Uri[],
context: vscode.ExtensionContext,
includeTokens: boolean = true
)
| 92 | * Optionally includes token estimates for cost calculation |
| 93 | */ |
| 94 | export async function buildFileTree( |
| 95 | files: vscode.Uri[], |
| 96 | context: vscode.ExtensionContext, |
| 97 | includeTokens: boolean = true |
| 98 | ): Promise<{ tree: FileTreeNode; totalFiles: number }> { |
| 99 | const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath; |
| 100 | if (!workspaceRoot) { |
| 101 | return { tree: createEmptyRoot(), totalFiles: 0 }; |
| 102 | } |
| 103 | |
| 104 | const cache = getSelectionCache(context); |
| 105 | |
| 106 | // Get file sizes for token estimation (batch stat calls) |
| 107 | const fileSizes = new Map<string, number>(); |
| 108 | if (includeTokens) { |
| 109 | await Promise.all(files.map(async (file) => { |
| 110 | try { |
| 111 | const stat = await vscode.workspace.fs.stat(file); |
| 112 | fileSizes.set(file.fsPath, stat.size); |
| 113 | } catch { |
| 114 | fileSizes.set(file.fsPath, 0); |
| 115 | } |
| 116 | })); |
| 117 | } |
| 118 | |
| 119 | const root: FileTreeNode = { |
| 120 | path: workspaceRoot, |
| 121 | name: path.basename(workspaceRoot), |
| 122 | isDirectory: true, |
| 123 | depth: 0, |
| 124 | selected: false, |
| 125 | children: [] |
| 126 | }; |
| 127 | |
| 128 | for (const file of files) { |
| 129 | const relativePath = path.relative(workspaceRoot, file.fsPath); |
| 130 | const parts = relativePath.split(path.sep); |
| 131 | |
| 132 | let current = root; |
| 133 | let currentPath = workspaceRoot; |
| 134 | for (let i = 0; i < parts.length; i++) { |
| 135 | const part = parts[i]; |
| 136 | const isLast = i === parts.length - 1; |
| 137 | currentPath = path.join(currentPath, part); |
| 138 | |
| 139 | let child = current.children.find(c => c.name === part); |
| 140 | if (!child) { |
| 141 | // Use relative path for cache lookup (cache stores relative paths) |
| 142 | const cached = cache.files[relativePath]; |
| 143 | |
| 144 | // Determine selection: use cache if exists, otherwise select by default |
| 145 | const isSelected = isLast |
| 146 | ? (cached !== undefined ? cached.selected : true) |
| 147 | : false; |
| 148 | |
| 149 | // Estimate tokens from file size (1 token ≈ 4 bytes for code) |
| 150 | const fileSize = fileSizes.get(file.fsPath) || 0; |
| 151 | const tokens = isLast ? Math.ceil(fileSize / 4) : undefined; |
no test coverage detected