-
-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathindex.js
225 lines (204 loc) · 5.44 KB
/
index.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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// @ts-check
const {
packageJson,
install,
getExtsFromCommand,
uninstall,
} = require('mrm-core');
const { isUsingYarnBerry } = require('mrm-core/src/npm');
const { castArray } = require('lodash');
const husky = require('husky');
const packages = {
'lint-staged': '>=10',
husky: '>=7',
};
/**
* Default lint-staged rules
*
* @param name Name of the rule to match user overrides
* @param [condition] Function that returns true when the rule should be added
* @param extensions Default extension (if we can't infer them from an npm script)
* @param [script] Name of an npm script to infer extensions
* @param [param] Command line parameter of an npm script to infer extensions (for example, `ext` for `--ext`)
* @param command Command to run for a lint-staged rule
*/
const defaultRules = [
// ESLint
{
name: 'eslint',
condition: pkg => !!pkg.get('devDependencies.eslint'),
extensions: ['js'],
script: 'lint',
param: 'ext',
command: 'eslint --cache --fix',
},
// Stylelint
{
name: 'stylelint',
condition: pkg => !!pkg.get('devDependencies.stylelint'),
extensions: ['css'],
script: 'lint:css',
command: 'stylelint --fix',
},
// Prettier
{
name: 'prettier',
condition: pkg =>
!!pkg.get('devDependencies.prettier') &&
!pkg.get('devDependencies.eslint-plugin-prettier'),
extensions: ['js', 'css', 'md'],
script: 'format',
command: 'prettier --write',
},
];
/**
* Merge default rules with user overrides
*
* @param {Array} defaults
* @param {Object} overrides
*/
function mergeRules(defaults, overrides) {
// Overrides for default rules
const rulesWithOverrides = defaults.map(rule => ({
...rule,
...overrides[rule.name],
}));
// Custom rules
return Object.entries(overrides).reduce((acc, [name, rule]) => {
if (acc.some(x => x.name === name)) {
return acc;
}
return [...acc, rule];
}, rulesWithOverrides);
}
/**
* Convert an array of extensions to a glob pattern
*
* Example: ['js', 'ts'] -> '*.{js,ts}'
*
* @param {string[]} exts
*/
function extsToGlob(exts) {
if (exts.length > 1) {
return `*.{${exts}}`;
}
return `*.${exts}`;
}
/**
* Generate a regular expression to detect a rule in existing rules. For simplicity
* assumes that the first word in the command is the binary you're running.
*
* Example: 'eslint --fix' -> /\beslint\b/
*
* TODO: Allow overriding for more complex commands
*
* @param {string} command
*/
function getRuleRegExp(command) {
return new RegExp(`\\b${command.split(' ').shift()}\\b`);
}
/**
* Check if a given command belongs to a rule
*
* @param {string | string[]} ruleCommands
* @param {string} command
*/
function isCommandBelongsToRule(ruleCommands, command) {
const regExp = getRuleRegExp(command);
return castArray(ruleCommands).some(x => regExp.test(x));
}
module.exports = function task({ lintStagedRules }) {
const pkg = packageJson();
const allRules = mergeRules(defaultRules, lintStagedRules);
const existingRules = Object.entries(pkg.get('lint-staged', {}));
// Remove exising rules that run any of default commands
const commandsToRemove = allRules.map(rule => rule.command);
const existingRulesToKeep = existingRules.filter(([, ruleCommands]) =>
commandsToRemove
.map(command => isCommandBelongsToRule(ruleCommands, command))
.every(x => x === false)
);
// New rules
const rulesToAdd = allRules.map(
({
condition = () => true,
extensions: defaultExtensions,
script,
param,
command,
enabled = true,
}) => {
if (!enabled || !condition(pkg)) {
return null;
}
const extensions =
getExtsFromCommand(pkg.getScript(script), param) || defaultExtensions;
const pattern = extsToGlob(extensions);
return [pattern, command];
}
);
// Merge existing and new rules, clean up
const rulesToWrite = [...existingRulesToKeep, ...rulesToAdd].filter(Boolean);
// Merge rules with the same pattern and convert to an object
// Wrap commands in an array only when a pattern has multiple commands
const rules = {};
rulesToWrite.forEach(([pattern, command]) => {
if (rules[pattern]) {
rules[pattern] = [...castArray(rules[pattern]), command];
} else {
rules[pattern] = command;
}
});
if (Object.keys(rules).length === 0) {
const names = defaultRules.map(rule => rule.name);
console.log(
`\nCannot add lint-staged: only ${names.join(
', '
)} or custom rules are supported.`
);
return;
}
// package.json
pkg
// Remove husky 0.14 config
.unset('scripts.precommit')
// Remove husky 4 config
.unset('husky')
// Remove simple-git-hooks
.unset('simple-git-hooks')
// Add new config
.merge({
'lint-staged': rules,
});
if (isUsingYarnBerry()) {
// Yarn 2 doesn't support `prepare` lifecycle yet
// https://yarnpkg.com/advanced/lifecycle-scripts
pkg.appendScript('postinstall', 'husky install');
if (!pkg.get('private')) {
// In case package isn't private, pinst ensures that postinstall
// is disabled on publish
pkg
.appendScript('prepublishOnly', 'pinst --disable')
.appendScript('postpublish', 'pinst --enable');
packages.pinst = '>=2';
}
} else {
// npm, Yarn 1, pnpm
pkg.appendScript('prepare', 'husky install');
}
pkg.save();
uninstall('simple-git-hooks');
// Install dependencies
install(packages);
// Install husky
husky.install();
// Set lint-staged config
husky.add('.husky/pre-commit', 'npx lint-staged');
};
module.exports.description = 'Adds lint-staged';
module.exports.parameters = {
lintStagedRules: {
type: 'config',
default: {},
},
};