mirror of
https://github.com/renovatebot/renovate.git
synced 2025-01-14 16:46:25 +00:00
46 lines
1.3 KiB
TypeScript
46 lines
1.3 KiB
TypeScript
import fs from 'fs';
|
|
import { join, normalizeTrim } from 'upath';
|
|
|
|
function relatePath(here: string, there: string): string {
|
|
const thereParts = normalizeTrim(there).split(/[\\/]/);
|
|
const hereParts = normalizeTrim(here).split(/[\\/]/);
|
|
|
|
let idx = 0;
|
|
while (
|
|
typeof thereParts[idx] === 'string' &&
|
|
typeof hereParts[idx] === 'string' &&
|
|
thereParts[idx] === hereParts[idx]
|
|
) {
|
|
idx += 1;
|
|
}
|
|
|
|
const result = [];
|
|
for (let x = 0; x < hereParts.length - idx; x += 1) result.push('..');
|
|
for (let y = idx; y < thereParts.length; y += 1) result.push(thereParts[idx]);
|
|
return result.join('/');
|
|
}
|
|
|
|
export function loadModules<T>(
|
|
dirname: string,
|
|
validate?: (x: unknown) => x is T
|
|
): Record<string, T> {
|
|
const result: Record<string, T> = {};
|
|
|
|
const moduleNames: string[] = fs
|
|
.readdirSync(dirname, { withFileTypes: true })
|
|
.filter(dirent => dirent.isDirectory())
|
|
.map(dirent => dirent.name)
|
|
.filter(name => !name.startsWith('__'))
|
|
.sort();
|
|
|
|
for (const moduleName of moduleNames) {
|
|
const modulePath = join(relatePath(__dirname, dirname), moduleName);
|
|
const module = require(modulePath); // eslint-disable-line
|
|
// istanbul ignore if
|
|
if (!module || (validate && !validate(module)))
|
|
throw new Error(`Invalid module: ${modulePath}`);
|
|
result[moduleName] = module as T;
|
|
}
|
|
|
|
return result;
|
|
}
|