2020-02-16 04:57:12 +00:00
|
|
|
import fs from 'fs';
|
2021-12-22 08:37:47 +00:00
|
|
|
import upath from 'upath';
|
2021-10-27 14:37:11 +00:00
|
|
|
import { regEx } from './regex';
|
2020-02-16 04:57:12 +00:00
|
|
|
|
|
|
|
function relatePath(here: string, there: string): string {
|
2021-12-22 08:37:47 +00:00
|
|
|
const thereParts = upath.normalizeTrim(there).split(regEx(/[\\/]/));
|
|
|
|
const hereParts = upath.normalizeTrim(here).split(regEx(/[\\/]/));
|
2020-02-16 04:57:12 +00:00
|
|
|
|
|
|
|
let idx = 0;
|
|
|
|
while (
|
|
|
|
typeof thereParts[idx] === 'string' &&
|
|
|
|
typeof hereParts[idx] === 'string' &&
|
|
|
|
thereParts[idx] === hereParts[idx]
|
|
|
|
) {
|
|
|
|
idx += 1;
|
|
|
|
}
|
|
|
|
|
|
|
|
const result = [];
|
2020-03-17 11:15:22 +00:00
|
|
|
for (let x = 0; x < hereParts.length - idx; x += 1) {
|
|
|
|
result.push('..');
|
|
|
|
}
|
|
|
|
for (let y = idx; y < thereParts.length; y += 1) {
|
2022-03-03 09:35:26 +00:00
|
|
|
result.push(thereParts[y]);
|
2020-03-17 11:15:22 +00:00
|
|
|
}
|
2020-02-16 04:57:12 +00:00
|
|
|
return result.join('/');
|
|
|
|
}
|
|
|
|
|
|
|
|
export function loadModules<T>(
|
|
|
|
dirname: string,
|
2020-04-08 07:14:32 +00:00
|
|
|
validate?: (module: T, moduleName?: string) => boolean,
|
|
|
|
filter: (moduleName?: string) => boolean = () => true
|
2020-02-16 04:57:12 +00:00
|
|
|
): Record<string, T> {
|
|
|
|
const result: Record<string, T> = {};
|
|
|
|
|
|
|
|
const moduleNames: string[] = fs
|
|
|
|
.readdirSync(dirname, { withFileTypes: true })
|
2020-04-12 16:09:36 +00:00
|
|
|
.filter((dirent) => dirent.isDirectory())
|
|
|
|
.map((dirent) => dirent.name)
|
|
|
|
.filter((name) => !name.startsWith('__'))
|
2020-04-08 07:14:32 +00:00
|
|
|
.filter(filter)
|
2020-02-16 04:57:12 +00:00
|
|
|
.sort();
|
|
|
|
|
|
|
|
for (const moduleName of moduleNames) {
|
2021-12-22 08:37:47 +00:00
|
|
|
const modulePath = upath.join(relatePath(__dirname, dirname), moduleName);
|
2020-02-16 04:57:12 +00:00
|
|
|
const module = require(modulePath); // eslint-disable-line
|
|
|
|
// istanbul ignore if
|
2020-03-17 11:15:22 +00:00
|
|
|
if (!module || (validate && !validate(module, moduleName))) {
|
2020-02-16 04:57:12 +00:00
|
|
|
throw new Error(`Invalid module: ${modulePath}`);
|
2020-03-17 11:15:22 +00:00
|
|
|
}
|
2020-02-16 04:57:12 +00:00
|
|
|
result[moduleName] = module as T;
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|