From 66e4db7f7c6f6be7a2ae59f50db2301a6dc38bde Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 09:52:31 -0800 Subject: [PATCH 1/6] should ignore p1 --- core/core.ts | 4 ++ core/indexing/shouldIgnore.test.ts | 53 ++++++++++++++++++++ core/indexing/shouldIgnore.ts | 80 ++++++++++++++++++++++++++++++ core/test/testDir.ts | 4 +- 4 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 core/indexing/shouldIgnore.test.ts create mode 100644 core/indexing/shouldIgnore.ts diff --git a/core/core.ts b/core/core.ts index 180ce8642..dd05484d3 100644 --- a/core/core.ts +++ b/core/core.ts @@ -829,6 +829,10 @@ export class Core { // Codebase indexing on("index/forceReIndex", async ({ data }) => { + const { config } = await this.configHandler.loadConfig(); + if (config?.disableIndexing) { + return; // TODO silent in case of commands? + } if (data?.shouldClearIndexes) { const codebaseIndexer = await this.codebaseIndexerPromise; await codebaseIndexer.clearIndexes(); diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts new file mode 100644 index 000000000..31981c134 --- /dev/null +++ b/core/indexing/shouldIgnore.test.ts @@ -0,0 +1,53 @@ +// Generated by continue + +// Import modules +import { describe, expect, test } from "@jest/globals"; +import { testIde } from "../test/fixtures"; +import { + TEST_DIR, + addToTestDir, + setUpTestDir, + tearDownTestDir, +} from "../test/testDir"; +import { shouldIgnore } from "./shouldIgnore"; + +// Test for the shouldIgnore function +describe("shouldIgnore", () => { + beforeEach(() => { + setUpTestDir(); + }); + + afterEach(() => { + tearDownTestDir(); + }); + + test("should return true if a file is ignored by .gitignore", async () => { + addToTestDir([ + ["/ignored-file.txt", "content"], + ["/kept-file.txt", "content"], + ["/.gitignore", "ignored-file.txt\nignored-folder/"], + "/ignored-folder/", + ["/ignored-folder/file.txt", "content"], + ]); + const result1 = await shouldIgnore( + TEST_DIR + "/ignored-file.txt", + TEST_DIR, + testIde, + ); + expect(result1).toBe(true); + + const result2 = await shouldIgnore( + TEST_DIR + "/ignored-folder", + TEST_DIR, + testIde, + ); + expect(result2).toBe(true); + + const result3 = await shouldIgnore( + TEST_DIR + "/kept-file.txt", + TEST_DIR, + testIde, + ); + expect(result3).toBe(false); + }); +}); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts new file mode 100644 index 000000000..5af63394b --- /dev/null +++ b/core/indexing/shouldIgnore.ts @@ -0,0 +1,80 @@ +import ignore from "ignore"; +import { FileType, IDE } from "../index"; +import { getUriPathBasename } from "../util/uri"; +import { getGlobalContinueIgArray, gitIgArrayFromFile } from "./ignore"; + +interface IgnoreContext { + ignore: ReturnType; + dirname: string; +} + +export async function shouldIgnore( + fileUri: string, + rootDirUri: string, + ide: IDE, + ignoreFiles: string[] = [".gitignore", ".continueignore"], +): Promise { + let currentDir = fileUri; + + while (currentDir !== rootDirUri && currentDir.startsWith(rootDirUri)) { + const dirEntries = await ide.listDir(currentDir); + const dirs = dirEntries + .filter(([_, uriType]) => uriType === FileType.File) + .map(([uri, _]) => uri); + + const ignoreContexts = await getIgnoreContextsInDir( + currentDir, + dirs, + ignoreFiles, + ide, + ); + + const relativePath = fileUri.substring(currentDir.length + 1); + + for (const context of ignoreContexts) { + if (context.ignore.ignores(relativePath)) { + return true; + } + } + + currentDir = getParentDir(currentDir); + } + + return false; +} + +async function getIgnoreContextsInDir( + dirUri: string, + entries: string[], + ignoreFiles: string[], + ide: IDE, +): Promise { + const ignoreEntries = entries.filter((entryUri) => + ignoreFiles.includes(getUriPathBasename(entryUri)), + ); + const patterns = await Promise.all( + ignoreEntries.map(async (entryUri) => { + const fileContent = await ide.readFile(entryUri); + return gitIgArrayFromFile(fileContent); + }), + ); + + const globalPatterns = getGlobalContinueIgArray(); + + return [ + ...patterns.map((patterns) => ({ + ignore: ignore().add(patterns), + dirname: dirUri, + })), + { + ignore: ignore().add(globalPatterns), + dirname: "/", + }, + ]; +} + +function getParentDir(uri: string): string { + const splitUri = uri.split("/"); + splitUri.pop(); + return splitUri.join("/"); +} diff --git a/core/test/testDir.ts b/core/test/testDir.ts index 9b0473b46..0e34f509b 100644 --- a/core/test/testDir.ts +++ b/core/test/testDir.ts @@ -1,7 +1,7 @@ import fs from "fs"; import os from "os"; import path from "path"; -import { localPathToUri, localPathOrUriToPath } from "../util/pathToUri"; +import { localPathOrUriToPath, localPathToUri } from "../util/pathToUri"; // Want this outside of the git repository so we can change branches in tests export const TEST_DIR_PATH = path.join(os.tmpdir(), "testWorkspaceDir"); @@ -26,7 +26,7 @@ export function tearDownTestDir() { "index/index.ts" creates an empty index/index.ts ["index/index.ts", "hello"] creates index/index.ts with contents "hello" */ -export function addToTestDir(pathsOrUris: (string | string[])[]) { +export function addToTestDir(pathsOrUris: (string | [string, string])[]) { // Allow tests to use URIs or local paths const paths = pathsOrUris.map((val) => { if (Array.isArray(val)) { From a2034e801db2469870f0acbe69c3b2512d00aec9 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 13:01:37 -0800 Subject: [PATCH 2/6] shouldignore working --- core/core.ts | 34 ++++++-- core/indexing/shouldIgnore.test.ts | 109 ++++++++++++++++++++---- core/indexing/shouldIgnore.ts | 130 +++++++++++++++-------------- 3 files changed, 184 insertions(+), 89 deletions(-) diff --git a/core/core.ts b/core/core.ts index dd05484d3..874810967 100644 --- a/core/core.ts +++ b/core/core.ts @@ -53,6 +53,7 @@ import { type IndexingProgressUpdate, } from "."; +import { shouldIgnore } from "./indexing/shouldIgnore"; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; import type { IMessenger, Message } from "./protocol/messenger"; @@ -890,30 +891,45 @@ export class Core { uri.endsWith(".gitignore") ) { // Reindex the workspaces - this.invoke("index/forceReIndex", undefined); + this.invoke("index/forceReIndex", { + shouldClearIndexes: true, + }); } else { // Reindex the file - await this.refreshCodebaseIndexFiles([uri]); + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } } } } }); - on("files/created", async ({ data }) => { - if (data?.uris?.length) { + const refreshIfNotIgnored = async (uris: string[]) => { + const toRefresh: string[] = []; + for (const uri of uris) { + const ignore = await shouldIgnore(uri, ide); + if (!ignore) { + toRefresh.push(uri); + } + } + if (toRefresh.length > 0) { this.messenger.send("refreshSubmenuItems", { providers: ["file"], }); - await this.refreshCodebaseIndexFiles(data.uris); + await this.refreshCodebaseIndexFiles(toRefresh); + } + }; + + on("files/created", async ({ data }) => { + if (data?.uris?.length) { + void refreshIfNotIgnored(data.uris); } }); on("files/deleted", async ({ data }) => { if (data?.uris?.length) { - this.messenger.send("refreshSubmenuItems", { - providers: ["file"], - }); - await this.refreshCodebaseIndexFiles(data.uris); + void refreshIfNotIgnored(data.uris); } }); on("files/opened", async ({ data }) => { diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts index 31981c134..1d1ac857c 100644 --- a/core/indexing/shouldIgnore.test.ts +++ b/core/indexing/shouldIgnore.test.ts @@ -1,7 +1,5 @@ // Generated by continue -// Import modules -import { describe, expect, test } from "@jest/globals"; import { testIde } from "../test/fixtures"; import { TEST_DIR, @@ -9,6 +7,7 @@ import { setUpTestDir, tearDownTestDir, } from "../test/testDir"; + import { shouldIgnore } from "./shouldIgnore"; // Test for the shouldIgnore function @@ -23,31 +22,105 @@ describe("shouldIgnore", () => { test("should return true if a file is ignored by .gitignore", async () => { addToTestDir([ - ["/ignored-file.txt", "content"], - ["/kept-file.txt", "content"], - ["/.gitignore", "ignored-file.txt\nignored-folder/"], - "/ignored-folder/", - ["/ignored-folder/file.txt", "content"], + ["ignored-file.txt", "content"], + [".gitignore", "ignored-file.txt"], ]); - const result1 = await shouldIgnore( - TEST_DIR + "/ignored-file.txt", + const result = await shouldIgnore(TEST_DIR + "/ignored-file.txt", testIde, [ TEST_DIR, + ]); + expect(result).toBe(true); + }); + test("should return true if a folder is ignored by .continueignore", async () => { + addToTestDir([ + "ignored-folder/", + ["ignored-folder/file.txt", "content"], + [".continueignore", "ignored-folder/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/ignored-folder/file.txt", testIde, + [TEST_DIR], ); - expect(result1).toBe(true); + expect(result).toBe(true); + }); + test("should return false if a file is not ignored", async () => { + addToTestDir([["kept-file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept-file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + test("should return true if a file is ignored by .gitignore with spaces in file name", async () => { + addToTestDir([ + ["ignored file.txt", "content"], + [".gitignore", "ignored file.txt"], + ]); + const result = await shouldIgnore(TEST_DIR + "/ignored file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(true); + }); - const result2 = await shouldIgnore( - TEST_DIR + "/ignored-folder", - TEST_DIR, + test("should return true if a .continueignore override ignores file", async () => { + addToTestDir([ + ["override-file.txt", "content"], + [".gitignore", "override-file.txt"], + [".continueignore", "!override-file.txt"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/override-file.txt", testIde, + [TEST_DIR], ); - expect(result2).toBe(true); + expect(result).toBe(false); + }); - const result3 = await shouldIgnore( - TEST_DIR + "/kept-file.txt", - TEST_DIR, + 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/"], + ]); + const result = await shouldIgnore( + TEST_DIR + "/level1/level2/level3/ignored-file.txt", testIde, + [TEST_DIR], ); - expect(result3).toBe(false); + expect(result).toBe(true); + }); + + test("should return false if a file with spaces is not ignored", async () => { + addToTestDir([["kept file.txt", "contents"]]); + const result = await shouldIgnore(TEST_DIR + "/kept file.txt", testIde, [ + TEST_DIR, + ]); + expect(result).toBe(false); + }); + + 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"], + ]); + const ignoredResult = await shouldIgnore( + TEST_DIR + "/nested/dir1/ignored.txt", + testIde, + [TEST_DIR], + ); + expect(ignoredResult).toBe(true); + + const keptResult = await shouldIgnore( + TEST_DIR + "/nested/dir2/kept.txt", + testIde, + [TEST_DIR], + ); + expect(keptResult).toBe(false); }); }); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts index 5af63394b..9170bae3e 100644 --- a/core/indexing/shouldIgnore.ts +++ b/core/indexing/shouldIgnore.ts @@ -1,80 +1,86 @@ import ignore from "ignore"; -import { FileType, IDE } from "../index"; -import { getUriPathBasename } from "../util/uri"; -import { getGlobalContinueIgArray, gitIgArrayFromFile } from "./ignore"; +import type { FileType, IDE } from "../"; +import { findUriInDirs } from "../util/uri"; +import { + DEFAULT_IGNORE, + getGlobalContinueIgArray, + gitIgArrayFromFile, +} from "./ignore"; -interface IgnoreContext { - ignore: ReturnType; - dirname: string; -} +/* + Process: + 1. Check global/default ignores + 2. Walk UP tree from file, checking ignores at each level + TODO there might be issues with symlinks here +*/ export async function shouldIgnore( fileUri: string, - rootDirUri: string, ide: IDE, - ignoreFiles: string[] = [".gitignore", ".continueignore"], + rootDirCandidates?: string[], ): Promise { - let currentDir = fileUri; + 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"); + } - while (currentDir !== rootDirUri && currentDir.startsWith(rootDirUri)) { + // Global/default ignores + const globalPatterns = getGlobalContinueIgArray(); + const rootIgnoreContext = ignore().add(globalPatterns).add(DEFAULT_IGNORE); + if (rootIgnoreContext.ignores(relativePathOrBasename)) { + return true; + } + + let currentDir = uri; + while (currentDir !== rootDir) { + // Go to parent dir of file + const splitUri = currentDir.split("/"); + splitUri.pop(); + currentDir = splitUri.join("/"); + + // Get all files in the dir const dirEntries = await ide.listDir(currentDir); - const dirs = dirEntries - .filter(([_, uriType]) => uriType === FileType.File) - .map(([uri, _]) => uri); + const dirFiles = dirEntries + .filter(([_, entryType]) => entryType === (1 as FileType.File)) + .map(([name, _]) => name); - const ignoreContexts = await getIgnoreContextsInDir( - currentDir, - dirs, - ignoreFiles, - ide, + // Find ignore files and get ignore arrays from their contexts + const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore"); + const continueIgnoreFile = dirFiles.find( + (name) => name === ".continueignore", ); - const relativePath = fileUri.substring(currentDir.length + 1); - - for (const context of ignoreContexts) { - if (context.ignore.ignores(relativePath)) { - return true; + 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 []; + }; - currentDir = getParentDir(currentDir); + 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; + } } return false; } - -async function getIgnoreContextsInDir( - dirUri: string, - entries: string[], - ignoreFiles: string[], - ide: IDE, -): Promise { - const ignoreEntries = entries.filter((entryUri) => - ignoreFiles.includes(getUriPathBasename(entryUri)), - ); - const patterns = await Promise.all( - ignoreEntries.map(async (entryUri) => { - const fileContent = await ide.readFile(entryUri); - return gitIgArrayFromFile(fileContent); - }), - ); - - const globalPatterns = getGlobalContinueIgArray(); - - return [ - ...patterns.map((patterns) => ({ - ignore: ignore().add(patterns), - dirname: dirUri, - })), - { - ignore: ignore().add(globalPatterns), - dirname: "/", - }, - ]; -} - -function getParentDir(uri: string): string { - const splitUri = uri.split("/"); - splitUri.pop(); - return splitUri.join("/"); -} From 8765df11fcac1092487ffd1fc842c29dc1e4d0fc Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 15:52:19 -0800 Subject: [PATCH 3/6] speed tests --- core/commands/slash/onboard.ts | 8 +- core/core.ts | 2 +- core/indexing/ignore.ts | 4 + core/indexing/shouldIgnore.test.ts | 55 +++++- core/indexing/shouldIgnore.ts | 79 ++++---- core/indexing/walkDir.test.ts | 43 ++++- core/indexing/walkDir.ts | 267 +++++++++++++------------- core/promptFiles/v2/getPromptFiles.ts | 2 +- 8 files changed, 256 insertions(+), 204 deletions(-) diff --git a/core/commands/slash/onboard.ts b/core/commands/slash/onboard.ts index d6fedcafb..b53c8d3a9 100644 --- a/core/commands/slash/onboard.ts +++ b/core/commands/slash/onboard.ts @@ -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"); diff --git a/core/core.ts b/core/core.ts index 874810967..33ff03776 100644 --- a/core/core.ts +++ b/core/core.ts @@ -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"; diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 6075bdb26..7f5e8a039 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -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 diff --git a/core/indexing/shouldIgnore.test.ts b/core/indexing/shouldIgnore.test.ts index 1d1ac857c..c1935e7d9 100644 --- a/core/indexing/shouldIgnore.test.ts +++ b/core/indexing/shouldIgnore.test.ts @@ -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); + }); }); diff --git a/core/indexing/shouldIgnore.ts b/core/indexing/shouldIgnore.ts index 9170bae3e..dd82a0457 100644 --- a/core/indexing/shouldIgnore.ts +++ b/core/indexing/shouldIgnore.ts @@ -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 { 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; } diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 8a9d26e7e..8ded86670 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -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 () => { diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index 4e97e01d4..757163d96 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -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; - constructor( private readonly uri: string, private readonly ide: IDE, private readonly options: WalkerOptions, - ) { - this.ignoreFileNames = new Set(options.ignoreFiles); - } + ) {} // walk is a depth-first search implementation public async *walk(): AsyncGenerator { - 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 { - 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 { - 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 { - 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; +} diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index d991d140a..7859c7cf7 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -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 From 06bfaee488163cc217236a8169ab006bb409ea28 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 15:56:59 -0800 Subject: [PATCH 4/6] did change active ignores --- core/core.ts | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/core/core.ts b/core/core.ts index 33ff03776..a3fe41f2b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,7 +1,4 @@ -import path from "path"; - import { fetchwithRequestOptions } from "@continuedev/fetch"; -import ignore from "ignore"; import * as URI from "uri-js"; import { v4 as uuidv4 } from "uuid"; @@ -52,7 +49,6 @@ 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"; @@ -995,19 +991,15 @@ export class Core { }); on("didChangeActiveTextEditor", async ({ data: { filepath } }) => { - const ignoreInstance = ignore().add(defaultIgnoreFile); - let rootDirectory = await this.ide.getWorkspaceDirs(); - const relativeFilePath = path.relative(rootDirectory[0], filepath); try { - if (!ignoreInstance.ignores(relativeFilePath)) { + const ignore = shouldIgnore(filepath, this.ide); + if (!ignore) { recentlyEditedFilesCache.set(filepath, filepath); } } catch (e) { - if (e instanceof RangeError) { - // do nothing, this can happen when editing a file outside the workspace such as `../extensions/.continue-debug/config.json` - } else { - console.debug("unhandled ignores error", relativeFilePath, e); - } + console.error( + `didChangeActiveTextEditor: failed to udpate recentlyEditedFiles cache for ${filepath}`, + ); } }); From 1edb910bcbfe40b9c58d38479f14d5d437bfd61e Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 15:58:34 -0800 Subject: [PATCH 5/6] cleanup --- core/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/core.ts b/core/core.ts index a3fe41f2b..7a45bcd03 100644 --- a/core/core.ts +++ b/core/core.ts @@ -998,7 +998,7 @@ export class Core { } } catch (e) { console.error( - `didChangeActiveTextEditor: failed to udpate recentlyEditedFiles cache for ${filepath}`, + `didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`, ); } }); From b2568b7296d19262b605c0fa3043970d5624e3ab Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Fri, 7 Mar 2025 16:11:52 -0800 Subject: [PATCH 6/6] account for disable indexing --- core/core.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/core/core.ts b/core/core.ts index 7a45bcd03..c4370aac2 100644 --- a/core/core.ts +++ b/core/core.ts @@ -827,7 +827,7 @@ export class Core { // Codebase indexing on("index/forceReIndex", async ({ data }) => { const { config } = await this.configHandler.loadConfig(); - if (config?.disableIndexing) { + if (!config || config.disableIndexing) { return; // TODO silent in case of commands? } if (data?.shouldClearIndexes) { @@ -891,10 +891,13 @@ export class Core { shouldClearIndexes: true, }); } else { - // Reindex the file - const ignore = await shouldIgnore(uri, this.ide); - if (!ignore) { - await this.refreshCodebaseIndexFiles([uri]); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + // Reindex the file + const ignore = await shouldIgnore(uri, this.ide); + if (!ignore) { + await this.refreshCodebaseIndexFiles([uri]); + } } } } @@ -913,7 +916,10 @@ export class Core { this.messenger.send("refreshSubmenuItems", { providers: ["file"], }); - await this.refreshCodebaseIndexFiles(toRefresh); + const { config } = await this.configHandler.loadConfig(); + if (config && !config.disableIndexing) { + await this.refreshCodebaseIndexFiles(toRefresh); + } } };