diff --git a/core/indexing/ignore.ts b/core/indexing/ignore.ts index 2fe5e2ca2..1277ba1cf 100644 --- a/core/indexing/ignore.ts +++ b/core/indexing/ignore.ts @@ -1,6 +1,6 @@ import ignore from "ignore"; -const DEFAULT_IGNORE_FILETYPES = [ +export const DEFAULT_IGNORE_FILETYPES = [ "*.DS_Store", "*-lock.json", "*.lock", @@ -87,3 +87,6 @@ export const DEFAULT_IGNORE_DIRS = [ "gems", ]; export const defaultIgnoreDir = ignore().add(DEFAULT_IGNORE_DIRS); + +export const DEFAULT_IGNORE = + DEFAULT_IGNORE_FILETYPES.join("\n") + "\n" + DEFAULT_IGNORE_DIRS.join("\n"); diff --git a/core/indexing/walkDir.ts b/core/indexing/walkDir.ts index d76b240bf..98636b857 100644 --- a/core/indexing/walkDir.ts +++ b/core/indexing/walkDir.ts @@ -2,6 +2,7 @@ import { EventEmitter } from "events"; import { Minimatch } from "minimatch"; import path from "node:path"; import { FileType, IDE } from ".."; +import { DEFAULT_IGNORE_DIRS, DEFAULT_IGNORE_FILETYPES } from "./ignore"; export interface WalkerOptions { isSymbolicLink?: boolean; @@ -13,6 +14,7 @@ export interface WalkerOptions { exact?: boolean; onlyDirs?: boolean; returnRelativePaths?: boolean; + additionalIgnoreRules?: string[]; } type Entry = [string, FileType]; @@ -40,7 +42,7 @@ class Walker extends EventEmitter { this.isSymbolicLink = opts.isSymbolicLink || false; this.path = opts.path || process.cwd(); this.basename = path.basename(this.path); - this.ignoreFiles = opts.ignoreFiles || [".ignore"]; + this.ignoreFiles = [...(opts.ignoreFiles || [".ignore"]), ".defaultignore"]; this.ignoreRules = {}; this.parent = opts.parent || null; this.includeEmpty = !!opts.includeEmpty; @@ -51,6 +53,10 @@ class Walker extends EventEmitter { this.sawError = false; this.exact = opts.exact; this.onlyDirs = opts.onlyDirs; + + if (opts.additionalIgnoreRules) { + this.addIgnoreRules(opts.additionalIgnoreRules); + } } sort(a: string, b: string): number { @@ -157,6 +163,22 @@ class Walker extends EventEmitter { then(); } + addIgnoreRules(rules: string[]) { + const mmopt = { + matchBase: true, + dot: true, + flipNegate: true, + nocase: true, + }; + const minimatchRules = rules + .filter((line) => !/^#|^$/.test(line.trim())) + .map((rule) => { + return new Minimatch(rule.trim(), mmopt); + }); + + this.ignoreRules[".defaultignore"] = minimatchRules; + } + filterEntries(): void { const filtered = this.entries!.map((entry) => { const passFile = this.filterEntry(entry[0]); @@ -303,9 +325,10 @@ async function walkDirWithCallback( return callback ? p.then((res) => callback(null, res), callback) : p; } -const defaultOptions = { +const defaultOptions: WalkerOptions = { ignoreFiles: [".gitignore", ".continueignore"], onlyDirs: false, + additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES], }; export async function walkDir( @@ -322,6 +345,7 @@ export async function walkDir( onlyDirs: options.onlyDirs, follow: true, includeEmpty: false, + additionalIgnoreRules: options.additionalIgnoreRules, }, ide, async (err, result) => { @@ -337,7 +361,11 @@ export async function walkDir( resolve(relativePaths.map((p) => path + pathSep + p)); } else { // Need to replace with windows path sep - resolve(relativePaths.map((p) => path + pathSep + p.split("/").join(pathSep))); + resolve( + relativePaths.map( + (p) => path + pathSep + p.split("/").join(pathSep), + ), + ); } } } diff --git a/core/test/walkDir.test.ts b/core/test/walkDir.test.ts index 79360b0d1..e3f4b9e0b 100644 --- a/core/test/walkDir.test.ts +++ b/core/test/walkDir.test.ts @@ -168,20 +168,20 @@ describe("walkDir", () => { test("should handle complex patterns in .gitignore", async () => { const files = [ - [".gitignore", "*.log\n!important.log\ntemp/\n/root_only.txt"], - "a.log", - "important.log", + [".gitignore", "*.what\n!important.what\ntemp/\n/root_only.txt"], + "a.what", + "important.what", "root_only.txt", "subdir/", "subdir/root_only.txt", - "subdir/b.log", + "subdir/b.what", "temp/", "temp/c.txt", ]; buildTestDir(files); await expectPaths( - ["important.log", "subdir/root_only.txt"], - ["a.log", "root_only.txt", "subdir/b.log", "temp/c.txt"], + ["important.what", "subdir/root_only.txt"], + ["a.what", "root_only.txt", "subdir/b.what", "temp/c.txt"], ); }); @@ -221,19 +221,39 @@ describe("walkDir", () => { }); test("should return valid paths in absolute path mode", async () => { + const files = ["a.txt", "b/", "b/c.txt"]; + buildTestDir(files); + await expectPaths( + [path.join(TEST_DIR, "a.txt"), path.join(TEST_DIR, "b", "c.txt")], + [], + { + returnRelativePaths: false, + }, + ); + }); + + test.skip("should walk continue repo", async () => { + const results = await walkDir(path.join(__dirname, "..", ".."), ide, { + ignoreFiles: [".gitignore", ".continueignore"], + }); + console.log(results); + }); + + test.skip("should skip .git and node_modules folders", async () => { const files = [ "a.txt", - "b/", - "b/c.txt" + ".git/", + ".git/config", + ".git/HEAD", + "node_modules/", + "node_modules/package/index.js", + "src/", + "src/index.ts", ]; buildTestDir(files); await expectPaths( - [path.join(TEST_DIR, "a.txt"), - path.join(TEST_DIR, "b", "c.txt")], - [], - { - "returnRelativePaths": false - } - ) - }) + ["a.txt", "src/index.ts"], + [".git/config", ".git/HEAD", "node_modules/package/index.js"], + ); + }); }); diff --git a/extensions/vscode/src/ideProtocol.ts b/extensions/vscode/src/ideProtocol.ts index 5f934d6f2..ebb210cf8 100644 --- a/extensions/vscode/src/ideProtocol.ts +++ b/extensions/vscode/src/ideProtocol.ts @@ -15,7 +15,7 @@ import type { Thread, } from "core"; import { Range } from "core"; -import { defaultIgnoreFile } from "core/indexing/ignore"; +import { defaultIgnoreDir, defaultIgnoreFile } from "core/indexing/ignore"; import { walkDir } from "core/indexing/walkDir"; import { editConfigJson, @@ -508,7 +508,10 @@ class VsCodeIde implements IDE { const files = await vscode.workspace.fs.readDirectory(uriFromFilePath(dir)); const results = files.filter( ([name, type]) => - !(type === vscode.FileType.File && defaultIgnoreFile.ignores(name)), + !( + (type === vscode.FileType.File && defaultIgnoreFile.ignores(name)) || + (type === vscode.FileType.Directory && defaultIgnoreDir.ignores(name)) + ), ) as any; return results; } diff --git a/extensions/vscode/src/util/traverseDirectory.ts b/extensions/vscode/src/util/traverseDirectory.ts deleted file mode 100644 index 5040a050a..000000000 --- a/extensions/vscode/src/util/traverseDirectory.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { defaultIgnoreDir, defaultIgnoreFile } from "core/indexing/ignore"; -import ignore from "ignore"; -import * as path from "node:path"; -import * as vscode from "vscode"; -import { uriFromFilePath } from "./vscode"; - -function isIgnoreFilepath(filepath: string): boolean { - return ( - filepath.endsWith(".gitignore") || filepath.endsWith(".continueignore") - ); -} - -/** - * Given glob pattern, returns first non-wildcard path, rest of glob, and whether there was a leading wildcard - */ -function splitGlob(glob: string): [string | undefined, string, boolean] { - const segs = glob.split("/"); - let wildcards = 0; - while (segs[0] === "**") { - segs.shift(); - wildcards++; - } - return [segs.shift(), segs.join("/"), wildcards > 0]; -} - -export async function* traverseDirectory( - directory: string, - gitIgnorePatterns: string[], - returnFiles = true, - onlyThisDirectory: string[] | undefined, - useGitIgnore: boolean, -): AsyncGenerator { - const nodes = await vscode.workspace.fs.readDirectory( - uriFromFilePath(directory), - ); - const files: string[] = []; - const dirs: string[] = []; - const ignorePatterns: string[] = []; - for (const [name, type] of nodes) { - switch (type) { - case vscode.FileType.Directory: - if (!defaultIgnoreDir.ignores(name)) { - dirs.push(name); - } - break; - case vscode.FileType.File: - if (!defaultIgnoreFile.ignores(name)) { - if (isIgnoreFilepath(name)) { - // Make sure you are respecting windows with linux dev container - const bytes = await vscode.workspace.fs.readFile( - uriFromFilePath(path.join(directory, name)), - ); - const contents = new TextDecoder().decode(bytes); - ignorePatterns.push( - ...contents - .split("\n") - .filter((p) => p.trim() !== "" && p[0] !== "#"), - ); - } else { - files.push(name); - } - } - break; - case vscode.FileType.SymbolicLink: - break; - case vscode.FileType.Unknown: - break; - } - } - - const allIgnorePatterns = [...gitIgnorePatterns, ...ignorePatterns].map( - (pattern) => { - if (!pattern.slice(0, -1).includes("/")) { - return `**/${pattern}`; - } - return pattern; - }, - ); - const ig = ignore().add(allIgnorePatterns); - - if (!onlyThisDirectory) { - for (const node of returnFiles ? files : dirs) { - if (!useGitIgnore || !ig.ignores(node)) { - yield path.join(directory, node); - } - } - } - - const subDirIgnorePatterns: { [key: string]: string[] } = {}; - const wildcardPatterns: string[] = []; - for (const ignorePattern of allIgnorePatterns) { - const [first, rest, leadingWildcard] = splitGlob(ignorePattern); - if (leadingWildcard) { - wildcardPatterns.push(`**/${first}${rest ? `/${rest}` : ""}`); - } - if (first) { - if (subDirIgnorePatterns[first] === undefined) { - subDirIgnorePatterns[first] = []; - } - subDirIgnorePatterns[first].push(rest); - } - } - const entries = Object.entries(subDirIgnorePatterns); - for (const dir of dirs) { - // Skip everything except onlyThisDirectory - if (onlyThisDirectory && onlyThisDirectory[0] !== dir) { - continue; - } - - // Recurse if not ignored - if (!useGitIgnore || !(ig.ignores(`${dir}/`) || ig.ignores(dir))) { - // For patterns who can potentially match items of this subdir, strip the subdir from the start - const keepPatterns = [...wildcardPatterns]; - for (const [startPattern, subDirPatterns] of entries) { - if (ignore().add(startPattern).ignores(dir)) { - keepPatterns.push(...subDirPatterns); - } - } - for await (const file of traverseDirectory( - path.join(directory, dir), - keepPatterns, - returnFiles, - onlyThisDirectory && onlyThisDirectory.length > 1 - ? onlyThisDirectory.slice(1) - : undefined, - useGitIgnore, - )) { - yield file; - } - } - } -}