2023-07-06 16:09:48 -04:00
|
|
|
import fs from "fs";
|
|
|
|
import path from "path";
|
|
|
|
|
|
|
|
const MAX_DEPTH = 2;
|
|
|
|
|
2023-11-09 19:11:11 -05:00
|
|
|
export function collectAllFileSources(
|
|
|
|
fileOrDir: string,
|
|
|
|
ext?: string,
|
|
|
|
depth = 0,
|
|
|
|
): string[] {
|
2023-07-06 16:09:48 -04:00
|
|
|
const resolvedPath = path.resolve(fileOrDir);
|
|
|
|
|
|
|
|
if (depth >= MAX_DEPTH) {
|
2023-11-09 19:11:11 -05:00
|
|
|
console.warn(
|
|
|
|
`WARN: MAX_DEPTH of ${MAX_DEPTH} reached traversing "${resolvedPath}"`,
|
|
|
|
);
|
2023-07-06 16:09:48 -04:00
|
|
|
return [];
|
|
|
|
}
|
|
|
|
|
|
|
|
const stat = fs.statSync(resolvedPath);
|
|
|
|
|
2023-11-09 11:27:11 -08:00
|
|
|
if (stat.isFile() && (ext === null || path.extname(resolvedPath) === ext)) {
|
2023-07-06 16:09:48 -04:00
|
|
|
const contents = fs.readFileSync(resolvedPath);
|
|
|
|
return [`/* src: ${resolvedPath} */\n\n${contents}`];
|
|
|
|
}
|
|
|
|
|
2023-11-09 11:27:11 -08:00
|
|
|
if (stat.isDirectory()) {
|
2023-07-06 16:09:48 -04:00
|
|
|
const files = fs.readdirSync(resolvedPath);
|
2023-11-09 11:27:11 -08:00
|
|
|
return files.reduce((acc: string[], next: string) => {
|
2023-07-06 16:09:48 -04:00
|
|
|
const nextPath = path.join(fileOrDir, next);
|
|
|
|
return [...acc, ...collectAllFileSources(nextPath, ext, depth + 1)];
|
|
|
|
}, []);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (depth === 0) {
|
2023-11-09 19:11:11 -05:00
|
|
|
console.warn(
|
|
|
|
`WARN: The provided path "${resolvedPath}" is not a .js file or directory.`,
|
|
|
|
);
|
2023-07-06 16:09:48 -04:00
|
|
|
}
|
2023-11-09 11:27:11 -08:00
|
|
|
|
|
|
|
return [];
|
2023-07-06 16:09:48 -04:00
|
|
|
}
|