speed tests

This commit is contained in:
Dallin Romney 2025-03-07 15:52:19 -08:00
parent a2034e801d
commit 8765df11fc
8 changed files with 256 additions and 204 deletions

View file

@ -2,8 +2,7 @@ import ignore from "ignore";
import type { FileType, IDE, SlashCommand } from "../..";
import {
defaultIgnoreDir,
defaultIgnoreFile,
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
@ -58,10 +57,7 @@ const OnboardSlashCommand: SlashCommand = {
};
async function getEntriesFilteredByIgnore(dir: string, ide: IDE) {
const ig = ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(getGlobalContinueIgArray());
const ig = ignore().add(DEFAULT_IGNORE).add(getGlobalContinueIgArray());
const entries = await ide.listDir(dir);
const ignoreUri = joinPathsToUri(dir, ".gitignore");

View file

@ -26,7 +26,6 @@ import { streamDiffLines } from "./edit/streamDiffLines";
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { getAllSuggestedDocs } from "./indexing/docs/suggestions";
import { defaultIgnoreFile } from "./indexing/ignore.js";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { callTool } from "./tools/callTool";
@ -53,6 +52,7 @@ import {
type IndexingProgressUpdate,
} from ".";
import { defaultIgnoreFile } from "./indexing/ignore";
import { shouldIgnore } from "./indexing/shouldIgnore";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./protocol/messenger";

View file

@ -114,6 +114,10 @@ export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS);
export const DEFAULT_IGNORE =
DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n");
export const defaultIgnoreFileAndDir = ignore()
.add(defaultIgnoreFile)
.add(defaultIgnoreDir);
export function gitIgArrayFromFile(file: string) {
return file
.split(/\r?\n/) // Split on new line

View file

@ -32,7 +32,6 @@ describe("shouldIgnore", () => {
});
test("should return true if a folder is ignored by .continueignore", async () => {
addToTestDir([
"ignored-folder/",
["ignored-folder/file.txt", "content"],
[".continueignore", "ignored-folder/"],
]);
@ -77,9 +76,6 @@ describe("shouldIgnore", () => {
test("should return true for deeply nested file ignored by ignore files at multiple levels", async () => {
addToTestDir([
"level1/",
"level1/level2/",
"level1/level2/level3/",
["level1/level2/level3/ignored-file.txt", "content"],
["level1/.gitignore", "level2/"],
["level1/level2/.continueignore", "level3/"],
@ -102,9 +98,6 @@ describe("shouldIgnore", () => {
test("should handle multiple levels of directories with some files ignored", async () => {
addToTestDir([
"nested/",
"nested/dir1/",
"nested/dir2/",
["nested/dir1/.gitignore", "ignored.txt"],
["nested/dir1/ignored.txt", "content"],
["nested/dir2/kept.txt", "content"],
@ -123,4 +116,52 @@ describe("shouldIgnore", () => {
);
expect(keptResult).toBe(false);
});
test("should respect default file and folder ignores top level", async () => {
addToTestDir([
[".env", "contents"],
["go.sum", "contents"],
".idea/",
[".idea/test.xml", "contents"],
]);
let result = await shouldIgnore(TEST_DIR + "/.env", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/go.sum", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/.idea", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/.idea/test.xml", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
test("should respect default file and folder ignores at nested level", async () => {
addToTestDir([
"nested/.idea/test.xml",
["nested/.env", "contents"],
["nested/go.sum", "contents"],
]);
let result = await shouldIgnore(TEST_DIR + "/nested/.idea", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/.idea/test.xml", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/.env", testIde, [TEST_DIR]);
expect(result).toBe(true);
result = await shouldIgnore(TEST_DIR + "/nested/go.sum", testIde, [
TEST_DIR,
]);
expect(result).toBe(true);
});
});

View file

@ -1,11 +1,8 @@
import ignore from "ignore";
import type { FileType, IDE } from "../";
import { findUriInDirs } from "../util/uri";
import {
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "./ignore";
import { findUriInDirs, getUriPathBasename } from "../util/uri";
import { defaultIgnoreFileAndDir, getGlobalContinueIgArray } from "./ignore";
import { getIgnoreContext } from "./walkDir";
/*
Process:
@ -20,23 +17,19 @@ export async function shouldIgnore(
rootDirCandidates?: string[],
): Promise<boolean> {
const rootDirUris = rootDirCandidates ?? (await ide.getWorkspaceDirs());
const {
foundInDir: rootDir,
uri,
relativePathOrBasename,
} = findUriInDirs(fileUri, rootDirUris);
if (!rootDir) {
throw new Error("Should ignore: file uri not found in root dirs");
}
const { foundInDir: rootDir, uri } = findUriInDirs(fileUri, rootDirUris);
// Global/default ignores
const globalPatterns = getGlobalContinueIgArray();
const rootIgnoreContext = ignore().add(globalPatterns).add(DEFAULT_IGNORE);
if (rootIgnoreContext.ignores(relativePathOrBasename)) {
if (!rootDir) {
return true;
}
const defaultAndGlobalIgnores = ignore()
.add(defaultIgnoreFileAndDir)
.add(getGlobalContinueIgArray());
let currentDir = uri;
let directParent = true;
let fileType = 1 as FileType.File as FileType;
while (currentDir !== rootDir) {
// Go to parent dir of file
const splitUri = currentDir.split("/");
@ -45,38 +38,32 @@ export async function shouldIgnore(
// Get all files in the dir
const dirEntries = await ide.listDir(currentDir);
const dirFiles = dirEntries
.filter(([_, entryType]) => entryType === (1 as FileType.File))
.map(([name, _]) => name);
// Find ignore files and get ignore arrays from their contexts
const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore");
const continueIgnoreFile = dirFiles.find(
(name) => name === ".continueignore",
// Check if the file is a symbolic link, ignore if so
if (directParent) {
directParent = false;
const baseName = getUriPathBasename(fileUri);
const entry = dirEntries.find(([name, _]) => name === baseName);
if (entry) {
fileType = entry[1];
if (fileType === (64 as FileType.SymbolicLink)) {
return true;
}
}
}
const ignoreContext = await getIgnoreContext(
currentDir,
dirEntries,
ide,
defaultAndGlobalIgnores,
);
const getGitIgnorePatterns = async () => {
if (gitIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.gitignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const getContinueIgnorePatterns = async () => {
if (continueIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.continueignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
let relativePath = uri.substring(currentDir.length + 1);
if (fileType === (2 as FileType.Directory)) {
relativePath += "/";
}
const ignoreArrays = await Promise.all([
getGitIgnorePatterns(),
getContinueIgnorePatterns(),
]);
const ignoreContext = ignore().add(ignoreArrays[0]).add(ignoreArrays[1]);
const relativePath = uri.substring(currentDir.length + 1);
if (ignoreContext.ignores(relativePath)) {
return true;
}

View file

@ -1,14 +1,14 @@
// Generated by continue
import { testIde } from "../test/fixtures";
import {
setUpTestDir,
tearDownTestDir,
addToTestDir,
TEST_DIR_PATH,
} from "../test/testDir";
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
import fs from "fs";
import path from "path";
import { walkDir, walkDirAsync, walkDirs } from "../indexing/walkDir";
import { testIde } from "../test/fixtures";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR_PATH,
} from "../test/testDir";
describe("walkDir functions", () => {
beforeEach(async () => {
@ -19,6 +19,27 @@ describe("walkDir functions", () => {
tearDownTestDir();
});
// describe.only("test speed", () => {
// it("should walk a simple directory structure", async () => {
// addToTestDir([
// "src/",
// ["src/file1.ts", "content1"],
// ["src/file2.ts", "content2"],
// "src/nested/",
// ["src/nested/file3.ts", "content3"],
// ]);
// const dir = await testIde.getWorkspaceDirs();
// const start = Date.now();
// for (let i = 0; i < 10000; i++) {
// await walkDir(dir[0], testIde);
// }
// const passed = Date.now() - start;
// console.log(`Test took ${passed} ms`);
// });
// });
describe("walkDir", () => {
it("should walk a simple directory structure", async () => {
addToTestDir([
@ -313,6 +334,9 @@ describe("walkDir functions", () => {
["node_modules/package/index.js", "content"],
["dist/bundle.js", "content"],
["coverage/lcov.env", "content"],
["nested/node_modules/package/index.js", "content"],
["nested/dist/bundle.js", "content"],
["nested/coverage/lcov.env", "content"],
]);
const files = await walkDir(
@ -327,6 +351,9 @@ describe("walkDir functions", () => {
expect(files).not.toContain(".git/config");
expect(files).not.toContain("node_modules/package/index.js");
expect(files).not.toContain("coverage/lcov.info");
expect(files).not.toContain("nested/node_modules/package/index.js");
expect(files).not.toContain("nested/dist/bundle.js");
expect(files).not.toContain("nested/coverage/lcov.env");
});
it("should handle directory-specific ignore patterns correctly", async () => {

View file

@ -2,27 +2,23 @@ import ignore, { Ignore } from "ignore";
import type { FileType, IDE } from "..";
import { joinPathsToUri } from "../util/uri";
import {
DEFAULT_IGNORE_DIRS,
DEFAULT_IGNORE_FILETYPES,
defaultIgnoreDir,
defaultIgnoreFile,
defaultIgnoreFileAndDir,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "./ignore";
import { joinPathsToUri } from "../util/uri";
export interface WalkerOptions {
ignoreFiles?: string[];
onlyDirs?: boolean;
returnRelativeUrisPaths?: boolean;
additionalIgnoreRules?: string[];
}
type Entry = [string, FileType];
// helper struct used for the DFS walk
type WalkableEntry = {
name: string;
relativeUriPath: string;
uri: string;
type: FileType;
@ -41,143 +37,110 @@ type IgnoreContext = {
};
class DFSWalker {
private readonly ignoreFileNames: Set<string>;
constructor(
private readonly uri: string,
private readonly ide: IDE,
private readonly options: WalkerOptions,
) {
this.ignoreFileNames = new Set<string>(options.ignoreFiles);
}
) {}
// walk is a depth-first search implementation
public async *walk(): AsyncGenerator<string> {
const root = this.newRootWalkContext();
const stack = [root];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
const walkableEntries = await this.listDirForWalking(cur.walkableEntry);
const ignoreContexts = await this.getIgnoreToApplyInDir(
cur,
walkableEntries,
);
for (const w of walkableEntries) {
if (!this.shouldInclude(w, ignoreContexts)) {
continue;
}
if (this.entryIsDirectory(w.entry)) {
stack.push({
walkableEntry: w,
ignoreContexts: ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.returnRelativeUrisPaths) {
yield w.relativeUriPath;
} else {
yield w.uri;
}
}
} else {
// Note that shouldInclude handles skipping files if options.onlyDirs is true
if (this.options.returnRelativeUrisPaths) {
yield w.relativeUriPath;
} else {
yield w.uri;
}
}
}
}
}
const defaultAndGlobalIgnores = ignore()
.add(defaultIgnoreFileAndDir)
.add(getGlobalContinueIgArray());
private newRootWalkContext(): WalkContext {
const globalIgnoreFile = getGlobalContinueIgArray();
return {
const rootContext: WalkContext = {
walkableEntry: {
name: "",
relativeUriPath: "",
uri: this.uri,
type: 2 as FileType.Directory,
entry: ["", 2 as FileType.Directory],
},
ignoreContexts: [
ignoreContexts: [],
};
const stack = [rootContext];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
// Only directories will be added to the stack
const entries = await this.ide.listDir(cur.walkableEntry.uri);
const newIgnore = await getIgnoreContext(
cur.walkableEntry.uri,
entries,
this.ide,
defaultAndGlobalIgnores,
);
const ignoreContexts = [
...cur.ignoreContexts,
{
ignore: ignore()
.add(defaultIgnoreDir)
.add(defaultIgnoreFile)
.add(globalIgnoreFile),
dirname: "",
ignore: newIgnore,
dirname: cur.walkableEntry.relativeUriPath,
},
],
};
}
];
private async listDirForWalking(
walkableEntry: WalkableEntry,
): Promise<WalkableEntry[]> {
const entries = await this.ide.listDir(walkableEntry.uri);
return entries.map((e) => ({
relativeUriPath: `${walkableEntry.relativeUriPath}${walkableEntry.relativeUriPath ? "/" : ""}${e[0]}`,
uri: joinPathsToUri(walkableEntry.uri, e[0]),
type: e[1],
entry: e,
}));
}
for (const entry of entries) {
if (this.entryIsSymlink(entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it links to something outside of the repository and
// we do not want to index it
continue;
}
const walkableEntry = {
name: entry[0],
relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`,
uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]),
type: entry[1],
entry: entry,
};
private async getIgnoreToApplyInDir(
curDir: WalkContext,
entriesInDir: WalkableEntry[],
): Promise<IgnoreContext[]> {
const ignoreFilesInDir = await this.loadIgnoreFiles(entriesInDir);
if (ignoreFilesInDir.length === 0) {
return curDir.ignoreContexts;
}
const patterns = ignoreFilesInDir.map((c) => gitIgArrayFromFile(c)).flat();
const newIgnoreContext = {
ignore: ignore().add(patterns),
dirname: curDir.walkableEntry.relativeUriPath,
};
return [...curDir.ignoreContexts, newIgnoreContext];
}
let relPath = walkableEntry.relativeUriPath;
if (this.entryIsDirectory(entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
continue;
}
}
let shouldInclude = true;
for (const ig of ignoreContexts) {
// remove the directory name and path separator from the match path, unless this an ignore file
// in the root directory
const prefixLength =
ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
if (ig.ignore.ignores(matchPath)) {
shouldInclude = false;
}
}
if (!shouldInclude) {
continue;
}
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<string[]> {
const ignoreEntries = entries.filter((w) =>
this.entryIsIgnoreFile(w.entry),
);
const promises = ignoreEntries.map(async (w) => {
return await this.ide.readFile(w.uri);
});
return Promise.all(promises);
}
private shouldInclude(
walkableEntry: WalkableEntry,
ignoreContexts: IgnoreContext[],
) {
if (this.entryIsSymlink(walkableEntry.entry)) {
// If called from the root, a symlink either links to a real file in this repository,
// and therefore will be walked OR it links to something outside of the repository and
// we do not want to index it
return false;
}
let relPath = walkableEntry.relativeUriPath;
if (this.entryIsDirectory(walkableEntry.entry)) {
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
return false;
if (this.entryIsDirectory(entry)) {
stack.push({
walkableEntry,
ignoreContexts,
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
yield walkableEntry.uri;
}
}
} else {
if (this.options.returnRelativeUrisPaths) {
yield walkableEntry.relativeUriPath;
} else {
yield walkableEntry.uri;
}
}
}
}
for (const ig of ignoreContexts) {
// remove the directory name and path separator from the match path, unless this an ignore file
// in the root directory
const prefixLength = ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
// The ignore library expects a path relative to the ignore file location
const matchPath = relPath.substring(prefixLength);
if (ig.ignore.ignores(matchPath)) {
return false;
}
}
return true;
}
private entryIsDirectory(entry: Entry) {
@ -187,21 +150,9 @@ class DFSWalker {
private entryIsSymlink(entry: Entry) {
return entry[1] === (64 as FileType.SymbolicLink);
}
private entryIsIgnoreFile(e: Entry): boolean {
if (
e[1] === (2 as FileType.Directory) ||
e[1] === (64 as FileType.SymbolicLink)
) {
return false;
}
return this.ignoreFileNames.has(e[0]);
}
}
const defaultOptions: WalkerOptions = {
ignoreFiles: [".gitignore", ".continueignore"],
additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
onlyDirs: false,
returnRelativeUrisPaths: false,
};
@ -238,3 +189,49 @@ export async function walkDirs(
);
return results.flat();
}
export async function getIgnoreContext(
currentDir: string,
currentDirEntries: Entry[],
ide: IDE,
defaultAndGlobalIgnores: Ignore,
) {
const dirFiles = currentDirEntries
.filter(([_, entryType]) => entryType === (1 as FileType.File))
.map(([name, _]) => name);
// Find ignore files and get ignore arrays from their contexts
// These are done separately so that .continueignore can override .gitignore
const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore");
const continueIgnoreFile = dirFiles.find(
(name) => name === ".continueignore",
);
const getGitIgnorePatterns = async () => {
if (gitIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.gitignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const getContinueIgnorePatterns = async () => {
if (continueIgnoreFile) {
const contents = await ide.readFile(`${currentDir}/.continueignore`);
return gitIgArrayFromFile(contents);
}
return [];
};
const ignoreArrays = await Promise.all([
getGitIgnorePatterns(),
getContinueIgnorePatterns(),
]);
// Note precedence here!
const ignoreContext = ignore()
.add(ignoreArrays[0]) // gitignore
.add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed
.add(ignoreArrays[1]); // local .continueignore
return ignoreContext;
}

View file

@ -16,7 +16,7 @@ export async function getPromptFilesFromDir(
return [];
}
const uris = await walkDir(dir, ide, { ignoreFiles: [] });
const uris = await walkDir(dir, ide);
const promptFilePaths = uris.filter((p) => p.endsWith(".prompt"));
const results = promptFilePaths.map(async (uri) => {
const content = await ide.readFile(uri); // make a try catch