Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/fsAsync.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,22 @@ describe("fsAsync", () => {
.sort();
return expect(gotFileNames).to.deep.equal(expectFiles);
});

it("should support maximum recursion depth", async () => {
const results = await fsAsync.readdirRecursive({ path: baseDir, maxDepth: 2 });

const gotFileNames = results.map((r) => r.name).sort();
const expectFiles = [".hidden", "visible", "subdir/subfile", "node_modules/subfile"];
const expectPaths = expectFiles.map((file) => path.join(baseDir, file)).sort();
return expect(gotFileNames).to.deep.equal(expectPaths);
});

it("should ignore invalid maximum recursion depth", async () => {
const results = await fsAsync.readdirRecursive({ path: baseDir, maxDepth: 0 });

const gotFileNames = results.map((r) => r.name).sort();
const expectFiles = files.map((file) => path.join(baseDir, file)).sort();
return expect(gotFileNames).to.deep.equal(expectFiles);
});
});
});
11 changes: 10 additions & 1 deletion src/fsAsync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ export interface ReaddirRecursiveOpts {
isGitIgnore?: boolean;
// Files in the ignore array to include.
include?: string[];
// Maximum depth to recurse.
maxDepth?: number;
}

export interface ReaddirRecursiveFile {
Expand All @@ -22,6 +24,7 @@ export interface ReaddirRecursiveFile {
async function readdirRecursiveHelper(options: {
path: string;
filter: (p: string) => boolean;
maxDepth: number;
}): Promise<ReaddirRecursiveFile[]> {
const dirContents = readdirSync(options.path);
const fullPaths = dirContents.map((n) => join(options.path, n));
Expand All @@ -35,7 +38,11 @@ async function readdirRecursiveHelper(options: {
if (!fstat.isDirectory()) {
continue;
}
filePromises.push(readdirRecursiveHelper({ path: p, filter: options.filter }));
if (options.maxDepth > 1) {
filePromises.push(
readdirRecursiveHelper({ path: p, filter: options.filter, maxDepth: options.maxDepth - 1 }),
);
}
}

const files = await Promise.all(filePromises);
Expand Down Expand Up @@ -70,8 +77,10 @@ export async function readdirRecursive(
return rule(t);
});
};
const maxDepth = options.maxDepth && options.maxDepth > 0 ? options.maxDepth : Infinity;
return await readdirRecursiveHelper({
path: options.path,
filter: filter,
maxDepth,
});
}
Loading