forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gulpfile.js
731 lines (645 loc) · 28.6 KB
/
gulpfile.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/* jshint node: true */
/* jshint esversion: 6 */
'use strict';
const gulp = require('gulp');
const filter = require('gulp-filter');
const es = require('event-stream');
const tsfmt = require('typescript-formatter');
const tslint = require('tslint');
const relative = require('relative');
const ts = require('gulp-typescript');
const cp = require('child_process');
const spawn = require('cross-spawn');
const colors = require('colors/safe');
const path = require('path');
const jeditor = require("gulp-json-editor");
const del = require('del');
const sourcemaps = require('gulp-sourcemaps');
const fs = require('fs-extra');
const fsExtra = require('fs-extra');
const remapIstanbul = require('remap-istanbul');
const istanbul = require('istanbul');
const glob = require('glob');
const _ = require('lodash');
const nativeDependencyChecker = require('node-has-native-dependencies');
const flat = require('flat');
const inlinesource = require('gulp-inline-source');
const isCI = process.env.TRAVIS === 'true' || process.env.TF_BUILD !== undefined;
const noop = function () { };
/**
* Hygiene works by creating cascading subsets of all our files and
* passing them through a sequence of checks. Here are the current subsets,
* named according to the checks performed on them. Each subset contains
* the following one, as described in mathematical notation:
*
* all ⊃ indentation ⊃ typescript
*/
const all = [
'src/**/*',
'src/client/**/*',
];
const tsFilter = [
'src/**/*.ts*',
'!out/**/*'
];
const indentationFilter = [
'src/**/*.ts*',
'!**/typings/**/*',
];
const tslintFilter = [
'src/**/*.ts*',
'test/**/*.ts*',
'!**/node_modules/**',
'!out/**/*',
'!images/**/*',
'!.vscode/**/*',
'!pythonFiles/**/*',
'!resources/**/*',
'!snippets/**/*',
'!syntaxes/**/*',
'!**/typings/**/*',
'!**/*.d.ts'
];
gulp.task('precommit', (done) => run({ exitOnError: true, mode: 'staged' }, done));
gulp.task('hygiene-watch', () => gulp.watch(tsFilter, gulp.series('hygiene-modified')));
gulp.task('hygiene', (done) => run({ mode: 'all', skipFormatCheck: true, skipIndentationCheck: true }, done));
gulp.task('compile', (done) => run({ mode: 'compile', skipFormatCheck: true, skipIndentationCheck: true, skipLinter: true }, done));
gulp.task('hygiene-modified', gulp.series('compile', (done) => run({ mode: 'changes' }, done)));
gulp.task('watch', gulp.parallel('hygiene-modified', 'hygiene-watch'));
// Duplicate to allow duplicate task in tasks.json (one ith problem matching, and one without)
gulp.task('watchProblems', gulp.parallel('hygiene-modified', 'hygiene-watch'));
gulp.task('debugger-coverage', buildDebugAdapterCoverage);
gulp.task('hygiene-watch-branch', () => gulp.watch(tsFilter, gulp.series('hygiene-branch')));
gulp.task('hygiene-all', (done) => run({ mode: 'all' }, done));
gulp.task('hygiene-branch', (done) => run({ mode: 'diffMaster' }, done));
gulp.task('cover:clean', () => del(['coverage', 'debug_coverage*']));
gulp.task('output:clean', () => del(['coverage', 'debug_coverage*']));
gulp.task('clean:cleanExceptTests', () => del(['clean:vsix', 'out/client', 'out/datascience-ui', 'out/server']));
gulp.task('clean:vsix', () => del(['*.vsix']));
gulp.task('clean:out', () => del(['out']));
gulp.task('clean', gulp.parallel('output:clean', 'cover:clean', 'clean:vsix', 'clean:out'));
gulp.task('checkNativeDependencies', (done) => {
if (hasNativeDependencies()) {
throw new Error('Native dependencies deteced');
}
done();
});
gulp.task('cover:enable', () => {
return gulp.src("./build/coverconfig.json")
.pipe(jeditor((json) => {
json.enabled = true;
return json;
}))
.pipe(gulp.dest("./out", { 'overwrite': true }));
});
gulp.task('cover:disable', () => {
return gulp.src("./build/coverconfig.json")
.pipe(jeditor((json) => {
json.enabled = false;
return json;
}))
.pipe(gulp.dest("./out", { 'overwrite': true }));
});
/**
* Inline CSS into the coverage report for better visualizations on
* the VSTS report page for code coverage.
*/
gulp.task('inlinesource', () => {
return gulp.src('./coverage/lcov-report/*.html')
.pipe(inlinesource({ attribute: false }))
.pipe(gulp.dest('./coverage/lcov-report-inline'));
});
gulp.task('check-datascience-dependencies', () => checkDatascienceDependencies());
gulp.task("compile", () => {
const tsProject = ts.createProject("tsconfig.json");
return tsProject.src()
.pipe(tsProject())
.js.pipe(gulp.dest("out"));
});
gulp.task('compile-webviews', async () => spawnAsync('npx', ['webpack', '--config', 'webpack.datascience-ui.config.js', '--mode', 'production']));
gulp.task('webpack', async () => {
await spawnAsync('npx', ['webpack', '--mode', 'production', '--inline', '--progress']);
await spawnAsync('npx', ['webpack', '--config', './build/webpack/webpack.extension.config.js', '--mode', 'production', '--inline', '--progress']);
});
gulp.task('webpack', async () => {
await spawnAsync('npx', ['webpack', '--mode', 'production']);
await spawnAsync('npx', ['webpack', '--config', './build/webpack/webpack.extension.sourceMaps.config.js', '--mode', 'production']);
await spawnAsync('npx', ['webpack', '--config', './build/webpack/webpack.extension.config.js', '--mode', 'production']);
await spawnAsync('npx', ['webpack', '--config', './build/webpack/webpack.debugadapter.config.js', '--mode', 'production']);
});
gulp.task('prePublishBundle', gulp.series('checkNativeDependencies', 'check-datascience-dependencies', 'compile', 'clean:cleanExceptTests', 'webpack'));
gulp.task('prePublishNonBundle', gulp.series('checkNativeDependencies', 'check-datascience-dependencies', 'compile', 'compile-webviews'));
const installPythonLibArgs = ['-m', 'pip', '--disable-pip-version-check', 'install',
'-t', './pythonFiles/lib/python', '--no-cache-dir', '--implementation', 'py', '--no-deps',
'--upgrade', '-r', 'requirements.txt'];
gulp.task('installPythonLibs', async () => {
const requirements = fs.readFileSync(path.join(__dirname, 'requirements.txt'), 'utf8').split('\n').map(item => item.trim()).filter(item => item.length > 0);
const args = ['-m', 'pip', '--disable-pip-version-check', 'install', '-t', './pythonFiles/lib/python', '--no-cache-dir', '--implementation', 'py', '--no-deps', '--upgrade'];
await Promise.all(requirements.map(async requirement => {
const success = await spawnAsync(process.env.CI_PYTHON_PATH || 'python3', args.concat(requirement))
.then(() => true)
.catch(ex => {
console.error('Failed to install Python Libs using \'python3\'', ex);
return false
});
if (!success) {
console.info('Failed to install Python Libs using \'python3\', attempting to install using \'python\'');
await spawnAsync('python', args.concat(requirement))
.catch(ex => console.error('Failed to install Python Libs using \'python\'', ex));
}
}));
});
function spawnAsync(command, args) {
return new Promise((resolve, reject) => {
const proc = spawn(command, args, { cwd: __dirname });
proc.stdout.on('data', data => {
// Log output on CI (else travis times out when there's not output).
if (isCI) {
console.log(data.toString());
}
});
proc.stderr.on('data', data => console.error(data.toString()));
proc.on('close', () => resolve());
proc.on('error', error => reject(error));
});
}
function buildDatascienceDependencies() {
fsExtra.ensureDirSync(path.join(__dirname, 'tmp'));
spawn.sync('npm', ['run', 'dump-datascience-webpack-stats']);
}
async function checkDatascienceDependencies() {
buildDatascienceDependencies();
const existingModulesFileName = 'package.datascience-ui.dependencies.json';
const existingModulesFile = path.join(__dirname, existingModulesFileName);
const existingModulesList = JSON.parse(await fsExtra.readFile(existingModulesFile).then(data => data.toString()));
const existingModules = new Set(existingModulesList);
const existingModulesCopy = new Set(existingModulesList);
const statsOutput = path.join(__dirname, 'tmp', 'ds-stats.json');
const contents = await fsExtra.readFile(statsOutput).then(data => data.toString());
const startIndex = contents.toString().indexOf('{') - 1;
const json = JSON.parse(contents.substring(startIndex));
const newModules = new Set();
const packageLock = JSON.parse(await fsExtra.readFile('package-lock.json').then(data => data.toString()));
const modulesInPackageLock = Object.keys(packageLock.dependencies);
// Right now the script only handles two parts in the dependency name (with one '/').
// If we have dependencies with more than one '/', then update this code.
if (modulesInPackageLock.some(dependency => dependency.indexOf('/') !== dependency.lastIndexOf('/'))) {
throwAndLogError('Dependencies detected with more than one \'/\', please update this script.');
}
json.chunks[0].modules.forEach(m => {
const name = m.name;
if (!name.startsWith('./node_modules')) {
return;
}
const nameWithoutNodeModules = name.substring('./node_modules'.length);
let moduleName1 = nameWithoutNodeModules.split('/')[1];
moduleName1 = moduleName1.endsWith('!.') ? moduleName1.substring(0, moduleName1.length - 2) : moduleName1;
const moduleName2 = `${nameWithoutNodeModules.split('/')[1]}/${nameWithoutNodeModules.split('/')[2]}`;
const matchedModules = modulesInPackageLock.filter(dependency => dependency === moduleName2 || dependency === moduleName1);
switch (matchedModules.length) {
case 0:
throwAndLogError(`Dependency not found in package-lock.json, Dependency = '${name}, ${moduleName1}, ${moduleName2}'`);
break;
case 1:
break;
default: {
throwAndLogError(`Exact Dependency not found in package-lock.json, Dependency = '${name}'`);
}
}
const moduleName = matchedModules[0];
if (existingModulesCopy.has(moduleName)) {
existingModulesCopy.delete(moduleName);
}
if (existingModules.has(moduleName) || newModules.has(moduleName)) {
return;
}
newModules.add(moduleName);
});
const errorMessages = [];
if (newModules.size > 0) {
errorMessages.push(`Add the untracked dependencies '${Array.from(newModules.values()).join(', ')}' to ${existingModulesFileName}`);
}
if (existingModulesCopy.size > 0) {
errorMessages.push(`Remove the unused '${Array.from(existingModulesCopy.values()).join(', ')}' dependencies from ${existingModulesFileName}`);
}
if (errorMessages.length > 0) {
throwAndLogError(errorMessages.join('\n'));
}
}
function throwAndLogError(message) {
if (message.length > 0) {
console.error(colors.red(message));
throw new Error(message);
}
}
function hasNativeDependencies() {
let nativeDependencies = nativeDependencyChecker.check(path.join(__dirname, 'node_modules'));
if (!Array.isArray(nativeDependencies) || nativeDependencies.length === 0) {
return false;
}
const dependencies = JSON.parse(spawn.sync('npm', ['ls', '--json', '--prod']).stdout.toString());
const jsonProperties = Object.keys(flat.flatten(dependencies));
nativeDependencies = _.flatMap(nativeDependencies, item => path.dirname(item.substring(item.indexOf('node_modules') + 'node_modules'.length)).split(path.sep))
.filter(item => item.length > 0)
.filter(item => jsonProperties.findIndex(flattenedDependency => flattenedDependency.endsWith(`dependencies.${item}.version`)) >= 0);
if (nativeDependencies.length > 0) {
console.error('Native dependencies detected', nativeDependencies);
return true;
}
return false;
}
function buildDebugAdapterCoverage(done) {
const matches = glob.sync(path.join(__dirname, 'debug_coverage*/coverage.json'));
matches.forEach(coverageFile => {
const finalCoverageFile = path.join(path.dirname(coverageFile), 'coverage-final-upload.json');
const remappedCollector = remapIstanbul.remap(JSON.parse(fs.readFileSync(coverageFile, 'utf8')), {
warn: warning => {
// We expect some warnings as any JS file without a typescript mapping will cause this.
// By default, we'll skip printing these to the console as it clutters it up.
console.warn(warning);
}
});
const reporter = new istanbul.Reporter(undefined, path.dirname(coverageFile));
reporter.add('lcov');
reporter.write(remappedCollector, true, () => { });
});
done();
}
/**
* @typedef {Object} hygieneOptions - creates a new type named 'SpecialType'
* @property {'changes'|'staged'|'all'|'compile'|'diffMaster'} [mode=] - Mode.
* @property {boolean=} skipIndentationCheck - Skip indentation checks.
* @property {boolean=} skipFormatCheck - Skip format checks.
* @property {boolean=} skipLinter - Skip linter.
*/
const tsProjectMap = {};
/**
*
* @param {hygieneOptions} options
*/
function getTsProject(options) {
const tsOptions = options.mode === 'compile' ? undefined : { strict: true, noImplicitAny: false, noImplicitThis: false };
const mode = tsOptions && tsOptions.mode ? tsOptions.mode : '';
return tsProjectMap[mode] ? tsProjectMap[mode] : tsProjectMap[mode] = ts.createProject('tsconfig.json', tsOptions);
}
let configuration;
/**
*
* @param {hygieneOptions} options
*/
function getLinter(options) {
configuration = configuration ? configuration : tslint.Configuration.findConfiguration(null, '.');
const program = tslint.Linter.createProgram('./tsconfig.json');
const linter = new tslint.Linter({ formatter: 'json' }, program);
return { linter, configuration };
}
let compilationInProgress = false;
let reRunCompilation = false;
/**
*
* @param {hygieneOptions} options
* @returns {NodeJS.ReadWriteStream}
*/
const hygiene = (options, done) => {
if (compilationInProgress) {
reRunCompilation = true;
return done();
}
const fileListToProcess = options.mode === 'compile' ? undefined : getFileListToProcess(options);
if (Array.isArray(fileListToProcess) && fileListToProcess !== all
&& fileListToProcess.filter(item => item.endsWith('.ts')).length === 0) {
return done();
}
const started = new Date().getTime();
compilationInProgress = true;
options = options || {};
let errorCount = 0;
const indentation = es.through(function (file) {
file.contents
.toString('utf8')
.split(/\r\n|\r|\n/)
.forEach((line, i) => {
if (/^\s*$/.test(line) || /^\S+.*$/.test(line)) {
// Empty or whitespace lines are OK.
} else if (/^(\s\s\s\s)+.*/.test(line)) {
// Good indent.
} else if (/^[\t]+.*/.test(line)) {
console.error(file.relative + '(' + (i + 1) + ',1): Bad whitespace indentation (use 4 spaces instead of tabs or other)');
errorCount++;
}
});
this.emit('data', file);
});
const formatOptions = { verify: true, tsconfig: true, tslint: true, editorconfig: true, tsfmt: true };
const formatting = es.map(function (file, cb) {
tsfmt.processString(file.path, file.contents.toString('utf8'), formatOptions)
.then(result => {
if (result.error) {
let message = result.message.trim();
let formattedMessage = '';
if (message.startsWith(__dirname)) {
message = message.substr(__dirname.length);
message = message.startsWith(path.sep) ? message.substr(1) : message;
const index = message.indexOf('.ts ');
if (index === -1) {
formattedMessage = colors.red(message);
} else {
const file = message.substr(0, index + 3);
const errorMessage = message.substr(index + 4).trim();
formattedMessage = `${colors.red(file)} ${errorMessage}`;
}
} else {
formattedMessage = colors.red(message);
}
console.error(formattedMessage);
errorCount++;
}
cb(null, file);
})
.catch(cb);
});
let reportedLinterFailures = [];
/**
* Report the linter failures
* @param {any[]} failures
*/
function reportLinterFailures(failures) {
return failures
.map(failure => {
const name = failure.name || failure.fileName;
const position = failure.startPosition;
const line = position.lineAndCharacter ? position.lineAndCharacter.line : position.line;
const character = position.lineAndCharacter ? position.lineAndCharacter.character : position.character;
// Output in format similar to tslint for the linter to pickup.
const message = `ERROR: (${failure.ruleName}) ${relative(__dirname, name)}[${line + 1}, ${character + 1}]: ${failure.failure}`;
if (reportedLinterFailures.indexOf(message) === -1) {
console.error(message);
reportedLinterFailures.push(message);
return true;
} else {
return false;
}
})
.filter(reported => reported === true)
.length > 0;
}
const { linter, configuration } = getLinter(options);
const tsl = es.through(function (file) {
const contents = file.contents.toString('utf8');
if (isCI) {
// Don't print anything to the console, we'll do that.
console.log('.');
}
// Yes this is a hack, but tslinter doesn't provide an option to prevent this.
const oldWarn = console.warn;
console.warn = () => { };
linter.failures = [];
linter.fixes = [];
linter.lint(file.relative, contents, configuration.results);
console.warn = oldWarn;
const result = linter.getResult();
if (result.failureCount > 0 || result.errorCount > 0) {
const reported = reportLinterFailures(result.failures);
if (result.failureCount && reported) {
errorCount += result.failureCount;
}
if (result.errorCount && reported) {
errorCount += result.errorCount;
}
}
this.emit('data', file);
});
const tsFiles = [];
const tscFilesTracker = es.through(function (file) {
tsFiles.push(file.path.replace(/\\/g, '/'));
tsFiles.push(file.path);
this.emit('data', file);
});
const tsProject = getTsProject(options);
const tsc = function () {
function customReporter() {
return {
error: function (error, typescript) {
const fullFilename = error.fullFilename || '';
const relativeFilename = error.relativeFilename || '';
if (tsFiles.findIndex(file => fullFilename === file || relativeFilename === file) === -1) {
return;
}
console.error(`Error: ${error.message}`);
errorCount += 1;
},
finish: function () {
// forget the summary.
console.log('Finished compilation');
}
};
}
const reporter = customReporter();
return tsProject(reporter);
}
const files = options.mode === 'compile' ? tsProject.src() : getFilesToProcess(fileListToProcess);
const dest = options.mode === 'compile' ? './out' : '.';
let result = files
.pipe(filter(f => f && f.stat && !f.stat.isDirectory()));
if (!options.skipIndentationCheck) {
result = result.pipe(filter(indentationFilter))
.pipe(indentation);
}
result = result
.pipe(filter(tslintFilter));
if (!options.skipFormatCheck) {
// result = result
// .pipe(formatting);
}
if (!options.skipLinter) {
result = result
.pipe(tsl);
}
let totalTime = 0;
result = result
.pipe(tscFilesTracker)
.pipe(sourcemaps.init())
.pipe(tsc())
.pipe(sourcemaps.mapSources(function (sourcePath, file) {
let tsFileName = path.basename(file.path).replace(/js$/, 'ts');
const qualifiedSourcePath = path.dirname(file.path).replace('out/', 'src/').replace('out\\', 'src\\');
if (!fs.existsSync(path.join(qualifiedSourcePath, tsFileName))) {
const tsxFileName = path.basename(file.path).replace(/js$/, 'tsx');
if (!fs.existsSync(path.join(qualifiedSourcePath, tsxFileName))) {
console.error(`ERROR: (source-maps) ${file.path}[1,1]: Source file not found`);
} else {
tsFileName = tsxFileName;
}
}
return path.join(path.relative(path.dirname(file.path), qualifiedSourcePath), tsFileName);
}))
.pipe(sourcemaps.write('.', { includeContent: false }))
.pipe(gulp.dest(dest))
.pipe(es.through(null, function () {
if (errorCount > 0) {
const errorMessage = `Hygiene failed with errors 👎 . Check 'gulpfile.js' (completed in ${new Date().getTime() - started}ms).`;
console.error(colors.red(errorMessage));
exitHandler(options);
} else {
console.log(colors.green(`Hygiene passed with 0 errors 👍 (completed in ${new Date().getTime() - started}ms).`));
}
// Reset error counter.
errorCount = 0;
reportedLinterFailures = [];
compilationInProgress = false;
if (reRunCompilation) {
reRunCompilation = false;
setTimeout(() => {
hygiene(options, done);
}, 10);
}
done();
this.emit('end');
}))
.on('error', ex => {
exitHandler(options, ex);
done();
});
return result;
};
/**
* @typedef {Object} runOptions
* @property {boolean=} exitOnError - Exit on error.
* @property {'changes'|'staged'|'all'} [mode=] - Mode.
* @property {string[]=} files - Optional list of files to be modified.
* @property {boolean=} skipIndentationCheck - Skip indentation checks.
* @property {boolean=} skipFormatCheck - Skip format checks.
* @property {boolean=} skipLinter - Skip linter.
* @property {boolean=} watch - Watch mode.
*/
/**
* Run the linters.
* @param {runOptions} options
* @param {Error} ex
*/
function exitHandler(options, ex) {
console.error();
if (ex) {
console.error(ex);
console.error(colors.red(ex));
}
if (options.exitOnError) {
console.log('exit');
process.exit(1);
}
}
/**
* Run the linters.
* @param {runOptions} options
*/
function run(options, done) {
done = done || noop;
options = options ? options : {};
options.exitOnError = typeof options.exitOnError === 'undefined' ? isCI : options.exitOnError;
process.once('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
exitHandler(options);
});
// Clear screen each time
console.log('\x1Bc');
const startMessage = `Hygiene starting`;
console.log(colors.blue(startMessage));
hygiene(options, done);
}
function git(args) {
let result = cp.spawnSync('git', args, { encoding: 'utf-8' });
return result.output.join('\n');
}
function getStagedFilesSync() {
const out = git(['diff', '--cached', '--name-only']);
return out
.split(/\r?\n/)
.filter(l => !!l);
}
function getAddedFilesSync() {
const out = git(['status', '-u', '-s']);
return out
.split(/\r?\n/)
.filter(l => !!l)
.filter(l => _.intersection(['A', '?', 'U'], l.substring(0, 2).trim().split('')).length > 0)
.map(l => path.join(__dirname, l.substring(2).trim()));
}
function getAzureDevOpsVarValue(varName) {
return process.env[varName.replace(/\./g, '_').toUpperCase()]
}
function getModifiedFilesSync() {
if (isCI) {
const isAzurePR = getAzureDevOpsVarValue('System.PullRequest.SourceBranch') !== undefined;
const isTravisPR = process.env.TRAVIS_PULL_REQUEST !== undefined && process.env.TRAVIS_PULL_REQUEST !== 'true';
if (!isAzurePR && !isTravisPR) {
return [];
}
const targetBranch = process.env.TRAVIS_BRANCH || getAzureDevOpsVarValue('System.PullRequest.TargetBranch');
if (targetBranch !== 'master') {
return [];
}
const repo = process.env.TRAVIS_REPO_SLUG || getAzureDevOpsVarValue('Build.Repository.Name');
const originOrUpstream = (repo.toUpperCase() === 'MICROSOFT/VSCODE-PYTHON' || repo.toUpperCase() === 'VSCODE-PYTHON-DATASCIENCE/VSCODE-PYTHON') ? 'origin' : 'upstream';
// If on CI, get a list of modified files comparing against
// PR branch and master of current (assumed 'origin') repo.
cp.execSync(`git remote set-branches --add ${originOrUpstream} master`, { encoding: 'utf8', cwd: __dirname });
cp.execSync('git fetch', { encoding: 'utf8', cwd: __dirname });
const cmd = `git diff --name-only HEAD ${originOrUpstream}/master`;
console.info(cmd);
const out = cp.execSync(cmd, { encoding: 'utf8', cwd: __dirname });
return out
.split(/\r?\n/)
.filter(l => !!l)
.filter(l => l.length > 0)
.map(l => l.trim().replace(/\//g, path.sep))
.map(l => path.join(__dirname, l));
} else {
const out = cp.execSync('git status -u -s', { encoding: 'utf8' });
return out
.split(/\r?\n/)
.filter(l => !!l)
.filter(l => _.intersection(['M', 'A', 'R', 'C', 'U', '?'], l.substring(0, 2).trim().split('')).length > 0)
.map(l => path.join(__dirname, l.substring(2).trim().replace(/\//g, path.sep)));
}
}
function getDifferentFromMasterFilesSync() {
const out = git(['diff', '--name-status', 'master']);
return out
.split(/\r?\n/)
.filter(l => !!l)
.map(l => path.join(__dirname, l.substring(2).trim()));
}
/**
* @param {hygieneOptions} options
*/
function getFilesToProcess(fileList) {
const gulpSrcOptions = { base: '.' };
return gulp.src(fileList, gulpSrcOptions);
}
/**
* @param {hygieneOptions} options
*/
function getFileListToProcess(options) {
const mode = options ? options.mode : 'all';
const gulpSrcOptions = { base: '.' };
// If we need only modified files, then filter the glob.
if (options && options.mode === 'changes') {
return getModifiedFilesSync().filter(f => fs.existsSync(f));
}
if (options && options.mode === 'staged') {
return getStagedFilesSync().filter(f => fs.existsSync(f));;
}
if (options && options.mode === 'diffMaster') {
return getDifferentFromMasterFilesSync().filter(f => fs.existsSync(f));;
}
return all;
}
exports.hygiene = hygiene;
// this allows us to run hygiene via CLI (e.g. `node gulfile.js`).
if (require.main === module) {
run({ exitOnError: true, mode: 'staged' }, () => { });
}