forked from DonJayamanne/gitHistoryVSCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
356 lines (313 loc) · 12 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'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 colors = require('colors/safe');
const gitmodified = require('gulp-gitmodified');
const path = require('path');
const debounce = require('debounce');
const jeditor = require("gulp-json-editor");
const del = require('del');
const codecov = require('gulp-codecov');
/**
* 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/**/*',
'test/**/*',
'browser/src/**/*'
];
const indentationFilter = [
'src/**/*.ts',
'!**/typings/**/*',
];
const tslintFilter = [
'src/**/*.ts',
'browser/src/**/*.ts',
'browser/src/**/*.tsx',
'test/**/*.ts',
'!webpack.config.js',
'!**/node_modules/**',
'!out/**/*',
'!images/**/*',
'!.vscode/**/*',
'!resources/**/*',
'!**/typings/**/*',
];
gulp.task('hygiene', () => run({ mode: 'all', skipFormatCheck: true, skipIndentationCheck: true }));
gulp.task('compile', () => run({ mode: 'compile', skipFormatCheck: true, skipIndentationCheck: true, skipLinter: true }));
gulp.task('watch', ['hygiene-modified', 'hygiene-watch']);
gulp.task('hygiene-watch', () => gulp.watch(all, debounce(() => run({ mode: 'changes' }), 1000)));
gulp.task('hygiene-modified', ['compile'], () => run({ mode: 'changes' }));
gulp.task('clean', ['output:clean', 'cover:clean'], () => { });
gulp.task('cover:upload', () => gulp.src('./coverage/lcov.info').pipe(codecov()));
gulp.task('output:clean', () => del('coverage'));
gulp.task('cover:clean', () => del('coverage'));
gulp.task('cover:enable', () => {
return gulp.src("./coverconfig.json")
.pipe(jeditor((json) => {
json.enabled = true;
return json;
}))
.pipe(gulp.dest("./out", { 'overwrite': true }));
});
gulp.task('cover:disable', () => {
return gulp.src("./coverconfig.json")
.pipe(jeditor((json) => {
json.enabled = true;
return json;
}))
.pipe(gulp.dest("./out", { 'overwrite': true }));
});
/**
* @typedef {Object} hygieneOptions - creates a new type named 'SpecialType'
* @property {'changes'|'staged'|'all'|'compile'} [mode=] - Mode.
* @property {boolean=} skipIndentationCheck - Skip indentation checks.
* @property {boolean=} skipFormatCheck - Skip format checks.
* @property {boolean=} skipLinter - Skip linter.
*/
/**
*
* @param {hygieneOptions} options
* @returns {NodeJS.ReadWriteStream}
*/
const hygiene = (options) => {
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) {
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 configuration = tslint.Configuration.findConfiguration(null, '.');
const program = tslint.Linter.createProgram('./tsconfig.json');
const linter = new tslint.Linter({ formatter: 'json' }, program);
const tsl = es.through(function (file) {
const contents = file.contents.toString('utf8');
// Don't print anything to the console, we'll do that.
// Yes this is a hack, but tslinter doesn't provide an option to prevent this.
const oldWarn = console.warn;
console.warn = () => { };
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 tsOptions = options.mode === 'compile' ? undefined : { strict: true, noImplicitAny: false, noImplicitThis: false };
const tsProject = ts.createProject('tsconfig.json', tsOptions);
const tsc = function () {
function customReporter() {
return {
error: function (error) {
const fullFilename = error.fullFilename || '';
const relativeFilename = error.relativeFilename || '';
if (tsFiles.findIndex(file => fullFilename === file || relativeFilename === file) === -1) {
return;
}
errorCount += 1;
console.error(error.message);
},
finish: function () {
// forget the summary.
}
};
}
const reporter = customReporter();
return tsProject(reporter);
}
const files = options.mode === 'compile' ? tsProject.src() : getFilesToProcess(options);
const dest = options.mode === 'compile' ? './out' : '.';
let result = files
.pipe(filter(f => !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);
}
result = result
.pipe(tscFilesTracker)
.pipe(tsc())
.js.pipe(gulp.dest(dest))
.pipe(es.through(null, function () {
if (errorCount > 0) {
const errorMessage = `Hygiene failed with ${colors.yellow(errorCount)} errors 👎 . Check 'gulpfile.js'.`;
console.error(colors.red(errorMessage));
exitHandler(options);
} else {
console.log(colors.green('Hygiene passed with 0 errors 👍.'));
}
// Reset error counter.
errorCount = 0;
reportedLinterFailures = [];
this.emit('end');
}))
.on('error', exitHandler.bind(this, options));
};
/**
* @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) {
options = options ? options : {};
process.once('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
exitHandler(options);
});
return hygiene(options);
}
function getStagedFilesSync() {
const out = cp.execSync('git diff --cached --name-only', { encoding: 'utf8' });
const some = out
.split(/\r?\n/)
.filter(l => !!l);
return some;
}
/**
* @param {hygieneOptions} options
*/
function getFilesToProcess(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 gulp.src(all, gulpSrcOptions)
.pipe(gitmodified(['M', 'A', 'D', 'R', 'C', 'U', '??']));
}
if (options && options.mode === 'staged') {
return gulp.src(getStagedFilesSync(), gulpSrcOptions);
}
return gulp.src(all, gulpSrcOptions);
}
exports.hygiene = hygiene;
// this allows us to run hygiene as a git pre-commit hook.
if (require.main === module) {
run({ exitOnError: true, mode: 'staged' });
}