path->uri more fixes

This commit is contained in:
Dallin Romney 2024-12-13 15:20:35 -08:00
parent 96e970682f
commit e40c4751e1
14 changed files with 148 additions and 183 deletions

View file

@ -6,7 +6,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { walkDirInWorkspaces } from "../../indexing/walkDir";
import { walkDirs } from "../../indexing/walkDir";
import {
getUriPathBasename,
getShortestUniqueRelativeUriPaths,
@ -46,11 +46,7 @@ class FileContextProvider extends BaseContextProvider {
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const workspaceDirs = await args.ide.getWorkspaceDirs();
const results = await walkDirInWorkspaces(
args.ide,
undefined,
workspaceDirs,
);
const results = await walkDirs(args.ide, undefined, workspaceDirs);
const files = results.flat().slice(-MAX_SUBMENU_ITEMS);
const withUniquePaths = getShortestUniqueRelativeUriPaths(
files,

View file

@ -5,7 +5,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../index.js";
import { walkDirInWorkspaces } from "../../indexing/walkDir.js";
import { walkDirs } from "../../indexing/walkDir.js";
import {
getShortestUniqueRelativeUriPaths,
getUriPathBasename,
@ -32,7 +32,7 @@ class FolderContextProvider extends BaseContextProvider {
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const workspaceDirs = await args.ide.getWorkspaceDirs();
const folders = await walkDirInWorkspaces(
const folders = await walkDirs(
args.ide,
{
onlyDirs: true,

View file

@ -6,7 +6,7 @@ import {
ContextSubmenuItem,
LoadSubmenuItemsArgs,
} from "../../";
import { walkDirInWorkspaces } from "../../indexing/walkDir";
import { walkDirs } from "../../indexing/walkDir";
import generateRepoMap from "../../util/generateRepoMap";
import {
getShortestUniqueRelativeUriPaths,
@ -36,7 +36,9 @@ class RepoMapContextProvider extends BaseContextProvider {
name: "Repository Map",
description: "Overview of the repository structure",
content: await generateRepoMap(extras.llm, extras.ide, {
dirs: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query],
dirUris: query === ENTIRE_PROJECT_ITEM.id ? undefined : [query],
outputRelativeUriPaths: true,
includeSignatures: false,
}),
},
];
@ -46,7 +48,7 @@ class RepoMapContextProvider extends BaseContextProvider {
args: LoadSubmenuItemsArgs,
): Promise<ContextSubmenuItem[]> {
const workspaceDirs = await args.ide.getWorkspaceDirs();
const folders = await walkDirInWorkspaces(
const folders = await walkDirs(
args.ide,
{
onlyDirs: true,

View file

@ -47,8 +47,9 @@ export async function requestFilesFromRepoMap(
try {
const repoMap = await generateRepoMap(llm, ide, {
dirUris: filterDirUri ? [filterDirUri] : undefined,
includeSignatures: false,
dirs: filterDirUri ? [filterDirUri] : undefined,
outputRelativeUriPaths: false,
});
const prompt = `${repoMap}
@ -72,26 +73,26 @@ This is the question that you should select relevant files for: "${input}"`;
return [];
}
const subDirPrefix = filterDirUri
? getUriPathBasename(filterDirUri) + "/"
: "";
const files =
content
.split("<results>")[1]
?.split("</results>")[0]
?.split("\n")
.filter(Boolean)
.map((file) => file.trim())
.map((file) => subDirPrefix + file) ?? [];
// IMPORANT
// const subDirPrefix = filterDirUri
// ? getUriPathBasename(filterDirUri) + "/"
// : "";
const fileUris = content
.split("<results>")[1]
?.split("</results>")[0]
?.split("\n")
.filter(Boolean)
.map((uri) => uri.trim());
const chunks = await Promise.all(
files.map(async (file) => {
const content = await ide.readFile(file);
fileUris.map(async (uri) => {
const content = await ide.readFile(uri);
const lineCount = content.split("\n").length;
const chunk: Chunk = {
digest: file,
digest: uri,
content,
filepath: file,
filepath: uri,
endLine: lineCount - 1,
startLine: 0,
index: 0,

View file

@ -390,7 +390,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
offset: number = 0,
batchSize: number = 100,
): Promise<{
groupedByPath: { [path: string]: string[] };
groupedByUri: { [path: string]: string[] };
hasMore: boolean;
}> {
const db = await SqliteDb.get();
@ -411,17 +411,17 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
const rows = await db.all(query, [...likePatterns, batchSize, offset]);
const groupedByPath: { [path: string]: string[] } = {};
const groupedByUri: { [path: string]: string[] } = {};
for (const { path, signature } of rows) {
if (!groupedByPath[path]) {
groupedByPath[path] = [];
if (!groupedByUri[path]) {
groupedByUri[path] = [];
}
groupedByPath[path].push(signature);
groupedByUri[path].push(signature);
}
const hasMore = rows.length === batchSize;
return { groupedByPath, hasMore };
return { groupedByUri, hasMore };
}
}

View file

@ -1,6 +1,6 @@
import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../";
import { getBasename } from "../util/index";
import { RETRIEVAL_PARAMS } from "../util/parameters";
import { getUriPathBasename } from "../util/uri";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
@ -79,7 +79,7 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
yield {
progress: i / results.compute.length,
desc: `Indexing ${getBasename(item.path)}`,
desc: `Indexing ${getUriPathBasename(item.path)}`,
status: "indexing",
};
await markComplete([item], IndexResultType.Compute);

View file

@ -31,6 +31,11 @@ function breakdownArticleComponent(
let content = "";
let index = 0;
const fullUrl = new URL(
`${subpath}#${cleanFragment(article.title)}`,
url,
).toString();
const createChunk = (
chunkContent: string,
chunkStartLine: number,
@ -44,11 +49,8 @@ function breakdownArticleComponent(
title: cleanHeader(article.title),
},
index: index++,
filepath: new URL(
`${subpath}#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,
filepath: fullUrl,
digest: fullUrl,
});
};

View file

@ -7,7 +7,7 @@ import {
ParsedPackageInfo,
} from "../../..";
import { getUriPathBasename } from "../../../util/uri";
import { walkDir, walkDirInWorkspaces } from "../../walkDir";
import { walkDir, walkDirs } from "../../walkDir";
import { PythonPackageCrawler } from "./packageCrawlers/Python";
import { NodePackageCrawler } from "./packageCrawlers/TsJs";
@ -25,7 +25,7 @@ export interface PackageCrawler {
}
export async function getAllSuggestedDocs(ide: IDE) {
const allFileUris = await walkDirInWorkspaces(ide);
const allFileUris = await walkDirs(ide);
const allFiles = allFileUris.map((uri) => ({
path: uri,
name: getUriPathBasename(uri),

View file

@ -224,7 +224,7 @@ export async function* walkDirAsync(
yield* new DFSWalker(path, ide, options).walk();
}
export async function walkDirInWorkspaces(
export async function walkDirs(
ide: IDE,
_optionOverrides?: WalkerOptions,
dirs?: string[], // Can pass dirs to prevent duplicate calls

View file

@ -3,7 +3,10 @@ import generateRepoMap from "../../util/generateRepoMap";
import { ToolImpl } from ".";
export const viewRepoMapImpl: ToolImpl = async (args, extras) => {
const repoMap = await generateRepoMap(extras.llm, extras.ide, {});
const repoMap = await generateRepoMap(extras.llm, extras.ide, {
outputRelativeUriPaths: true,
includeSignatures: false,
});
return [
{
name: "Repo map",

View file

@ -5,18 +5,18 @@ import { ToolImpl } from ".";
export const viewSubdirectoryImpl: ToolImpl = async (args: any, extras) => {
const { directory_path } = args;
const absoluteUri = await resolveRelativePathInDir(
directory_path,
extras.ide,
);
const uri = await resolveRelativePathInDir(directory_path, extras.ide);
if (!absoluteUri) {
if (!uri) {
throw new Error(`Directory path "${directory_path}" does not exist.`);
}
const repoMap = await generateRepoMap(extras.llm, extras.ide, {
dirs: [absoluteUri],
dirUris: [uri],
outputRelativeUriPaths: true,
includeSignatures: false,
});
return [
{
name: "Repo map",

View file

@ -39,7 +39,7 @@ describe.skip("generateRepoMap", () => {
.mockImplementation(async (dirs, offset, limit) => {
// Return test data
return {
groupedByPath: {
groupedByUri: {
[path.join(TEST_DIR, "file1.js")]: [
"function foo() {}",
"function bar() {}",
@ -60,6 +60,7 @@ describe.skip("generateRepoMap", () => {
// Act
const repoMapContent = await generateRepoMap(testLLM, testIde, {
includeSignatures: true,
outputRelativeUriPaths: true,
});
// Assert
@ -103,7 +104,7 @@ describe.skip("generateRepoMap", () => {
.mockImplementation(async (dirs, offset, limit) => {
// Return test data
return {
groupedByPath: {
groupedByUri: {
[path.join(TEST_DIR, "file1.js")]: [],
[path.join(TEST_DIR, "subdir/file2.py")]: [],
},
@ -118,6 +119,7 @@ describe.skip("generateRepoMap", () => {
// Act
const repoMapContent = await generateRepoMap(testLLM, testIde, {
includeSignatures: false,
outputRelativeUriPaths: true,
});
// Assert
@ -155,7 +157,7 @@ describe.skip("generateRepoMap", () => {
.mockImplementation(async (dirs, offset, limit) => {
// Return test data
return {
groupedByPath: {
groupedByUri: {
[path.join(TEST_DIR, "file1.js")]: ["function foo() {}"],
[path.join(TEST_DIR, "subdir/file2.py")]: ["def foo():"],
},
@ -185,6 +187,7 @@ describe.skip("generateRepoMap", () => {
// Act
const repoMapContent = await generateRepoMap(testLLM, testIde, {
includeSignatures: true,
outputRelativeUriPaths: true,
});
// Assert

View file

@ -1,16 +1,17 @@
import fs from "node:fs";
import path from "node:path";
import { IDE, ILLM } from "..";
import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex";
import { walkDirAsync } from "../indexing/walkDir";
import { walkDirs } from "../indexing/walkDir";
import { pruneLinesFromTop } from "../llm/countTokens";
import { getRepoMapFilePath } from "./paths";
import { findUriInDirs } from "./uri";
export interface RepoMapOptions {
includeSignatures?: boolean;
dirs?: string[];
dirUris?: string[];
outputRelativeUriPaths: boolean;
}
class RepoMapGenerator {
@ -19,8 +20,8 @@ class RepoMapGenerator {
private repoMapPath: string = getRepoMapFilePath();
private writeStream: fs.WriteStream = fs.createWriteStream(this.repoMapPath);
private contentTokens: number = 0;
private repoMapDirs: string[] = [];
private allPathsInDirs: Set<string> = new Set();
private dirs: string[] = [];
private allUris: string[] = [];
private pathsInDirsWithSnippets: Set<string> = new Set();
private BATCH_SIZE = 100;
@ -40,123 +41,100 @@ class RepoMapGenerator {
llm.contextLength * this.REPO_MAX_CONTEXT_LENGTH_RATIO;
}
/*
Note, the repo map is usually USED as relative file paths (passed to LLM)
So for now, using URIs INPUTS to generate the map, but OUTPUTing relative paths
The exception if requestFilesFromRepoMap, which now converts the relative paths back to URIs
*/
private getUriForWrite(uri: string) {
if (this.options.outputRelativeUriPaths) {
return findUriInDirs(uri, this.dirs).relativePathOrBasename;
}
return uri;
}
async generate(): Promise<string> {
this.repoMapDirs = this.options.dirs ?? (await this.ide.getWorkspaceDirs());
this.allPathsInDirs = await this.getAllPathsInDirs();
this.dirs = this.options.dirUris ?? (await this.ide.getWorkspaceDirs());
this.allUris = await walkDirs(this.ide, undefined, this.dirs);
await this.initializeWriteStream();
await this.processPathsAndSignatures();
this.writeStream.end();
this.logRepoMapGeneration();
return fs.readFileSync(this.repoMapPath, "utf8");
}
private async initializeWriteStream(): Promise<void> {
// Initialize
await this.writeToStream(this.PREAMBLE);
this.contentTokens += this.llm.countTokens(this.PREAMBLE);
}
private async getAllPathsInDirs(): Promise<Set<string>> {
const paths = new Set<string>();
if (this.options.includeSignatures) {
// Process uris and signatures
let offset = 0;
while (true) {
const { groupedByUri, hasMore } =
await CodeSnippetsCodebaseIndex.getPathsAndSignatures(
this.allUris,
offset,
this.BATCH_SIZE,
);
// process batch
for (const [uri, signatures] of Object.entries(groupedByUri)) {
let fileContent: string;
for (const dir of this.repoMapDirs) {
for await (const filepath of walkDirAsync(dir, this.ide)) {
paths.add(filepath.replace(dir, "").slice(1));
try {
fileContent = await this.ide.readFile(uri);
} catch (err) {
console.error(
"Failed to read file:\n" +
` Uri: ${uri}\n` +
` Error: ${err instanceof Error ? err.message : String(err)}`,
);
continue;
}
const filteredSignatures = signatures.filter(
(signature) => signature.trim() !== fileContent.trim(),
);
if (filteredSignatures.length > 0) {
this.pathsInDirsWithSnippets.add(uri);
}
let content = `${this.getUriForWrite(uri)}:\n`;
for (const signature of signatures.slice(0, -1)) {
content += `${this.indentMultilineString(signature)}\n\t...\n`;
}
content += `${this.indentMultilineString(
signatures[signatures.length - 1],
)}\n\n`;
if (content) {
await this.writeToStream(content);
}
}
if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) {
break;
}
offset += this.BATCH_SIZE;
}
}
return paths;
}
private async processPathsAndSignatures(): Promise<void> {
let offset = 0;
while (true) {
const { groupedByPath, hasMore } =
await CodeSnippetsCodebaseIndex.getPathsAndSignatures(
this.repoMapDirs,
offset,
this.BATCH_SIZE,
);
await this.processBatch(groupedByPath);
if (!hasMore || this.contentTokens >= this.maxRepoMapTokens) {
break;
}
offset += this.BATCH_SIZE;
}
await this.writeRemainingPaths();
}
private async processBatch(
groupedByPath: Record<string, string[]>,
): Promise<void> {
for (const [absolutePath, signatures] of Object.entries(groupedByPath)) {
const content = await this.processFile(absolutePath, signatures);
if (content) {
await this.writeToStream(content);
}
}
}
private async processFile(
absolutePath: string,
signatures: string[],
): Promise<string | undefined> {
const workspaceDir =
this.repoMapDirs.find((dir) => absolutePath.startsWith(dir)) || "";
const relativePath = path.relative(workspaceDir, absolutePath);
let fileContent: string;
try {
fileContent = await fs.promises.readFile(absolutePath, "utf8");
} catch (err) {
console.error(
"Failed to read file:\n" +
` Path: ${absolutePath}\n` +
` Error: ${err instanceof Error ? err.message : String(err)}`,
// Remaining Uris just so that written repo map isn't incomplete
const urisWithoutSnippets = this.allUris.filter(
(uri) => !this.pathsInDirsWithSnippets.has(uri),
);
return;
if (urisWithoutSnippets.length > 0) {
await this.writeToStream(
urisWithoutSnippets.map((uri) => this.getUriForWrite(uri)).join("\n"),
);
}
} else {
// Only process uris
await this.writeToStream(
this.allUris.map((uri) => this.getUriForWrite(uri)).join("\n"),
);
}
const filteredSignatures = signatures.filter(
(signature) => signature.trim() !== fileContent.trim(),
);
this.writeStream.end();
if (filteredSignatures.length > 0) {
this.pathsInDirsWithSnippets.add(relativePath);
if (this.contentTokens >= this.maxRepoMapTokens) {
console.debug(
"Full repo map was unable to be generated due to context window limitations",
);
}
return this.generateContentForPath(relativePath, filteredSignatures);
}
private generateContentForPath(
relativePath: string,
signatures: string[],
): string {
if (this.options.includeSignatures === false) {
return `${relativePath}\n`;
}
let content = `${relativePath}:\n`;
for (const signature of signatures.slice(0, -1)) {
content += `${this.indentMultilineString(signature)}\n\t...\n`;
}
content += `${this.indentMultilineString(
signatures[signatures.length - 1],
)}\n\n`;
return content;
return fs.readFileSync(this.repoMapPath, "utf8");
}
private async writeToStream(content: string): Promise<void> {
@ -175,26 +153,6 @@ class RepoMapGenerator {
await new Promise((resolve) => this.writeStream.write(content, resolve));
}
private async writeRemainingPaths(): Promise<void> {
const pathsWithoutSnippets = new Set(
[...this.allPathsInDirs].filter(
(x) => !this.pathsInDirsWithSnippets.has(x),
),
);
if (pathsWithoutSnippets.size > 0) {
await this.writeToStream(Array.from(pathsWithoutSnippets).join("\n"));
}
}
private logRepoMapGeneration(): void {
if (this.contentTokens >= this.maxRepoMapTokens) {
console.debug(
"Full repo map was unable to be generated due to context window limitations",
);
}
}
private indentMultilineString(str: string) {
return str
.split("\n")

View file

@ -1,5 +1,5 @@
import { IDE } from "core";
import { walkDirInWorkspaces } from "core/indexing/walkDir";
import { walkDirs } from "core/indexing/walkDir";
// @ts-ignore
import MiniSearch from "minisearch";
import * as vscode from "vscode";
@ -24,7 +24,7 @@ export class FileSearch {
},
});
private async initializeFileSearchState() {
const results = await walkDirInWorkspaces(this.ide);
const results = await walkDirs(this.ide);
this.miniSearch.addAll(
results.flat().map((uri) => ({
id: uri,