forked from irinazheltisheva/vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtasks.ts
More file actions
514 lines (452 loc) · 14.4 KB
/
Copy pathtasks.ts
File metadata and controls
514 lines (452 loc) · 14.4 KB
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import {
TaskDefinition, Task, TaskGroup, WorkspaceFolder, RelativePattern, ShellExecution, Uri, workspace,
DebugConfiguration, debug, TaskProvider, TextDocument, tasks, TaskScope, QuickPickItem
} from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import * as minimatch from 'minimatch';
import * as nls from 'vscode-nls';
import { JSONVisitor, visit, ParseErrorCode } from 'jsonc-parser';
const localize = nls.loadMessageBundle();
export interface NpmTaskDefinition extends TaskDefinition {
script: string;
path?: string;
}
export interface FolderTaskItem extends QuickPickItem {
label: string;
task: Task;
}
type AutoDetect = 'on' | 'off';
let cachedTasks: Task[] | undefined = undefined;
const INSTALL_SCRIPT = 'install';
export class NpmTaskProvider implements TaskProvider {
constructor() {
}
public provideTasks() {
return provideNpmScripts();
}
public resolveTask(_task: Task): Task | undefined {
const npmTask = (<any>_task.definition).script;
if (npmTask) {
const kind: NpmTaskDefinition = (<any>_task.definition);
let packageJsonUri: Uri;
if (_task.scope === undefined || _task.scope === TaskScope.Global || _task.scope === TaskScope.Workspace) {
// scope is required to be a WorkspaceFolder for resolveTask
return undefined;
}
if (kind.path) {
packageJsonUri = _task.scope.uri.with({ path: _task.scope.uri.path + '/' + kind.path + 'package.json' });
} else {
packageJsonUri = _task.scope.uri.with({ path: _task.scope.uri.path + '/package.json' });
}
return createTask(kind, `${kind.script === INSTALL_SCRIPT ? '' : 'run '}${kind.script}`, _task.scope, packageJsonUri);
}
return undefined;
}
}
export function invalidateTasksCache() {
cachedTasks = undefined;
}
const buildNames: string[] = ['build', 'compile', 'watch'];
function isBuildTask(name: string): boolean {
for (let buildName of buildNames) {
if (name.indexOf(buildName) !== -1) {
return true;
}
}
return false;
}
const testNames: string[] = ['test'];
function isTestTask(name: string): boolean {
for (let testName of testNames) {
if (name === testName) {
return true;
}
}
return false;
}
function getPrePostScripts(scripts: any): Set<string> {
const prePostScripts: Set<string> = new Set([
'preuninstall', 'postuninstall', 'prepack', 'postpack', 'preinstall', 'postinstall',
'prepack', 'postpack', 'prepublish', 'postpublish', 'preversion', 'postversion',
'prestop', 'poststop', 'prerestart', 'postrestart', 'preshrinkwrap', 'postshrinkwrap',
'pretest', 'postest', 'prepublishOnly'
]);
let keys = Object.keys(scripts);
for (const script of keys) {
const prepost = ['pre' + script, 'post' + script];
prepost.forEach(each => {
if (scripts[each] !== undefined) {
prePostScripts.add(each);
}
});
}
return prePostScripts;
}
export function isWorkspaceFolder(value: any): value is WorkspaceFolder {
return value && typeof value !== 'number';
}
export function getPackageManager(folder: WorkspaceFolder): string {
return workspace.getConfiguration('npm', folder.uri).get<string>('packageManager', 'npm');
}
export async function hasNpmScripts(): Promise<boolean> {
let folders = workspace.workspaceFolders;
if (!folders) {
return false;
}
try {
for (const folder of folders) {
if (isAutoDetectionEnabled(folder)) {
let relativePattern = new RelativePattern(folder, '**/package.json');
let paths = await workspace.findFiles(relativePattern, '**/node_modules/**');
if (paths.length > 0) {
return true;
}
}
}
return false;
} catch (error) {
return Promise.reject(error);
}
}
async function detectNpmScripts(): Promise<Task[]> {
let emptyTasks: Task[] = [];
let allTasks: Task[] = [];
let visitedPackageJsonFiles: Set<string> = new Set();
let folders = workspace.workspaceFolders;
if (!folders) {
return emptyTasks;
}
try {
for (const folder of folders) {
if (isAutoDetectionEnabled(folder)) {
let relativePattern = new RelativePattern(folder, '**/package.json');
let paths = await workspace.findFiles(relativePattern, '**/{node_modules,.vscode-test}/**');
for (const path of paths) {
if (!isExcluded(folder, path) && !visitedPackageJsonFiles.has(path.fsPath)) {
let tasks = await provideNpmScriptsForFolder(path);
visitedPackageJsonFiles.add(path.fsPath);
allTasks.push(...tasks);
}
}
}
}
return allTasks;
} catch (error) {
return Promise.reject(error);
}
}
export async function detectNpmScriptsForFolder(folder: Uri): Promise<FolderTaskItem[]> {
let folderTasks: FolderTaskItem[] = [];
try {
let relativePattern = new RelativePattern(folder.fsPath, '**/package.json');
let paths = await workspace.findFiles(relativePattern, '**/node_modules/**');
let visitedPackageJsonFiles: Set<string> = new Set();
for (const path of paths) {
if (!visitedPackageJsonFiles.has(path.fsPath)) {
let tasks = await provideNpmScriptsForFolder(path);
visitedPackageJsonFiles.add(path.fsPath);
folderTasks.push(...tasks.map(t => ({ label: t.name, task: t })));
}
}
return folderTasks;
} catch (error) {
return Promise.reject(error);
}
}
export async function provideNpmScripts(): Promise<Task[]> {
if (!cachedTasks) {
cachedTasks = await detectNpmScripts();
}
return cachedTasks;
}
export function isAutoDetectionEnabled(folder?: WorkspaceFolder): boolean {
return workspace.getConfiguration('npm', folder?.uri).get<AutoDetect>('autoDetect') === 'on';
}
function isExcluded(folder: WorkspaceFolder, packageJsonUri: Uri) {
function testForExclusionPattern(path: string, pattern: string): boolean {
return minimatch(path, pattern, { dot: true });
}
let exclude = workspace.getConfiguration('npm', folder.uri).get<string | string[]>('exclude');
let packageJsonFolder = path.dirname(packageJsonUri.fsPath);
if (exclude) {
if (Array.isArray(exclude)) {
for (let pattern of exclude) {
if (testForExclusionPattern(packageJsonFolder, pattern)) {
return true;
}
}
} else if (testForExclusionPattern(packageJsonFolder, exclude)) {
return true;
}
}
return false;
}
function isDebugScript(script: string): boolean {
let match = script.match(/--(inspect|debug)(-brk)?(=((\[[0-9a-fA-F:]*\]|[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+|[a-zA-Z0-9\.]*):)?(\d+))?/);
return match !== null;
}
async function provideNpmScriptsForFolder(packageJsonUri: Uri): Promise<Task[]> {
let emptyTasks: Task[] = [];
let folder = workspace.getWorkspaceFolder(packageJsonUri);
if (!folder) {
return emptyTasks;
}
let scripts = await getScripts(packageJsonUri);
if (!scripts) {
return emptyTasks;
}
const result: Task[] = [];
const prePostScripts = getPrePostScripts(scripts);
Object.keys(scripts).forEach(each => {
const task = createTask(each, `run ${each}`, folder!, packageJsonUri, scripts![each]);
const lowerCaseTaskName = each.toLowerCase();
if (isBuildTask(lowerCaseTaskName)) {
task.group = TaskGroup.Build;
} else if (isTestTask(lowerCaseTaskName)) {
task.group = TaskGroup.Test;
}
if (prePostScripts.has(each)) {
task.group = TaskGroup.Clean; // hack: use Clean group to tag pre/post scripts
}
// todo@connor4312: all scripts are now debuggable, what is a 'debug script'?
if (isDebugScript(scripts![each])) {
task.group = TaskGroup.Rebuild; // hack: use Rebuild group to tag debug scripts
}
result.push(task);
});
// always add npm install (without a problem matcher)
result.push(createTask(INSTALL_SCRIPT, INSTALL_SCRIPT, folder, packageJsonUri, 'install dependencies from package', []));
return result;
}
export function getTaskName(script: string, relativePath: string | undefined) {
if (relativePath && relativePath.length) {
return `${script} - ${relativePath.substring(0, relativePath.length - 1)}`;
}
return script;
}
export function createTask(script: NpmTaskDefinition | string, cmd: string, folder: WorkspaceFolder, packageJsonUri: Uri, detail?: string, matcher?: any): Task {
let kind: NpmTaskDefinition;
if (typeof script === 'string') {
kind = { type: 'npm', script: script };
} else {
kind = script;
}
function getCommandLine(folder: WorkspaceFolder, cmd: string): string {
let packageManager = getPackageManager(folder);
if (workspace.getConfiguration('npm', folder.uri).get<boolean>('runSilent')) {
return `${packageManager} --silent ${cmd}`;
}
return `${packageManager} ${cmd}`;
}
function getRelativePath(folder: WorkspaceFolder, packageJsonUri: Uri): string {
let rootUri = folder.uri;
let absolutePath = packageJsonUri.path.substring(0, packageJsonUri.path.length - 'package.json'.length);
return absolutePath.substring(rootUri.path.length + 1);
}
let relativePackageJson = getRelativePath(folder, packageJsonUri);
if (relativePackageJson.length) {
kind.path = getRelativePath(folder, packageJsonUri);
}
let taskName = getTaskName(kind.script, relativePackageJson);
let cwd = path.dirname(packageJsonUri.fsPath);
const task = new Task(kind, folder, taskName, 'npm', new ShellExecution(getCommandLine(folder, cmd), { cwd: cwd }), matcher);
task.detail = detail;
return task;
}
export function getPackageJsonUriFromTask(task: Task): Uri | null {
if (isWorkspaceFolder(task.scope)) {
if (task.definition.path) {
return Uri.file(path.join(task.scope.uri.fsPath, task.definition.path, 'package.json'));
} else {
return Uri.file(path.join(task.scope.uri.fsPath, 'package.json'));
}
}
return null;
}
export async function hasPackageJson(): Promise<boolean> {
let folders = workspace.workspaceFolders;
if (!folders) {
return false;
}
for (const folder of folders) {
if (folder.uri.scheme === 'file') {
let packageJson = path.join(folder.uri.fsPath, 'package.json');
if (await exists(packageJson)) {
return true;
}
}
}
return false;
}
async function exists(file: string): Promise<boolean> {
return new Promise<boolean>((resolve, _reject) => {
fs.exists(file, (value) => {
resolve(value);
});
});
}
async function readFile(file: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) {
reject(err);
}
resolve(data.toString());
});
});
}
export function runScript(script: string, document: TextDocument) {
let uri = document.uri;
let folder = workspace.getWorkspaceFolder(uri);
if (folder) {
let task = createTask(script, `run ${script}`, folder, uri);
tasks.executeTask(task);
}
}
export function startDebugging(scriptName: string, folder: WorkspaceFolder) {
const config: DebugConfiguration = {
type: 'pwa-node',
request: 'launch',
name: `Debug ${scriptName}`,
runtimeExecutable: getPackageManager(folder),
runtimeArgs: [
'run',
scriptName,
],
};
if (folder) {
debug.startDebugging(folder, config);
}
}
export type StringMap = { [s: string]: string; };
async function findAllScripts(buffer: string): Promise<StringMap> {
let scripts: StringMap = {};
let script: string | undefined = undefined;
let inScripts = false;
let visitor: JSONVisitor = {
onError(_error: ParseErrorCode, _offset: number, _length: number) {
console.log(_error);
},
onObjectEnd() {
if (inScripts) {
inScripts = false;
}
},
onLiteralValue(value: any, _offset: number, _length: number) {
if (script) {
if (typeof value === 'string') {
scripts[script] = value;
}
script = undefined;
}
},
onObjectProperty(property: string, _offset: number, _length: number) {
if (property === 'scripts') {
inScripts = true;
}
else if (inScripts && !script) {
script = property;
} else { // nested object which is invalid, ignore the script
script = undefined;
}
}
};
visit(buffer, visitor);
return scripts;
}
export function findAllScriptRanges(buffer: string): Map<string, [number, number, string]> {
let scripts: Map<string, [number, number, string]> = new Map();
let script: string | undefined = undefined;
let offset: number;
let length: number;
let inScripts = false;
let visitor: JSONVisitor = {
onError(_error: ParseErrorCode, _offset: number, _length: number) {
},
onObjectEnd() {
if (inScripts) {
inScripts = false;
}
},
onLiteralValue(value: any, _offset: number, _length: number) {
if (script) {
scripts.set(script, [offset, length, value]);
script = undefined;
}
},
onObjectProperty(property: string, off: number, len: number) {
if (property === 'scripts') {
inScripts = true;
}
else if (inScripts) {
script = property;
offset = off;
length = len;
}
}
};
visit(buffer, visitor);
return scripts;
}
export function findScriptAtPosition(buffer: string, offset: number): string | undefined {
let script: string | undefined = undefined;
let foundScript: string | undefined = undefined;
let inScripts = false;
let scriptStart: number | undefined;
let visitor: JSONVisitor = {
onError(_error: ParseErrorCode, _offset: number, _length: number) {
},
onObjectEnd() {
if (inScripts) {
inScripts = false;
scriptStart = undefined;
}
},
onLiteralValue(value: any, nodeOffset: number, nodeLength: number) {
if (inScripts && scriptStart) {
if (typeof value === 'string' && offset >= scriptStart && offset < nodeOffset + nodeLength) {
// found the script
inScripts = false;
foundScript = script;
} else {
script = undefined;
}
}
},
onObjectProperty(property: string, nodeOffset: number) {
if (property === 'scripts') {
inScripts = true;
}
else if (inScripts) {
scriptStart = nodeOffset;
script = property;
} else { // nested object which is invalid, ignore the script
script = undefined;
}
}
};
visit(buffer, visitor);
return foundScript;
}
export async function getScripts(packageJsonUri: Uri): Promise<StringMap | undefined> {
if (packageJsonUri.scheme !== 'file') {
return undefined;
}
let packageJson = packageJsonUri.fsPath;
if (!await exists(packageJson)) {
return undefined;
}
try {
let contents = await readFile(packageJson);
let json = findAllScripts(contents);//JSON.parse(contents);
return json;
} catch (e) {
let localizedParseError = localize('npm.parseError', 'Npm task detection: failed to parse the file {0}', packageJsonUri.fsPath);
throw new Error(localizedParseError);
}
}