Skip to content

Commit eec6c5c

Browse files
authored
Add maxDepth to readdirRecursive (#9488)
1 parent 644808c commit eec6c5c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/fsAsync.spec.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,5 +110,22 @@ describe("fsAsync", () => {
110110
.sort();
111111
return expect(gotFileNames).to.deep.equal(expectFiles);
112112
});
113+
114+
it("should support maximum recursion depth", async () => {
115+
const results = await fsAsync.readdirRecursive({ path: baseDir, maxDepth: 2 });
116+
117+
const gotFileNames = results.map((r) => r.name).sort();
118+
const expectFiles = [".hidden", "visible", "subdir/subfile", "node_modules/subfile"];
119+
const expectPaths = expectFiles.map((file) => path.join(baseDir, file)).sort();
120+
return expect(gotFileNames).to.deep.equal(expectPaths);
121+
});
122+
123+
it("should ignore invalid maximum recursion depth", async () => {
124+
const results = await fsAsync.readdirRecursive({ path: baseDir, maxDepth: 0 });
125+
126+
const gotFileNames = results.map((r) => r.name).sort();
127+
const expectFiles = files.map((file) => path.join(baseDir, file)).sort();
128+
return expect(gotFileNames).to.deep.equal(expectFiles);
129+
});
113130
});
114131
});

src/fsAsync.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ export interface ReaddirRecursiveOpts {
1212
isGitIgnore?: boolean;
1313
// Files in the ignore array to include.
1414
include?: string[];
15+
// Maximum depth to recurse.
16+
maxDepth?: number;
1517
}
1618

1719
export interface ReaddirRecursiveFile {
@@ -22,6 +24,7 @@ export interface ReaddirRecursiveFile {
2224
async function readdirRecursiveHelper(options: {
2325
path: string;
2426
filter: (p: string) => boolean;
27+
maxDepth: number;
2528
}): Promise<ReaddirRecursiveFile[]> {
2629
const dirContents = readdirSync(options.path);
2730
const fullPaths = dirContents.map((n) => join(options.path, n));
@@ -35,7 +38,11 @@ async function readdirRecursiveHelper(options: {
3538
if (!fstat.isDirectory()) {
3639
continue;
3740
}
38-
filePromises.push(readdirRecursiveHelper({ path: p, filter: options.filter }));
41+
if (options.maxDepth > 1) {
42+
filePromises.push(
43+
readdirRecursiveHelper({ path: p, filter: options.filter, maxDepth: options.maxDepth - 1 }),
44+
);
45+
}
3946
}
4047

4148
const files = await Promise.all(filePromises);
@@ -70,8 +77,10 @@ export async function readdirRecursive(
7077
return rule(t);
7178
});
7279
};
80+
const maxDepth = options.maxDepth && options.maxDepth > 0 ? options.maxDepth : Infinity;
7381
return await readdirRecursiveHelper({
7482
path: options.path,
7583
filter: filter,
84+
maxDepth,
7685
});
7786
}

0 commit comments

Comments
 (0)