@carlosv2/glue
Version:
Dependency injection library that stays out of the way
55 lines (54 loc) • 1.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.glob = glob;
exports.getFullPath = getFullPath;
exports.fileExists = fileExists;
exports.isFile = isFile;
const node_fs_1 = require("node:fs");
const node_path_1 = require("node:path");
function* iterateFiles(base) {
const entries = [base];
while (entries.length > 0) {
const entry = entries.shift();
if ((0, node_fs_1.lstatSync)(entry).isDirectory()) {
for (const path of (0, node_fs_1.readdirSync)(entry)) {
entries.push(`${entry}/${path}`);
}
}
else {
yield entry;
}
}
}
function glob(pattern) {
let base = pattern;
if (base.indexOf('*')) {
base = base.split('*')[0].replace(/\/[^/]*$/, '');
}
const sanitisedPattern = pattern
.replace('.', '\\.')
.replace(/\*\*\//g, '(?:.+/)?')
.replace(/\*/g, '[^/]+');
const regex = new RegExp(`^${sanitisedPattern}$`);
const entries = [];
for (const entry of iterateFiles(base)) {
if (regex.exec(entry)) {
entries.push(entry);
}
}
return entries;
}
function getFullPath(baseFile, relative) {
return (0, node_path_1.join)((0, node_path_1.dirname)(baseFile), relative);
}
function fileExists(path) {
// If the path points to a file, then we found it
if (isFile(path)) {
return true;
}
// If the folder has an `index.js` or `index.ts`, this is path we wanted
return isFile((0, node_path_1.join)(path, 'index.js')) || isFile((0, node_path_1.join)(path, 'index.ts'));
}
function isFile(path) {
return (0, node_fs_1.existsSync)(path) && (0, node_fs_1.lstatSync)(path).isFile();
}