-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathload-user-config.ts
More file actions
50 lines (41 loc) · 1.36 KB
/
load-user-config.ts
File metadata and controls
50 lines (41 loc) · 1.36 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
import path from 'node:path';
import { cosmiconfig } from 'cosmiconfig';
import { ZodError } from 'zod';
import { fromZodError } from 'zod-validation-error';
import { type UserConfig, UserConfigSchema } from './schema.js';
const explorer = cosmiconfig('codeowners');
type LoadUserConfigReturn = {
configPath: string;
userConfig: UserConfig;
};
export async function loadUserConfig(
rootDir: string,
configRelativePath?: string,
): Promise<LoadUserConfigReturn> {
try {
const result = configRelativePath
? await explorer.load(path.resolve(rootDir, configRelativePath))
: await explorer.search();
if (!result) {
throw new Error('no such file or directory');
}
return {
configPath: result.filepath,
userConfig: UserConfigSchema.parse(result?.config ?? {}),
};
} catch (error: unknown) {
let message = 'An unexpected error occurred.';
if (error instanceof ZodError) {
const validationError = fromZodError(error as ZodError);
message = validationError.message;
} else if (error instanceof Error) {
if (error.message.includes('no such file or directory')) {
message =
'Config file not found. Please ensure to point a valid config file path or create a new one with the init command.';
} else {
message = error.message;
}
}
throw new Error(message);
}
}