/
getConfigPath.ts
40 lines (37 loc) · 1.32 KB
/
getConfigPath.ts
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
import { promises as fs } from 'node:fs';
import { resolve } from 'node:path';
import { cwd } from 'node:process';
import { errorMissingExternalConfig } from '../../src/utils/error';
import { handleError } from '../logging';
const DEFAULT_CONFIG_BASE = 'rollup.config';
export async function getConfigPath(commandConfig: string | true): Promise<string> {
if (commandConfig === true) {
return resolve(await findConfigFileNameInCwd());
}
if (commandConfig.slice(0, 5) === 'node:') {
const packageName = commandConfig.slice(5);
try {
// eslint-disable-next-line unicorn/prefer-module
return require.resolve(`rollup-config-${packageName}`, { paths: [cwd()] });
} catch {
try {
// eslint-disable-next-line unicorn/prefer-module
return require.resolve(packageName, { paths: [cwd()] });
} catch (error: any) {
if (error.code === 'MODULE_NOT_FOUND') {
handleError(errorMissingExternalConfig(commandConfig));
}
throw error;
}
}
}
return resolve(commandConfig);
}
async function findConfigFileNameInCwd(): Promise<string> {
const filesInWorkingDirectory = new Set(await fs.readdir(cwd()));
for (const extension of ['mjs', 'cjs', 'ts']) {
const fileName = `${DEFAULT_CONFIG_BASE}.${extension}`;
if (filesInWorkingDirectory.has(fileName)) return fileName;
}
return `${DEFAULT_CONFIG_BASE}.js`;
}