-
-
Notifications
You must be signed in to change notification settings - Fork 222
/
expand-npm-wildcard.ts
75 lines (62 loc) · 2.75 KB
/
expand-npm-wildcard.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
import fs from 'fs';
import _ from 'lodash';
import { CommandInfo } from '../command';
import { CommandParser } from './command-parser';
const OMISSION = /\(!([^)]+)\)/;
/**
* Finds wildcards in npm/yarn/pnpm run commands and replaces them with all matching scripts in the
* `package.json` file of the current directory.
*/
export class ExpandNpmWildcard implements CommandParser {
static readPackage() {
try {
const json = fs.readFileSync('package.json', { encoding: 'utf-8' });
return JSON.parse(json);
} catch (e) {
return {};
}
}
private scripts?: string[];
constructor(private readonly readPackage = ExpandNpmWildcard.readPackage) {}
parse(commandInfo: CommandInfo) {
const [, npmCmd, cmdName, args] =
commandInfo.command.match(/(npm|yarn|pnpm) run (\S+)([^&]*)/) || [];
const wildcardPosition = (cmdName || '').indexOf('*');
// If the regex didn't match an npm script, or it has no wildcard,
// then we have nothing to do here
if (!cmdName || wildcardPosition === -1) {
return commandInfo;
}
if (!this.scripts) {
this.scripts = Object.keys(this.readPackage().scripts || {});
}
const omissionRegex = cmdName.match(OMISSION);
const cmdNameSansOmission = cmdName.replace(OMISSION, '');
const preWildcard = _.escapeRegExp(cmdNameSansOmission.slice(0, wildcardPosition));
const postWildcard = _.escapeRegExp(cmdNameSansOmission.slice(wildcardPosition + 1));
const wildcardRegex = new RegExp(`^${preWildcard}(.*?)${postWildcard}$`);
// If 'commandInfo.name' doesn't match 'cmdName', this means a custom name
// has been specified and thus becomes the prefix (as described in the README).
const prefix = commandInfo.name !== cmdName ? commandInfo.name : '';
return this.scripts
.map((script) => {
const match = script.match(wildcardRegex);
if (omissionRegex) {
const toOmit = script.match(new RegExp(omissionRegex[1]));
if (toOmit) {
return;
}
}
if (match) {
return {
...commandInfo,
command: `${npmCmd} run ${script}${args}`,
// Will use an empty command name if no prefix has been specified and
// the wildcard match is empty, e.g. if `npm:watch-*` matches `npm run watch-`.
name: prefix + match[1],
};
}
})
.filter((commandInfo): commandInfo is CommandInfo => !!commandInfo);
}
}