-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathhygiene.js
412 lines (365 loc) · 11.3 KB
/
hygiene.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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
const filter = require('gulp-filter');
const es = require('event-stream');
const VinylFile = require('vinyl');
const vfs = require('vinyl-fs');
const path = require('path');
const fs = require('fs');
const pall = require('p-all');
// --- Start Positron ---
const colors = require('colors');
// --- End Positron ---
const { all, copyrightFilter, unicodeFilter, indentationFilter, tsFormattingFilter, eslintFilter, stylelintFilter } = require('./filters');
const copyrightHeaderLines = [
'/*---------------------------------------------------------------------------------------------',
' * Copyright (c) Microsoft Corporation. All rights reserved.',
' * Licensed under the MIT License. See License.txt in the project root for license information.',
' *--------------------------------------------------------------------------------------------*/',
];
// --- Start Positron ---
const positCopyrightHeaderLines = [
/\/\*---------------------------------------------------------------------------------------------\s*/g,
/ \* Copyright \([cC]{1}\)\s?(20\d{2})?(-20\d{2})? Posit Software, PBC\.( All rights reserved\.)?\s*/g,
/ \* Licensed under the Elastic License 2\.0\. See LICENSE\.txt for license information\.\s*/g,
/ \*--------------------------------------------------------------------------------------------\*\/\s*/g,
];
const positCopyrightHeaderLinesHash = [
/# ---------------------------------------------------------------------------------------------\s*/g,
/# Copyright \([cC]{1}\)\s?(20\d{2})?(-20\d{2})? Posit Software, PBC\.( All rights reserved\.)?\s*/g,
/# Licensed under the Elastic License 2\.0\. See LICENSE\.txt for license information\.\s*/g,
/# ---------------------------------------------------------------------------------------------\s*/g,
];
// --- End Positron ---
// --- Start Positron ---
function hygiene(some, linting = true, secrets = true) {
// --- End Positron ---
const eslint = require('./gulp-eslint');
const gulpstylelint = require('./stylelint');
const formatter = require('./lib/formatter');
// --- Start Positron ---
const detectSecretsHook = require('./detect-secrets-hook');
const detectDotOnlyHook = require('./detect-dot-only-hook');
// --- End Positron ---
let errorCount = 0;
const productJson = es.through(function (file) {
const product = JSON.parse(file.contents.toString('utf8'));
this.emit('data', file);
});
const unicode = es.through(function (file) {
const lines = file.contents.toString('utf8').split(/\r\n|\r|\n/);
file.__lines = lines;
const allowInComments = lines.some(line => /allow-any-unicode-comment-file/.test(line));
let skipNext = false;
lines.forEach((line, i) => {
if (/allow-any-unicode-next-line/.test(line)) {
skipNext = true;
return;
}
if (skipNext) {
skipNext = false;
return;
}
// If unicode is allowed in comments, trim the comment from the line
if (allowInComments) {
if (line.match(/\s+(\*)/)) { // Naive multi-line comment check
line = '';
} else {
const index = line.indexOf('\/\/');
line = index === -1 ? line : line.substring(0, index);
}
}
// Please do not add symbols that resemble ASCII letters!
// eslint-disable-next-line no-misleading-character-class
const m = /([^\t\n\r\x20-\x7E⊃⊇✔︎✓🎯⚠️🛑🔴🚗🚙🚕🎉✨❗⇧⌥⌘×÷¦⋯…↑↓→→←↔⟷·•●◆▼⟪⟫┌└├⏎↩√φ]+)/g.exec(line);
if (m) {
console.error(
file.relative + `(${i + 1},${m.index + 1}): Unexpected unicode character: "${m[0]}" (charCode: ${m[0].charCodeAt(0)}). To suppress, use // allow-any-unicode-next-line`
);
errorCount++;
}
});
this.emit('data', file);
});
const indentation = es.through(function (file) {
const lines = file.__lines || file.contents.toString('utf8').split(/\r\n|\r|\n/);
file.__lines = lines;
lines.forEach((line, i) => {
if (/^\s*$/.test(line)) {
// empty or whitespace lines are OK
} else if (/^[\t]*[^\s]/.test(line)) {
// good indent
} else if (/^[\t]* \*/.test(line)) {
// block comment using an extra space
} else {
// --- Start Positron ---
console.error(
file.relative + '(' + (i + 1) + ',1): ' + 'Bad whitespace indentation'.magenta
);
// --- End Positron ---
errorCount++;
}
});
this.emit('data', file);
});
// --- Start Positron ---
// const copyrights = es.through(function (file) {
// const lines = file.__lines;
//
// for (let i = 0; i < copyrightHeaderLines.length; i++) {
// if (lines[i] !== copyrightHeaderLines[i]) {
// console.error(file.relative + ': Missing or bad copyright statement');
// errorCount++;
// break;
// }
// }
//
// this.emit('data', file);
// });
const copyrights = es.through(function (file) {
const lines = file.__lines;
const matchHeaderLines = (headerLines) => {
for (let i = 0; i < headerLines.length; i++) {
if (headerLines[i] !== lines[i]) {
return false;
}
}
return true;
};
const regexMatchHeaderLines = (headerLines) => {
for (let i = 0; i < headerLines.length; i++) {
if (!lines[i]?.match(headerLines[i])) {
return false;
}
}
return true;
};
if (!(matchHeaderLines(copyrightHeaderLines) ||
regexMatchHeaderLines(positCopyrightHeaderLines) ||
regexMatchHeaderLines(positCopyrightHeaderLinesHash))) {
console.error(file.relative + ': ' + 'Missing or bad copyright statement'.magenta);
errorCount++;
}
this.emit('data', file);
});
const testDataFiles = filter(['**/*', '!**/*.csv', '!**/*.parquet'], { restore: true });
// --- End Positron ---
const formatting = es.map(function (file, cb) {
try {
const rawInput = file.contents.toString('utf8');
const rawOutput = formatter.format(file.path, rawInput);
const original = rawInput.replace(/\r\n/gm, '\n');
const formatted = rawOutput.replace(/\r\n/gm, '\n');
if (original !== formatted) {
// --- Start Positron ---
console.error(
file.relative + ': ' +
`File not formatted. Run the 'Format Document' command to fix it`.magenta
);
// --- End Positron ---
errorCount++;
}
cb(null, file);
} catch (err) {
cb(err);
}
});
let input;
if (Array.isArray(some) || typeof some === 'string' || !some) {
const options = { base: '.', follow: true, allowEmpty: true };
if (some) {
input = vfs.src(some, options).pipe(filter(all)); // split this up to not unnecessarily filter all a second time
} else {
input = vfs.src(all, options);
}
} else {
input = some;
}
const productJsonFilter = filter('product.json', { restore: true });
const snapshotFilter = filter(['**', '!**/*.snap', '!**/*.snap.actual']);
const yarnLockFilter = filter(['**', '!**/yarn.lock']);
const unicodeFilterStream = filter(unicodeFilter, { restore: true });
const result = input
.pipe(filter((f) => !f.stat.isDirectory()))
.pipe(snapshotFilter)
// --- Start Positron ---
.pipe(testDataFiles)
// --- End Positron ---
.pipe(yarnLockFilter)
.pipe(productJsonFilter)
.pipe(process.env['BUILD_SOURCEVERSION'] ? es.through() : productJson)
.pipe(productJsonFilter.restore)
.pipe(unicodeFilterStream)
.pipe(unicode)
.pipe(unicodeFilterStream.restore)
.pipe(filter(indentationFilter))
.pipe(indentation)
.pipe(filter(copyrightFilter))
.pipe(copyrights);
const streams = [
result.pipe(filter(tsFormattingFilter)).pipe(formatting)
];
if (linting) {
streams.push(
result
.pipe(filter(eslintFilter))
.pipe(
eslint((results) => {
errorCount += results.warningCount;
errorCount += results.errorCount;
})
)
);
streams.push(
result.pipe(filter(stylelintFilter)).pipe(gulpstylelint(((message, isError) => {
if (isError) {
console.error(message);
errorCount++;
} else {
console.warn(message);
}
})))
);
// --- Start Positron ---
streams.push(
detectDotOnlyHook(((message, isError) => {
if (isError) {
console.error(message);
errorCount++;
} else {
console.warn(message);
}
}))
);
// --- End Positron ---
}
// --- Start Positron ---
if (secrets) {
streams.push(
detectSecretsHook(((message, isError) => {
if (isError) {
console.error(message);
errorCount++;
} else {
console.warn(message);
}
}))
);
}
// --- End Positron ---
let count = 0;
return es.merge(...streams).pipe(
es.through(
function (data) {
count++;
if (process.env['TRAVIS'] && count % 10 === 0) {
process.stdout.write('.');
}
this.emit('data', data);
// --- Start Positron ---
if (errorCount > 0) {
this.emit('error', `Hygiene failed with ${errorCount} errors`.red);
}
// --- End Positron ---
},
function () {
process.stdout.write('\n');
if (errorCount > 0) {
this.emit(
'error',
'Hygiene failed with ' +
errorCount +
` errors. Check 'build / gulpfile.hygiene.js'.`
);
} else {
this.emit('end');
}
}
)
);
}
module.exports.hygiene = hygiene;
function createGitIndexVinyls(paths) {
const cp = require('child_process');
const repositoryPath = process.cwd();
const fns = paths.map((relativePath) => () =>
new Promise((c, e) => {
const fullPath = path.join(repositoryPath, relativePath);
fs.stat(fullPath, (err, stat) => {
if (err && err.code === 'ENOENT') {
// ignore deletions
return c(null);
} else if (err) {
return e(err);
}
cp.exec(
process.platform === 'win32' ? `git show :${relativePath}` : `git show ':${relativePath}'`,
{ maxBuffer: stat.size, encoding: 'buffer' },
(err, out) => {
if (err) {
return e(err);
}
c(
new VinylFile({
path: fullPath,
base: repositoryPath,
contents: out,
stat,
})
);
}
);
});
})
);
return pall(fns, { concurrency: 4 }).then((r) => r.filter((p) => !!p));
}
// this allows us to run hygiene as a git pre-commit hook
if (require.main === module) {
const cp = require('child_process');
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
process.exit(1);
});
if (process.argv.length > 2) {
hygiene(process.argv.slice(2)).on('error', (err) => {
console.error();
console.error(err);
process.exit(1);
});
} else {
cp.exec(
// --- Start Positron ---
'git diff --cached --name-only --ignore-submodules',
// --- End Positron ---
{ maxBuffer: 2000 * 1024 },
(err, out) => {
if (err) {
console.error();
console.error(err);
process.exit(1);
}
const some = out.split(/\r?\n/).filter((l) => !!l);
if (some.length > 0) {
console.log('Reading git index versions...');
createGitIndexVinyls(some)
.then(
(vinyls) =>
new Promise((c, e) =>
hygiene(es.readArray(vinyls).pipe(filter(all)))
.on('end', () => c())
.on('error', e)
)
)
.catch((err) => {
console.error();
console.error(err);
process.exit(1);
});
}
}
);
}
}