-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathread-rc-file.ts
More file actions
64 lines (55 loc) · 1.51 KB
/
read-rc-file.ts
File metadata and controls
64 lines (55 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import path from 'node:path';
import {
CONFIG_FILE_NAME,
type CoreConfig,
SUPPORTED_CONFIG_FILE_FORMATS,
coreConfigSchema,
validate,
} from '@code-pushup/models';
import { fileExists, importModule } from '@code-pushup/utils';
export class ConfigPathError extends Error {
constructor(configPath: string) {
super(`Provided path '${configPath}' is not valid.`);
}
}
export async function readRcByPath(
filePath: string,
tsconfig?: string,
): Promise<CoreConfig> {
if (filePath.length === 0) {
throw new Error('The path to the configuration file is empty.');
}
if (!(await fileExists(filePath))) {
throw new ConfigPathError(filePath);
}
const cfg: CoreConfig = await importModule({
filepath: filePath,
tsconfig,
format: 'esm',
});
return validate(coreConfigSchema, cfg, { filePath });
}
export async function autoloadRc(tsconfig?: string): Promise<CoreConfig> {
// eslint-disable-next-line functional/no-let
let ext = '';
// eslint-disable-next-line functional/no-loop-statements
for (const extension of SUPPORTED_CONFIG_FILE_FORMATS) {
const filePath = `${CONFIG_FILE_NAME}.${extension}`;
const exists = await fileExists(filePath);
if (exists) {
ext = extension;
break;
}
}
if (!ext) {
throw new Error(
`No file ${CONFIG_FILE_NAME}.(${SUPPORTED_CONFIG_FILE_FORMATS.join(
'|',
)}) present in ${process.cwd()}`,
);
}
return readRcByPath(
path.join(process.cwd(), `${CONFIG_FILE_NAME}.${ext}`),
tsconfig,
);
}