-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.ts
102 lines (86 loc) · 2.88 KB
/
module.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import { resolve, basename, dirname } from 'path';
import { readJSONSync, existsSync, readFileSync } from 'fs-extra';
import { parse } from 'yaml';
import { execSync } from 'child_process';
import { toRegExp } from './language';
import { findUp } from './file';
export function packageNameOf(path: string) {
const list = resolve(path).split(/[/\\]+/);
path = list.slice(list.slice(-2)[0].startsWith('@') ? -2 : -1).join('/');
return path.toLowerCase().replace(/[^@/\w]+/g, '-');
}
/**
* @param map - Key for RegExp source, value for replacement
*
* @return Key for replacement, value for RegExp
*/
export function patternOf(map: Record<string, string>) {
const patternMap: Record<string, RegExp> = {};
for (const pattern in map) patternMap[map[pattern]] = toRegExp(pattern);
for (const key in patternMap) return patternMap;
}
export function currentModulePath() {
try {
throw Error();
} catch (error) {
return (error as Error).stack
?.split(/[\r\n]+/)[2]
.match(/at .+?\((.+):\d+:\d+\)/)[1]
.replace(/\\/g, '/');
}
}
export function packageOf(path = './'): {
path: string;
meta: Record<string, any>;
} {
for (const file of findUp(path))
if (basename(file) === 'package.json')
return {
path: dirname(file),
meta: readJSONSync(file)
};
}
/**
* Get configuration of a Package from
* `package.json`, `.${name}.json` or `.${name}.yml` in `process.cwd()`
*
* (`process.env.NODE_ENV` will affect the result)
*/
export function configOf(name: string): Record<string, any> {
let config = packageOf('./test')?.meta?.[name];
if (!config)
for (const type of ['json', 'yaml', 'yml'])
if (existsSync((name = `./.${name}.${type}`))) {
switch (type) {
case 'json':
config = readJSONSync(name);
break;
case 'yaml':
case 'yml':
config = parse(readFileSync(name) + '');
}
break;
}
return config?.env?.[process.env.NODE_ENV] || config;
}
export function getNPMConfig(
key: string
): string | Record<string, any> | undefined {
const value = (execSync(`npm get ${key}`) + '').trim();
if (value !== 'undefined')
try {
return JSON.parse(value);
} catch {
return value;
}
}
/**
* @see {@link https://github.blog/changelog/2022-10-24-npm-v9-0-0-released/#:~:text=npm%20config%20set%20will%20no%20longer%20accept%20deprecated%20or%20invalid%20config%20options}
*/
export function setNPMConfig(key: string, value: any) {
const data = JSON.stringify(value);
execSync(
value != null ? `npm set ${key} ${data}` : `npm config delete ${key}`
);
console.info(`${key} = ${data}`);
}