Simplify walkDir(...) and improve performance by roughly 10x in larger repos (#1806)

The performance of WalkDir is improved by replacing the recursive DFS
with a stack based implementation (less memory in-use during peak
exploration). In addition, some unnecessary flags and options were
removed which allowed the code to be overall simplified. Much less rule
matching is occuring with the same files returned.

Some performance results on my linux host:

small repo:
- 649 files returned by walkDir()
- 9 .gitignore files
- walkDir() old vs new duration: 918 ms to 143 ms

medium sized repo:
- 9271 returned by walkDir()
- 35 .gitignore files
- walkDir() old vs new duration: 10,886 ms to 970ms

large sized repo:
- 197,900 files returned by walkDir()
- 929 .gitignore files
- walkDir() old vs new duration: 498,151 ms to 37,353 ms

Co-authored-by: Rob Leidle <rleidle@tesla.com>
This commit is contained in:
Rob Leidle 2024-07-22 19:33:58 -07:00 • committed by GitHub
parent 087ec6ccaa
commit 0fa0c3bcbd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 150 additions and 308 deletions

View file

@ -1,332 +1,191 @@
import { EventEmitter } from "events";
import { Minimatch } from "minimatch";
import path from "node:path";
import { FileType, IDE } from "../index.js";
import { DEFAULT_IGNORE_DIRS, DEFAULT_IGNORE_FILETYPES } from "./ignore.js";
import { FileType, IDE } from "../index.d.js";
import { DEFAULT_IGNORE_DIRS, DEFAULT_IGNORE_FILETYPES, defaultIgnoreDir, defaultIgnoreFile } from "./ignore.js";
export interface WalkerOptions {
isSymbolicLink?: boolean;
path?: string;
ignoreFiles?: string[];
parent?: Walker | null;
includeEmpty?: boolean;
follow?: boolean;
exact?: boolean;
onlyDirs?: boolean;
onlyDirs?: boolean
returnRelativePaths?: boolean;
additionalIgnoreRules?: string[];
}
type Entry = [string, FileType];
class Walker extends EventEmitter {
isSymbolicLink: boolean;
path: string;
basename: string;
ignoreFiles: string[];
ignoreRules: { [key: string]: Minimatch[] };
parent: Walker | null;
includeEmpty: boolean;
root: string;
follow: boolean;
result: Set<string>;
entries: Entry[] | null;
sawError: boolean;
exact: boolean | undefined;
onlyDirs: boolean | undefined;
constructor(opts: WalkerOptions = {}, protected readonly ide: IDE) {
super(opts as any);
this.isSymbolicLink = opts.isSymbolicLink || false;
this.path = opts.path || process.cwd();
this.basename = path.basename(this.path);
this.ignoreFiles = [...(opts.ignoreFiles || [".ignore"]), ".defaultignore"];
this.ignoreRules = {};
this.parent = opts.parent || null;
this.includeEmpty = !!opts.includeEmpty;
this.root = this.parent ? this.parent.root : this.path;
this.follow = !!opts.follow;
this.result = this.parent ? this.parent.result : new Set();
this.entries = null;
this.sawError = false;
this.exact = opts.exact;
this.onlyDirs = opts.onlyDirs;
// helper struct used for the DFS walk
type WalkableEntry = {
relPath: string
absPath: string
type: FileType
entry: Entry
};
if (opts.additionalIgnoreRules) {
this.addIgnoreRules(opts.additionalIgnoreRules);
}
// helper struct used for the DFS walk
type WalkContext = {
walkableEntry: WalkableEntry
ignoreFiles: IgnoreFile[]
};
class IgnoreFile {
private _rules: Minimatch[];
constructor(public path: string, public content: string) {
this.path = path;
this.content = content;
this._rules = this.contentToRules(content);
}
sort(a: string, b: string): number {
return a.localeCompare(b, "en");
public get rules() {
return this._rules;
}
emit(ev: string, data: any): boolean {
let ret = false;
if (!(this.sawError && ev === "error")) {
if (ev === "error") {
this.sawError = true;
} else if (ev === "done" && !this.parent) {
data = (Array.from(data) as any)
.map((e: string) => (/^@/.test(e) ? `./${e}` : e))
.sort(this.sort);
this.result = new Set(data);
}
if (ev === "error" && this.parent) {
ret = this.parent.emit("error", data);
} else {
ret = super.emit(ev, data);
}
}
return ret;
}
async *start() {
try {
const entries = await this.ide.listDir(this.path);
for await (const result of this.onReadDir(entries)) {
yield result;
}
} catch (err) {
this.emit("error", err);
}
}
isIgnoreFile(e: Entry): boolean {
const p = e[0];
return p !== "." && p !== ".." && this.ignoreFiles.indexOf(p) !== -1;
}
async *onReadDir(entries: Entry[]) {
this.entries = entries;
if (entries.length === 0) {
if (this.includeEmpty) {
this.result.add(this.path.slice(this.root.length + 1));
}
this.emit("done", this.result);
yield this.result;
} else {
const hasIg = this.entries.some((e) => this.isIgnoreFile(e));
if (hasIg) {
await this.addIgnoreFiles();
}
yield* this.filterEntries();
}
}
async addIgnoreFiles() {
const newIg = this.entries!.filter((e) => this.isIgnoreFile(e));
await Promise.all(newIg.map((e) => this.addIgnoreFile(e)));
}
async addIgnoreFile(fileEntry: Entry) {
const ig = path.resolve(this.path, fileEntry[0]);
try {
const file = await this.ide.readFile(ig);
this.onReadIgnoreFile(fileEntry, file);
} catch (err) {
this.emit("error", err);
}
}
onReadIgnoreFile(file: Entry, data: string): void {
const mmopt = {
private contentToRules(content: string): Minimatch[] {
const options = {
matchBase: true,
dot: true,
flipNegate: true,
nocase: true,
};
const rules = data
return content
.split(/\r?\n/)
.filter((line) => !/^#|^$/.test(line.trim()))
.map((rule) => {
return new Minimatch(rule.trim(), mmopt);
});
.map(l => l.trim())
.filter(l => !/^#|^$/.test(l))
.map(l => new Minimatch(l, options));
}
}
this.ignoreRules[file[0]] = rules;
class DFSWalker {
private readonly path: string;
private readonly ide: IDE;
private readonly options: WalkerOptions;
private readonly ignoreFileNames: Set<string>
constructor(path: string, ide: IDE, options: WalkerOptions) {
this.path = path;
this.ide = ide;
this.options = options;
this.ignoreFileNames = new Set<string>(options.ignoreFiles)
}
addIgnoreRules(rules: string[]) {
const mmopt = {
matchBase: true,
dot: true,
flipNegate: true,
nocase: true,
// walk is a depth-first search implementation
public async* walk(): AsyncGenerator<string> {
const root: WalkContext = {
walkableEntry: {
relPath: "",
absPath: this.path,
type: 2 as FileType.Directory,
entry: ["", 2 as FileType.Directory],
},
ignoreFiles: []
};
const minimatchRules = rules
.filter((line) => !/^#|^$/.test(line.trim()))
.map((rule) => {
return new Minimatch(rule.trim(), mmopt);
});
this.ignoreRules[".defaultignore"] = minimatchRules;
}
async *filterEntries() {
const filtered = (await Promise.all(
this.entries!.map(async (entry) => {
const passFile = await this.filterEntry(entry[0]);
const passDir = await this.filterEntry(entry[0], true);
return passFile || passDir ? [entry, passFile, passDir] : false;
}),
).then((entries) => entries.filter((e) => e))) as [
Entry,
boolean,
boolean,
][];
let entryCount = filtered.length;
if (entryCount === 0) {
this.emit("done", this.result);
yield this.result;
} else {
const then = () => {
if (--entryCount === 0) {
// Otherwise in onlyDirs mode, nothing would be returned
if (this.onlyDirs && this.path !== this.root) {
this.result.add(this.path.slice(this.root.length + 1));
const stack = [root];
for (let cur = stack.pop(); cur; cur = stack.pop()) {
const walkableEntries = await this.listDirForWalking(cur.walkableEntry);
const ignoreFiles = await this.getIgnoreFilesToApplyInDir(cur.ignoreFiles, walkableEntries);
for (const w of walkableEntries) {
if (!this.shouldInclude(w, ignoreFiles)) {
continue;
}
if (this.entryIsDirectory(w.entry)) {
stack.push({
walkableEntry: w,
ignoreFiles: ignoreFiles
});
if (this.options.onlyDirs) {
// when onlyDirs is enabled the walker will only return directory names
yield w.relPath;
}
this.emit("done", this.result);
} else {
yield w.relPath;
}
}
}
}
private async listDirForWalking(walkableEntry: WalkableEntry): Promise<WalkableEntry[]> {
const entries = await this.ide.listDir(walkableEntry.absPath);
return entries.map((e) => {
return {
relPath: path.join(walkableEntry.relPath, e[0]),
absPath: path.join(walkableEntry.absPath, e[0]),
type: e[1],
entry: e,
};
});
}
for (const [entry, file, dir] of filtered) {
for await (const statResult of this.stat(entry, file, dir, then)) {
yield statResult;
}
}
private async getIgnoreFilesToApplyInDir(parentIgnoreFiles: IgnoreFile[], walkableEntries: WalkableEntry[]): Promise<IgnoreFile[]> {
const ignoreFilesInDir = await this.loadIgnoreFiles(walkableEntries);
if (ignoreFilesInDir.length === 0) {
return parentIgnoreFiles;
}
return Array.prototype.concat(parentIgnoreFiles, ignoreFilesInDir);
}
entryIsDirectory(entry: Entry) {
const Directory = 2 as FileType.Directory;
return entry[1] === Directory;
private async loadIgnoreFiles(entries: WalkableEntry[]): Promise<IgnoreFile[]> {
const ignoreEntries = entries
.filter(w => this.isIgnoreFile(w.entry));
const promises = ignoreEntries.map(async w => {
const content = await this.ide.readFile(w.absPath);
return new IgnoreFile(w.relPath, content);
});
return Promise.all(promises);
}
entryIsSymlink(entry: Entry) {
const Directory = 64 as FileType.SymbolicLink;
return entry[1] === Directory;
private isIgnoreFile(e: Entry): boolean {
const p = e[0];
return this.ignoreFileNames.has(p);
}
async *onstat(entry: Entry, file: boolean, dir: boolean, then: () => void) {
const abs = this.path + "/" + entry[0];
const isSymbolicLink = this.entryIsSymlink(entry);
if (!this.entryIsDirectory(entry)) {
if (file && !this.onlyDirs) {
this.result.add(abs.slice(this.root.length + 1));
}
then();
yield this.result;
} else {
if (dir) {
yield* this.walker(
entry[0],
{ isSymbolicLink, exact: await this.filterEntry(entry[0] + "/") },
then,
);
} else {
then();
yield this.result;
}
private shouldInclude(walkableEntry: WalkableEntry, ignoreFiles: IgnoreFile[]) {
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 linksto something outside of the repository and
// we do not want to index it
return false;
}
}
async *stat(
entry: Entry,
file: boolean,
dir: boolean,
then: () => void,
): any {
yield* this.onstat(entry, file, dir, then);
}
walkerOpt(entry: string, opts: Partial<WalkerOptions>): WalkerOptions {
return {
path: this.path + "/" + entry,
parent: this,
ignoreFiles: this.ignoreFiles,
follow: this.follow,
includeEmpty: this.includeEmpty,
onlyDirs: this.onlyDirs,
...opts,
};
}
async *walker(entry: string, opts: Partial<WalkerOptions>, then: () => void) {
const walker = new Walker(this.walkerOpt(entry, opts), this.ide);
walker.on("done", then);
yield* walker.start();
}
async filterEntry(
entry: string,
partial?: boolean,
entryBasename?: string,
): Promise<boolean> {
let included = true;
if (this.parent && this.parent.filterEntry) {
const parentEntry = this.basename + "/" + entry;
const parentBasename = entryBasename || entry;
included = await this.parent.filterEntry(
parentEntry,
partial,
parentBasename,
);
if (!included && !this.exact) {
let relPath = walkableEntry.relPath;
if (this.entryIsDirectory(walkableEntry.entry)) {
if (defaultIgnoreDir.ignores(walkableEntry.relPath)) {
return false;
}
relPath = `${relPath}/`;
} else {
if (this.options.onlyDirs) {
return false;
}
if (defaultIgnoreFile.ignores(walkableEntry.relPath)) {
return false;
}
relPath = `/${relPath}`;
}
for (const f of this.ignoreFiles) {
if (this.ignoreRules[f]) {
for (const rule of this.ignoreRules[f]) {
if (rule.negate !== included) {
const isRelativeRule =
entryBasename &&
rule.globParts.some(
(part) => part.length <= (part.slice(-1)[0] ? 1 : 2),
);
const match =
rule.match("/" + entry) ||
rule.match(entry) ||
(!!partial &&
(rule.match("/" + entry + "/") ||
rule.match(entry + "/") ||
(rule.negate &&
(rule.match("/" + entry, true) ||
rule.match(entry, true))) ||
(isRelativeRule &&
(rule.match("/" + entryBasename + "/") ||
rule.match(entryBasename + "/") ||
(rule.negate &&
(rule.match("/" + entryBasename, true) ||
rule.match(entryBasename, true)))))));
if (match) {
included = rule.negate;
}
}
let included = true;
for (const ignoreFile of ignoreFiles) {
for (const r of ignoreFile.rules) {
if (r.negate === included) {
// no need to test when the file is already NOT to be included unless this is a negate rule and vice versa
continue;
}
if (r.match(relPath)) {
included = r.negate;
}
}
}
return included;
}
private entryIsDirectory(entry: Entry) {
return entry[1] === (2 as FileType.Directory);
}
private entryIsSymlink(entry: Entry) {
return entry[1] === (64 as FileType.SymbolicLink);
}
}
const defaultOptions: WalkerOptions = {
ignoreFiles: [".gitignore", ".continueignore"],
onlyDirs: false,
additionalIgnoreRules: [...DEFAULT_IGNORE_DIRS, ...DEFAULT_IGNORE_FILETYPES],
};
@ -335,41 +194,18 @@ export async function walkDir(
ide: IDE,
_options?: WalkerOptions,
): Promise<string[]> {
let entries: string[] = [];
const options = { ...defaultOptions, ..._options };
const walker = new Walker(
{
path,
ignoreFiles: options.ignoreFiles,
onlyDirs: options.onlyDirs,
follow: true,
includeEmpty: false,
additionalIgnoreRules: options.additionalIgnoreRules,
},
ide,
);
try {
for await (const walkedEntries of walker.start()) {
entries = [...walkedEntries];
}
} catch (err) {
console.error(`Error walking directories: ${err}`);
throw err;
const dfsWalker = new DFSWalker(path, ide, options);
let relativePaths: string[] = [];
for await (const e of dfsWalker.walk()) {
relativePaths.push(e);
}
const relativePaths = entries || [];
if (options?.returnRelativePaths) {
return relativePaths;
}
const pathSep = await ide.pathSep();
if (pathSep === "/") {
return relativePaths.map((p) => path + pathSep + p);
return relativePaths.map(p => path + pathSep + p);
}
return relativePaths.map((p) => path + pathSep + p.split("/").join(pathSep));
return relativePaths.map(p => path + pathSep + p.split("/").join(pathSep));
}

View file

@ -126,6 +126,12 @@ describe("walkDir", () => {
await expectPaths(["a.txt", "b.py"], ["no.txt"]);
});
test("should not ignore leading slash when in subfolder", async () => {
const files = [[".gitignore", "/no.txt"], "a.txt", "b.py", "no.txt", "sub/", "sub/no.txt"];
addToTestDir(files);
await expectPaths(["a.txt", "b.py", "sub/no.txt"], ["no.txt"]);
});
test("should handle multiple .gitignore files in nested structure", async () => {
const files = [
[".gitignore", "*.txt"],
@ -218,7 +224,7 @@ describe("walkDir", () => {
await expectPaths(
["d", "d/g"],
["a.txt", "b.py", "c.ts", "d/e.txt", "d/f.py", "d/g/h.ts"],
{ onlyDirs: true, includeEmpty: true },
{ onlyDirs: true },
);
});