keycloak_theme/src/bin/tools/crawlAsync.ts

52 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-11-02 22:39:03 +01:00
import * as fsPr from "fs/promises";
import { join as pathJoin, relative as pathRelative } from "path";
import { assert, type Equals } from "tsafe/assert";
/** List all files in a given directory return paths relative to the dir_path */
export async function crawlAsync(params: {
dirPath: string;
returnedPathsType: "absolute" | "relative to dirPath";
2024-11-17 23:05:41 +01:00
onFileFound: (filePath: string) => Promise<void>;
2024-11-02 22:39:03 +01:00
}) {
const { dirPath, returnedPathsType, onFileFound } = params;
await crawlAsyncRec({
dirPath,
2024-11-17 23:05:41 +01:00
onFileFound: async ({ filePath }) => {
2024-11-02 22:39:03 +01:00
switch (returnedPathsType) {
case "absolute":
2024-11-17 23:05:41 +01:00
await onFileFound(filePath);
2024-11-02 22:39:03 +01:00
return;
case "relative to dirPath":
2024-11-17 23:05:41 +01:00
await onFileFound(pathRelative(dirPath, filePath));
2024-11-02 22:39:03 +01:00
return;
}
assert<Equals<typeof returnedPathsType, never>>();
}
});
}
async function crawlAsyncRec(params: {
dirPath: string;
2024-11-17 23:05:41 +01:00
onFileFound: (params: { filePath: string }) => Promise<void>;
2024-11-02 22:39:03 +01:00
}) {
const { dirPath, onFileFound } = params;
await Promise.all(
(await fsPr.readdir(dirPath)).map(async basename => {
const fileOrDirPath = pathJoin(dirPath, basename);
const isDirectory = await fsPr
.lstat(fileOrDirPath)
.then(stat => stat.isDirectory());
if (isDirectory) {
await crawlAsyncRec({ dirPath: fileOrDirPath, onFileFound });
return;
}
2024-11-17 23:05:41 +01:00
await onFileFound({ filePath: fileOrDirPath });
2024-11-02 22:39:03 +01:00
})
);
}