poku
Version:
🐷 Poku makes testing easy for Node.js, Bun, Deno, and you at the same time.
85 lines (84 loc) • 3.24 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.listFiles = exports.getAllFiles = exports.escapeRegExp = exports.isFile = exports.sanitizePath = void 0;
const promises_1 = require("fs/promises");
const node_path_1 = require("path");
const node_process_1 = require("process");
const poku_js_1 = require("../../configs/poku.js");
const regex = {
sep: /[/\\]+/g,
pathLevel: /(\.\.(\/|\\|$))+/g,
unusualChars: /[<>|^?*]+/g,
absolutePath: /^[/\\]/,
safeRegExp: /[.*{}[\]\\]/g,
defaultFilter: /\.(test|spec)\./i,
};
const sanitizePath = (input, ensureTarget) => {
const sanitizedPath = input
.replace(regex.sep, node_path_1.sep)
.replace(regex.pathLevel, '')
.replace(regex.unusualChars, '');
return ensureTarget
? sanitizedPath.replace(regex.absolutePath, `.${node_path_1.sep}`)
: sanitizedPath;
};
exports.sanitizePath = sanitizePath;
const isFile = async (fullPath) => (await (0, promises_1.stat)(fullPath)).isFile();
exports.isFile = isFile;
const escapeRegExp = (string) => string.replace(regex.safeRegExp, '\\$&');
exports.escapeRegExp = escapeRegExp;
const envFilter = node_process_1.env.FILTER?.trim()
? new RegExp((0, exports.escapeRegExp)(node_process_1.env.FILTER), 'i')
: undefined;
const getAllFiles = async (dirPath, files = new Set(), configs) => {
let isFullPath = false;
const currentFiles = await (async () => {
try {
if (await (0, exports.isFile)(dirPath)) {
isFullPath = true;
return [(0, exports.sanitizePath)(dirPath)];
}
return (0, promises_1.readdir)((0, exports.sanitizePath)(dirPath));
}
catch (error) {
console.error(error);
process.exit(1);
}
})();
const filter = (() => {
if (envFilter)
return envFilter;
if (configs?.filter instanceof RegExp)
return configs.filter;
return regex.defaultFilter;
})();
const exclude = (() => {
if (!configs?.exclude)
return undefined;
if (Array.isArray(configs.exclude))
return configs.exclude;
return [configs.exclude];
})();
await Promise.all(currentFiles.map(async (file) => {
const fullPath = isFullPath ? dirPath : (0, node_path_1.join)(dirPath, file);
const stat = await (0, promises_1.stat)(fullPath);
if (fullPath.indexOf('node_modules') !== -1 ||
fullPath.indexOf('.git/') !== -1)
return;
if (isFullPath && poku_js_1.states?.isSinglePath)
return files.add(fullPath);
if (exclude)
for (const pattern of exclude) {
if (pattern.test(fullPath))
return;
}
if (filter.test(fullPath))
return files.add(fullPath);
if (stat.isDirectory())
await (0, exports.getAllFiles)(fullPath, files, configs);
}));
return files;
};
exports.getAllFiles = getAllFiles;
const listFiles = async (targetDir, configs) => Array.from(await (0, exports.getAllFiles)((0, exports.sanitizePath)(targetDir), new Set(), configs));
exports.listFiles = listFiles;