Skip to content

Commit

Permalink
Added walker abort option
Browse files Browse the repository at this point in the history
  • Loading branch information
JrMasterModelBuilder committed Oct 3, 2023
1 parent 53cfc14 commit d739fcb
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ export interface IFsWalkOptions {
ignoreUnreadableDirectories?: boolean;
}

export interface IFsWalkSignal {
/**
* Option to abort walker while walking.
*
* @default false
*/
abort?: boolean;
}

const {O_WRONLY, O_SYMLINK} = fsConstants;
export const fsLchmodSupported = !!O_SYMLINK;
export const fsLutimesSupported = !!O_SYMLINK;
Expand Down Expand Up @@ -279,24 +288,29 @@ export async function fsLstatExists(path: string) {
* @param base Directory path.
* @param itter Callback for each entry.
* @param options Walk options.
* @param signal Walk signal.
*/
export async function fsWalk(
base: string,
itter: (path: string, stat: Stats) => Promise<boolean | null | void>,
options: Readonly<IFsWalkOptions> = {}
options: Readonly<IFsWalkOptions> = {},
signal: IFsWalkSignal = {}
) {
const {ignoreUnreadableDirectories} = options;
const stack = (await fsReaddir(base)).reverse();
while (stack.length) {
while (!signal.abort && stack.length) {
const entry = stack.pop() as string;
const fullPath = pathJoin(base, entry);
// eslint-disable-next-line no-await-in-loop
const stat = await fsLstat(fullPath);
if (signal.abort) {
break;
}

// Callback, possibly stop recursion on directory.
// eslint-disable-next-line no-await-in-loop
const recurse = await itter(entry, stat);
if (recurse === null) {
if (signal.abort || recurse === null) {
break;
}
if (recurse === false || !stat.isDirectory()) {
Expand All @@ -319,6 +333,9 @@ export async function fsWalk(
throw err;
}
}
if (signal.abort) {
break;
}
for (let i = subs.length; i--; ) {
stack.push(pathJoin(entry, subs[i]));
}
Expand Down

0 comments on commit d739fcb

Please sign in to comment.