-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
check-pkg-for-release.js
396 lines (350 loc) · 14.6 KB
/
check-pkg-for-release.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/**
* @license
* Copyright 2016 Google Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* @fileoverview Used within pre-release.sh, this checks a component's package.json
* to ensure that if it's a new component (version = "0.0.0"), it will have a proper
* "publishConfig.access" property set to "public".
* The argument should be the package.json file to check.
*/
const assert = require('assert');
const fs = require('fs');
const readDirRecursive = require('fs-readdir-recursive');
const path = require('path');
const childProcess = require('child_process');
const {default: traverse} = require('babel-traverse');
const camelCase = require('camel-case');
const recast = require('recast');
const typescriptParser = require('recast/parsers/typescript');
const CLI_PACKAGE_JSON_RELATIVE_PATH = process.argv[2];
if (!CLI_PACKAGE_JSON_RELATIVE_PATH) {
console.error(`Usage: node ${path.basename(process.argv[1])} packages/mdc-foo/package.json`);
process.exit(1);
}
const PACKAGE_RELATIVE_PATH = CLI_PACKAGE_JSON_RELATIVE_PATH.replace('package.json', '');
if (!new RegExp('packages/[^/]+/package.json$').test(CLI_PACKAGE_JSON_RELATIVE_PATH)) {
console.error(`Invalid argument: "${CLI_PACKAGE_JSON_RELATIVE_PATH}" is not a valid path to a package.json file.`);
console.error('Expected format: packages/mdc-foo/package.json');
process.exit(1);
}
const CLI_PACKAGE_JSON = require(path.resolve(CLI_PACKAGE_JSON_RELATIVE_PATH));
const WEBPACK_CONFIG_RELATIVE_PATH = 'webpack.config.js';
const WEBPACK_CONFIG = require(path.resolve(WEBPACK_CONFIG_RELATIVE_PATH));
const MASTER_TS_RELATIVE_PATH = 'packages/material-components-web/index.ts';
const MASTER_CSS_RELATIVE_PATH = 'packages/material-components-web/material-components-web.scss';
const MASTER_PACKAGE_JSON_RELATIVE_PATH = 'packages/material-components-web/package.json';
const MASTER_PACKAGE_JSON = require(path.resolve(MASTER_PACKAGE_JSON_RELATIVE_PATH));
// These few MDC packages work as foundation or utility packages, and are not
// directly included in webpack or the material-component-web module. But they
// are necessary since other MDC packages depend on them.
const CSS_EXCLUDES = new Set([
'base',
'animation',
'auto-init',
'density',
'dom',
'feature-targeting',
'focus',
'focus-ring',
'progress-indicator',
'rtl',
'shape',
'tokens',
'touch-target',
]);
const JS_EXCLUDES = new Set([
'animation',
'progress-indicator',
'tokens',
'chips', // Temporarily added during deprecation migration.
]);
const NOT_AUTOINIT = new Set([
'auto-init',
'base',
'dom',
'progress-indicator',
'tab', // Only makes sense in context of tab-bar
'tab-indicator', // Only makes sense in context of tab-bar
'tab-scroller', // Only makes sense in context of tab-bar
]);
main();
function main() {
checkPublicConfigForNewComponent();
if (CLI_PACKAGE_JSON.name !== MASTER_PACKAGE_JSON.name) {
if (CLI_PACKAGE_JSON.private) {
console.log('Skipping private component', CLI_PACKAGE_JSON.name);
} else {
checkDependencyAddedInWebpackConfig();
checkDependencyAddedInMDCPackage();
checkUsedDependenciesMatchDeclaredDependencies();
}
}
}
function checkPublicConfigForNewComponent() {
if (CLI_PACKAGE_JSON.version === '0.0.0') {
assert.notEqual(typeof CLI_PACKAGE_JSON.publishConfig, 'undefined',
'Please add publishConfig to' + CLI_PACKAGE_JSON.name + '\'s package.json. Consult our ' +
'docs/authoring-components.md to ensure your component\'s package.json ' +
'is well-formed.');
assert.equal(CLI_PACKAGE_JSON.publishConfig.access, 'public',
'Please set publishConfig.access to "public" in ' + CLI_PACKAGE_JSON.name + '\'s package.json. ' +
'Consult our docs/authoring-components.md to ensure your component\'s package.json ' +
'is well-formed.');
}
}
function checkDependencyAddedInWebpackConfig() {
// Check if css has been added to webpack config
checkCSSDependencyAddedInWebpackConfig();
// Check if js component has been added to webpack config
if (typeof(CLI_PACKAGE_JSON.main) !== 'undefined') {
checkJSDependencyAddedInWebpackConfig();
}
}
function checkJSDependencyAddedInWebpackConfig() {
const name = getPkgName();
if (JS_EXCLUDES.has(name)) {
return;
}
const jsconfig = WEBPACK_CONFIG.find((value) => {
return value.name === 'main-js-a-la-carte';
});
const pkgName = CLI_PACKAGE_JSON.name.replace('@material/', '');
assert.notEqual(typeof jsconfig.entry[pkgName], 'undefined',
'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' javascript dependency is not added to webpack ' +
'configuration. Please add ' + pkgName + ' to ' + WEBPACK_CONFIG_RELATIVE_PATH + '\'s js-components ' +
'entry before commit. If package @material/' + name + ' has no exported JS, add "' + name + '" to ' +
'the JS_EXCLUDES set in this file.');
}
function checkCSSDependencyAddedInWebpackConfig() {
const name = getPkgName();
if (CSS_EXCLUDES.has(name)) {
return;
}
const cssconfig = WEBPACK_CONFIG.find((value) => {
return value.name === 'main-css-a-la-carte';
});
const nameMDC = CLI_PACKAGE_JSON.name.replace('@material/', 'mdc.');
assert.notEqual(typeof cssconfig.entry[nameMDC], 'undefined',
'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' css dependency not added to webpack ' +
'configuration. Please add ' + name + ' to ' + WEBPACK_CONFIG_RELATIVE_PATH + '\'s css ' +
'entry before commit. If package @material/' + name + ' exports no concrete Sass, add ' +
'"' + name + '" to the CSS_EXCLUDES set in this file.');
}
function checkDependencyAddedInMDCPackage() {
// Package is added to package.json
checkPkgDependencyAddedInMDCPackage();
// SCSS is added to @import rule
checkCSSDependencyAddedInMDCPackage();
// If any, foundation is added to index and autoInit
checkJSDependencyAddedInMDCPackage();
}
function checkPkgDependencyAddedInMDCPackage() {
const name = getPkgName();
if (CSS_EXCLUDES.has(name) && JS_EXCLUDES.has(name)) {
return;
}
assert.notEqual(typeof MASTER_PACKAGE_JSON.dependencies[CLI_PACKAGE_JSON.name], 'undefined',
'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' is not a dependency for MDC Web. ' +
'Please add ' + CLI_PACKAGE_JSON.name +' to ' + MASTER_PACKAGE_JSON_RELATIVE_PATH +
'\' dependencies before commit.');
}
function checkCSSDependencyAddedInMDCPackage() {
const name = getPkgName();
if (CSS_EXCLUDES.has(name)) {
return;
}
const src = fs.readFileSync(path.join(process.env.PWD, MASTER_CSS_RELATIVE_PATH), 'utf8');
const shouldImportCSS = !!src.match(`${CLI_PACKAGE_JSON.name}/`);
assert(shouldImportCSS,
'FAILURE: Component ' + CLI_PACKAGE_JSON.name + ' is not being imported in MDC Web. ' +
'Please add ' + name + ' to ' + MASTER_CSS_RELATIVE_PATH + ' import rule before commit.');
}
function checkJSDependencyAddedInMDCPackage() {
const name = getPkgName();
if (typeof (CLI_PACKAGE_JSON.main) === 'undefined' || JS_EXCLUDES.has(name)) {
return;
}
const nameCamel = camelCase(CLI_PACKAGE_JSON.name.replace('@material/', ''));
const src = fs.readFileSync(path.join(process.env.PWD, MASTER_TS_RELATIVE_PATH), 'utf8');
const ast = recast.parse(src, {parser: typescriptParser});
assert(checkComponentImportedAddedInMDCPackage(ast), 'FAILURE: Component ' +
CLI_PACKAGE_JSON.name + ' is not being imported in MDC Web. ' + 'Please add ' + nameCamel +
' to '+ MASTER_TS_RELATIVE_PATH + ' import rule before commit.');
assert(checkComponentExportedAddedInMDCPackage(ast), 'FAILURE: Component ' +
CLI_PACKAGE_JSON.name + ' is not being exported in MDC Web. ' + 'Please add ' + nameCamel +
' to '+ MASTER_TS_RELATIVE_PATH + ' export before commit.');
if (!NOT_AUTOINIT.has(name)) {
assert(checkAutoInitAddedInMDCPackage(ast) > 0, 'FAILURE: Component ' +
CLI_PACKAGE_JSON.name + ' seems not being auto inited in MDC Web. ' + 'Please add ' +
nameCamel + ' to '+ MASTER_TS_RELATIVE_PATH + ' autoInit statement before commit.');
}
}
function checkComponentImportedAddedInMDCPackage(ast) {
let isImported = false;
traverse(ast, {
'ImportDeclaration'({node}) {
if (node.source) {
const source = node.source.value;
const pkgFile = CLI_PACKAGE_JSON.name + '/index';
if (source === pkgFile) {
isImported = true;
}
}
},
});
return isImported;
}
function checkAutoInitAddedInMDCPackage(ast) {
let nameCamel = camelCase(CLI_PACKAGE_JSON.name.replace('@material/', ''));
if (nameCamel === 'textfield') {
nameCamel = 'textField';
} else if (nameCamel === 'switch') {
nameCamel = 'switchControl';
}
let autoInitedCount = 0;
traverse(ast, {
'ExpressionStatement'({node}) {
const callee = node.expression.callee;
const args = node.expression.arguments;
if (callee.object.name === 'autoInit' && callee.property.name === 'register') {
for (let value of args) {
// When searching for a MemberExpression, if a typescript "as a"
// expression is found, recursively search its expression, since TS
// may define something "as a" multiple times.
//
// Example: object.foo as unknown as any as Interface
while (value.type === 'TSAsExpression') {
value = value.expression;
}
// For the given ExpressionStatement node whose callee name is
// "autoInit" and call property name is "register":
//
// autoInit.register('MDCCheckbox', checkbox.MDCCheckbox);
//
// We are searching the arguments provided to the expression to find
// the object with the package name ("checkbox" in the example).
// These node expression types which access an object's members are
// called MemberExpressions. The name of the object should be the
// package name.
if (value.type === 'MemberExpression' && value.object.name === nameCamel) {
autoInitedCount++;
break;
}
}
}
},
});
return autoInitedCount;
}
function checkComponentExportedAddedInMDCPackage(ast) {
let nameCamel = camelCase(CLI_PACKAGE_JSON.name.replace('@material/', ''));
if (nameCamel === 'textfield') {
nameCamel = 'textField';
} else if (nameCamel === 'switch') {
nameCamel = 'switchControl';
}
let isExported = false;
traverse(ast, {
'ExportNamedDeclaration'({node}) {
if (node.specifiers) {
if (node.specifiers.find((value) => {
return value.exported.name === nameCamel;
})) {
isExported = true;
}
}
},
});
return isExported;
}
/**
* Checks that all dependencies used in SASS and TypeScript files in the package
* match up with those declared in package.json.
*
* @throws {AssertionError} Will throw an error if dependencies do not strictly match.
*/
function checkUsedDependenciesMatchDeclaredDependencies() {
const files = readDirRecursive(
PACKAGE_RELATIVE_PATH,
(fileName) => {
return fileName[0] !== '.'
&& fileName !== 'node_modules' && fileName !== 'test';
},
);
const usedDeps = new Set();
const importMatcher = RegExp('(@use|@import|from) ["\'](@material/[^/"\']+)', 'g');
files.forEach((file) => {
if (file.endsWith('.scss') || file.endsWith('.ts') && !file.endsWith('.d.ts')) {
const src = fs.readFileSync(path.join(PACKAGE_RELATIVE_PATH, file), 'utf8');
while ((dep = importMatcher.exec(src)) !== null) {
usedDeps.add(dep[2]);
}
}
});
const declaredDeps = new Set(
Object.keys(CLI_PACKAGE_JSON.dependencies ? CLI_PACKAGE_JSON.dependencies : [])
.filter((key) => key.startsWith('@material/')));
const usedButNotDeclared = [...usedDeps].filter((x) => !declaredDeps.has(x));
const declaredButNotUsed = [...declaredDeps].filter((x) => !usedDeps.has(x));
assert.equal(usedButNotDeclared.length, 0, getMissingDependencyMsg(usedButNotDeclared));
assert.equal(declaredButNotUsed.length, 0, getUnusedDependencyMsg(declaredButNotUsed));
}
function getPkgName() {
let name = CLI_PACKAGE_JSON.name.split('/')[1];
if (name === 'textfield') {
// Text-field now has a dash in the name. The package cannot be changed,
// since it is a lot of effort to rename npm package
name = 'text-field';
}
return name;
}
function getMissingDependencyMsg(missingDeps) {
const missingDepsWithVersions = getPackageNamesWithVersions(missingDeps);
let msg = 'FAILURE: The following MDC dependencies were used in ' +
CLI_PACKAGE_JSON.name + ' but were not declared in its package.json:\n' +
missingDepsWithVersions.join('\n') +
'\n\nPlease add the missing dependencies to package.json manually, or by ' +
'running the following command(s) on the root of the repository:\n';
missingDepsWithVersions.forEach((dep) => {
msg += `npx lerna add ${dep} packages/${PACKAGE_RELATIVE_PATH.split('/')[1]}\n`;
});
return msg;
}
function getUnusedDependencyMsg(unusedDeps) {
let msg = 'FAILURE: The following MDC dependencies in package ' +
CLI_PACKAGE_JSON.name + ' are declared in its package.json but not used:\n' +
unusedDeps.join('\n') +
'\n\nPlease remove the unused dependencies in package.json manually, or ' +
'by running the following command(s) on the root of the repository:\n';
unusedDeps.forEach((dep) => {
msg += `npx lerna exec --scope ${CLI_PACKAGE_JSON.name} -- npm uninstall --no-shrinkwrap ${dep}\n`;
});
return msg;
}
function getPackageNamesWithVersions(packageNames) {
const packageNamesWithVersions = [];
packageNames.forEach((name) => {
const version = childProcess.execSync(`npm show ${name} version`).toString().replace('\n', '');
packageNamesWithVersions.push(`${name}@${version}`);
});
return packageNamesWithVersions;
}