-
Notifications
You must be signed in to change notification settings - Fork 3
/
find-config-file-path.js
54 lines (40 loc) · 1.4 KB
/
find-config-file-path.js
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
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { DEFAULT_CONFIG_FILENAME } from './constants.js';
import { logErrorAndExit } from './log.js';
const defaultDirectoryPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const defaultConfigPath = path.join(defaultDirectoryPath, DEFAULT_CONFIG_FILENAME);
export async function findConfigFilePath(providedConfigPath) {
if (providedConfigPath) {
const resolvedPath = path.resolve(providedConfigPath);
try {
const stat = await fs.promises.stat(resolvedPath);
if (!stat.isFile()) {
logErrorAndExit('Config path must point to a file');
}
return resolvedPath;
} catch {
logErrorAndExit(`Config file not exists: ${resolvedPath}`);
}
}
let currentDirectoryPath = path.resolve(process.cwd());
while (true) {
const currentConfigPath = path.join(currentDirectoryPath, DEFAULT_CONFIG_FILENAME);
try {
const stat = await fs.promises.stat(currentConfigPath); // eslint-disable-line no-await-in-loop
if (stat.isFile()) {
return currentConfigPath;
}
} catch {
// File not found, continue searching
}
const parentDirectoryPath = path.dirname(currentDirectoryPath);
if (parentDirectoryPath === currentDirectoryPath) {
// Reached the root of the file system
break;
}
currentDirectoryPath = parentDirectoryPath;
}
return defaultConfigPath;
}