forked from microsoft/vscode-python
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gulpfile.js
293 lines (263 loc) · 12.1 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
/*---------------------------------------------------------------------------------------------
* 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 ts = require('gulp-typescript');
const spawn = require('cross-spawn');
const path = require('path');
const del = require('del');
const fsExtra = require('fs-extra');
const glob = require('glob');
const _ = require('lodash');
const nativeDependencyChecker = require('node-has-native-dependencies');
const flat = require('flat');
const { argv } = require('yargs');
const os = require('os');
const typescript = require('typescript');
const tsProject = ts.createProject('./tsconfig.json', { typescript });
const isCI = process.env.TRAVIS === 'true' || process.env.TF_BUILD !== undefined;
gulp.task('compileCore', (done) => {
let failed = false;
tsProject
.src()
.pipe(tsProject())
.on('error', () => {
failed = true;
})
.js.pipe(gulp.dest('out'))
.on('finish', () => (failed ? done(new Error('TypeScript compilation errors')) : done()));
});
gulp.task('compileApi', (done) => {
spawnAsync('npm', ['run', 'compileApi'], undefined, true)
.then((stdout) => {
if (stdout.includes('error')) {
done(new Error(stdout));
} else {
done();
}
})
.catch((ex) => {
console.log(ex);
done(new Error('TypeScript compilation errors', ex));
});
});
gulp.task('compile', gulp.series('compileCore', 'compileApi'));
gulp.task('precommit', (done) => run({ exitOnError: true, mode: 'staged' }, done));
gulp.task('output:clean', () => del(['coverage']));
gulp.task('clean:cleanExceptTests', () => del(['clean:vsix', 'out/client']));
gulp.task('clean:vsix', () => del(['*.vsix']));
gulp.task('clean:out', () => del(['out']));
gulp.task('clean', gulp.parallel('output:clean', 'clean:vsix', 'clean:out'));
gulp.task('checkNativeDependencies', (done) => {
if (hasNativeDependencies()) {
done(new Error('Native dependencies detected'));
}
done();
});
const webpackEnv = { NODE_OPTIONS: '--max_old_space_size=9096' };
async function buildWebPackForDevOrProduction(configFile, configNameForProductionBuilds) {
if (configNameForProductionBuilds) {
await buildWebPack(configNameForProductionBuilds, ['--config', configFile], webpackEnv);
} else {
await spawnAsync('npm', ['run', 'webpack', '--', '--config', configFile, '--mode', 'production'], webpackEnv);
}
}
gulp.task('webpack', async () => {
// Build node_modules.
await buildWebPackForDevOrProduction('./build/webpack/webpack.extension.dependencies.config.js', 'production');
await buildWebPackForDevOrProduction('./build/webpack/webpack.extension.config.js', 'extension');
await buildWebPackForDevOrProduction('./build/webpack/webpack.extension.browser.config.js', 'browser');
});
gulp.task('addExtensionPackDependencies', async () => {
await buildLicense();
await addExtensionPackDependencies();
});
async function addExtensionPackDependencies() {
// Update the package.json to add extension pack dependencies at build time so that
// extension dependencies need not be installed during development
const packageJsonContents = await fsExtra.readFile('package.json', 'utf-8');
const packageJson = JSON.parse(packageJsonContents);
packageJson.extensionPack = ['ms-python.vscode-pylance', 'ms-python.debugpy'].concat(
packageJson.extensionPack ? packageJson.extensionPack : [],
);
// Remove potential duplicates.
packageJson.extensionPack = packageJson.extensionPack.filter(
(item, index) => packageJson.extensionPack.indexOf(item) === index,
);
await fsExtra.writeFile('package.json', JSON.stringify(packageJson, null, 4), 'utf-8');
}
async function buildLicense() {
const headerPath = path.join(__dirname, 'build', 'license-header.txt');
const licenseHeader = await fsExtra.readFile(headerPath, 'utf-8');
const license = await fsExtra.readFile('LICENSE', 'utf-8');
await fsExtra.writeFile('LICENSE', `${licenseHeader}\n${license}`, 'utf-8');
}
gulp.task('updateBuildNumber', async () => {
await updateBuildNumber(argv);
});
async function updateBuildNumber(args) {
if (args && args.buildNumber) {
// Edit the version number from the package.json
const packageJsonContents = await fsExtra.readFile('package.json', 'utf-8');
const packageJson = JSON.parse(packageJsonContents);
// Change version number
const versionParts = packageJson.version.split('.');
const buildNumberPortion =
versionParts.length > 2 ? versionParts[2].replace(/(\d+)/, args.buildNumber) : args.buildNumber;
const newVersion =
versionParts.length > 1
? `${versionParts[0]}.${versionParts[1]}.${buildNumberPortion}`
: packageJson.version;
packageJson.version = newVersion;
// Write back to the package json
await fsExtra.writeFile('package.json', JSON.stringify(packageJson, null, 4), 'utf-8');
// Update the changelog.md if we are told to (this should happen on the release branch)
if (args.updateChangelog) {
const changeLogContents = await fsExtra.readFile('CHANGELOG.md', 'utf-8');
const fixedContents = changeLogContents.replace(
/##\s*(\d+)\.(\d+)\.(\d+)\s*\(/,
`## $1.$2.${buildNumberPortion} (`,
);
// Write back to changelog.md
await fsExtra.writeFile('CHANGELOG.md', fixedContents, 'utf-8');
}
} else {
throw Error('buildNumber argument required for updateBuildNumber task');
}
}
async function buildWebPack(webpackConfigName, args, env) {
// Remember to perform a case insensitive search.
const allowedWarnings = getAllowedWarningsForWebPack(webpackConfigName).map((item) => item.toLowerCase());
const stdOut = await spawnAsync(
'npm',
['run', 'webpack', '--', ...args, ...['--mode', 'production', '--devtool', 'source-map']],
env,
);
const stdOutLines = stdOut
.split(os.EOL)
.map((item) => item.trim())
.filter((item) => item.length > 0);
// Remember to perform a case insensitive search.
const warnings = stdOutLines
.filter((item) => item.startsWith('WARNING in '))
.filter(
(item) =>
allowedWarnings.findIndex((allowedWarning) =>
item.toLowerCase().startsWith(allowedWarning.toLowerCase()),
) === -1,
);
const errors = stdOutLines.some((item) => item.startsWith('ERROR in'));
if (errors) {
throw new Error(`Errors in ${webpackConfigName}, \n${warnings.join(', ')}\n\n${stdOut}`);
}
if (warnings.length > 0) {
throw new Error(
`Warnings in ${webpackConfigName}, Check gulpfile.js to see if the warning should be allowed., \n\n${stdOut}`,
);
}
}
function getAllowedWarningsForWebPack(buildConfig) {
switch (buildConfig) {
case 'production':
return [
'WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).',
'WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.',
'WARNING in webpack performance recommendations:',
'WARNING in ./node_modules/encoding/lib/iconv-loader.js',
'WARNING in ./node_modules/any-promise/register.js',
'WARNING in ./node_modules/diagnostic-channel-publishers/dist/src/azure-coretracing.pub.js',
'WARNING in ./node_modules/applicationinsights/out/AutoCollection/NativePerformance.js',
];
case 'extension':
return [
'WARNING in ./node_modules/encoding/lib/iconv-loader.js',
'WARNING in ./node_modules/any-promise/register.js',
'remove-files-plugin@1.4.0:',
'WARNING in ./node_modules/diagnostic-channel-publishers/dist/src/azure-coretracing.pub.js',
'WARNING in ./node_modules/applicationinsights/out/AutoCollection/NativePerformance.js',
];
case 'debugAdapter':
return [
'WARNING in ./node_modules/vscode-uri/lib/index.js',
'WARNING in ./node_modules/diagnostic-channel-publishers/dist/src/azure-coretracing.pub.js',
'WARNING in ./node_modules/applicationinsights/out/AutoCollection/NativePerformance.js',
];
case 'browser':
return [
'WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).',
'WARNING in entrypoint size limit: The following entrypoint(s) combined asset size exceeds the recommended limit (244 KiB). This can impact web performance.',
'WARNING in webpack performance recommendations:',
];
default:
throw new Error('Unknown WebPack Configuration');
}
}
gulp.task('renameSourceMaps', async () => {
// By default source maps will be disabled in the extension.
// Users will need to use the command `python.enableSourceMapSupport` to enable source maps.
const extensionSourceMap = path.join(__dirname, 'out', 'client', 'extension.js.map');
await fsExtra.rename(extensionSourceMap, `${extensionSourceMap}.disabled`);
});
gulp.task('verifyBundle', async () => {
const matches = await glob.sync(path.join(__dirname, '*.vsix'));
if (!matches || matches.length === 0) {
throw new Error('Bundle does not exist');
} else {
console.log(`Bundle ${matches[0]} exists.`);
}
});
gulp.task('prePublishBundle', gulp.series('webpack', 'renameSourceMaps'));
gulp.task('checkDependencies', gulp.series('checkNativeDependencies'));
gulp.task('prePublishNonBundle', gulp.series('compile'));
function spawnAsync(command, args, env, rejectOnStdErr = false) {
env = env || {};
env = { ...process.env, ...env };
return new Promise((resolve, reject) => {
let stdOut = '';
console.info(`> ${command} ${args.join(' ')}`);
const proc = spawn(command, args, { cwd: __dirname, env });
proc.stdout.on('data', (data) => {
// Log output on CI (else travis times out when there's not output).
stdOut += data.toString();
if (isCI) {
console.log(data.toString());
}
});
proc.stderr.on('data', (data) => {
console.error(data.toString());
if (rejectOnStdErr) {
reject(data.toString());
}
});
proc.on('close', () => resolve(stdOut));
proc.on('error', (error) => reject(error));
});
}
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) => item !== 'fsevents')
.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;
}