-
Notifications
You must be signed in to change notification settings - Fork 30k
/
abstractTaskService.ts
3701 lines (3416 loc) · 141 KB
/
abstractTaskService.ts
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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Action } from 'vs/base/common/actions';
import { IStringDictionary } from 'vs/base/common/collections';
import { Emitter, Event } from 'vs/base/common/event';
import * as glob from 'vs/base/common/glob';
import * as json from 'vs/base/common/json';
import { Disposable, dispose, IDisposable, IReference } from 'vs/base/common/lifecycle';
import { LRUCache, Touch } from 'vs/base/common/map';
import * as Objects from 'vs/base/common/objects';
import { ValidationState, ValidationStatus } from 'vs/base/common/parsers';
import * as Platform from 'vs/base/common/platform';
import { TerminateResponseCode } from 'vs/base/common/processes';
import * as resources from 'vs/base/common/resources';
import Severity from 'vs/base/common/severity';
import * as Types from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import * as UUID from 'vs/base/common/uuid';
import * as nls from 'vs/nls';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { ConfigurationTarget, IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IFileService, IFileStatWithPartialMetadata } from 'vs/platform/files/common/files';
import { IMarkerService } from 'vs/platform/markers/common/markers';
import { IProgressOptions, IProgressService, ProgressLocation } from 'vs/platform/progress/common/progress';
import { IStorageService, StorageScope, StorageTarget } from 'vs/platform/storage/common/storage';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { INamedProblemMatcher, ProblemMatcherRegistry } from 'vs/workbench/contrib/tasks/common/problemMatcher';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { IOpenerService } from 'vs/platform/opener/common/opener';
import { IModelService } from 'vs/editor/common/services/model';
import { IWorkspace, IWorkspaceContextService, IWorkspaceFolder, WorkbenchState, WorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { Markers } from 'vs/workbench/contrib/markers/common/markers';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IOutputChannel, IOutputService } from 'vs/workbench/services/output/common/output';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { ITerminalGroupService, ITerminalService } from 'vs/workbench/contrib/terminal/browser/terminal';
import { ITerminalProfileResolverService } from 'vs/workbench/contrib/terminal/common/terminal';
import { ConfiguringTask, ContributedTask, CustomTask, ExecutionEngine, InMemoryTask, ITaskEvent, ITaskIdentifier, ITaskSet, JsonSchemaVersion, KeyedTaskIdentifier, RuntimeType, Task, TaskDefinition, TaskEventKind, TaskGroup, TaskRunSource, TaskSettingId, TaskSorter, TaskSourceKind, TasksSchemaProperties, TASK_RUNNING_STATE, USER_TASKS_GROUP_KEY } from 'vs/workbench/contrib/tasks/common/tasks';
import { CustomExecutionSupportedContext, ICustomizationProperties, IProblemMatcherRunOptions, ITaskFilter, ITaskProvider, ITaskService, IWorkspaceFolderTaskResult, ProcessExecutionSupportedContext, ServerlessWebContext, ShellExecutionSupportedContext, TaskCommandsRegistered, TaskExecutionSupportedContext } from 'vs/workbench/contrib/tasks/common/taskService';
import { ITaskExecuteResult, ITaskResolver, ITaskSummary, ITaskSystem, ITaskSystemInfo, ITaskTerminateResponse, TaskError, TaskErrors, TaskExecuteKind } from 'vs/workbench/contrib/tasks/common/taskSystem';
import { getTemplates as getTaskTemplates } from 'vs/workbench/contrib/tasks/common/taskTemplates';
import * as TaskConfig from '../common/taskConfiguration';
import { TerminalTaskSystem } from './terminalTaskSystem';
import { IQuickInputService, IQuickPick, IQuickPickItem, QuickPickInput } from 'vs/platform/quickinput/common/quickInput';
import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { TaskDefinitionRegistry } from 'vs/workbench/contrib/tasks/common/taskDefinitionRegistry';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { once } from 'vs/base/common/functional';
import { toFormattedString } from 'vs/base/common/jsonFormatter';
import { Schemas } from 'vs/base/common/network';
import { IResolvedTextEditorModel, ITextModelService } from 'vs/editor/common/services/resolverService';
import { TextEditorSelectionRevealType } from 'vs/platform/editor/common/editor';
import { ILogService } from 'vs/platform/log/common/log';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { ThemeIcon } from 'vs/base/common/themables';
import { IWorkspaceTrustManagementService, IWorkspaceTrustRequestService } from 'vs/platform/workspace/common/workspaceTrust';
import { VirtualWorkspaceContext } from 'vs/workbench/common/contextkeys';
import { EditorResourceAccessor, SaveReason } from 'vs/workbench/common/editor';
import { IViewDescriptorService, IViewsService } from 'vs/workbench/common/views';
import { configureTaskIcon, isWorkspaceFolder, ITaskQuickPickEntry, QUICKOPEN_DETAIL_CONFIG, QUICKOPEN_SKIP_CONFIG, TaskQuickPick } from 'vs/workbench/contrib/tasks/browser/taskQuickPick';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { ILifecycleService, ShutdownReason, StartupKind } from 'vs/workbench/services/lifecycle/common/lifecycle';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';
import { IPathService } from 'vs/workbench/services/path/common/pathService';
import { IPreferencesService } from 'vs/workbench/services/preferences/common/preferences';
import { TerminalExitReason } from 'vs/platform/terminal/common/terminal';
import { IRemoteAgentService } from 'vs/workbench/services/remote/common/remoteAgentService';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
const QUICKOPEN_HISTORY_LIMIT_CONFIG = 'task.quickOpen.history';
const PROBLEM_MATCHER_NEVER_CONFIG = 'task.problemMatchers.neverPrompt';
const USE_SLOW_PICKER = 'task.quickOpen.showAll';
export namespace ConfigureTaskAction {
export const ID = 'workbench.action.tasks.configureTaskRunner';
export const TEXT = nls.localize('ConfigureTaskRunnerAction.label', "Configure Task");
}
export type TaskQuickPickEntryType = (IQuickPickItem & { task: Task }) | (IQuickPickItem & { folder: IWorkspaceFolder }) | (IQuickPickItem & { settingType: string });
class ProblemReporter implements TaskConfig.IProblemReporter {
private _validationStatus: ValidationStatus;
constructor(private _outputChannel: IOutputChannel) {
this._validationStatus = new ValidationStatus();
}
public info(message: string): void {
this._validationStatus.state = ValidationState.Info;
this._outputChannel.append(message + '\n');
}
public warn(message: string): void {
this._validationStatus.state = ValidationState.Warning;
this._outputChannel.append(message + '\n');
}
public error(message: string): void {
this._validationStatus.state = ValidationState.Error;
this._outputChannel.append(message + '\n');
}
public fatal(message: string): void {
this._validationStatus.state = ValidationState.Fatal;
this._outputChannel.append(message + '\n');
}
public get status(): ValidationStatus {
return this._validationStatus;
}
}
export interface IWorkspaceFolderConfigurationResult {
workspaceFolder: IWorkspaceFolder;
config: TaskConfig.IExternalTaskRunnerConfiguration | undefined;
hasErrors: boolean;
}
interface ICommandUpgrade {
command?: string;
args?: string[];
}
class TaskMap {
private _store: Map<string, Task[]> = new Map();
public forEach(callback: (value: Task[], folder: string) => void): void {
this._store.forEach(callback);
}
public static getKey(workspaceFolder: IWorkspace | IWorkspaceFolder | string): string {
let key: string | undefined;
if (Types.isString(workspaceFolder)) {
key = workspaceFolder;
} else {
const uri: URI | null | undefined = isWorkspaceFolder(workspaceFolder) ? workspaceFolder.uri : workspaceFolder.configuration;
key = uri ? uri.toString() : '';
}
return key;
}
public get(workspaceFolder: IWorkspace | IWorkspaceFolder | string): Task[] {
const key = TaskMap.getKey(workspaceFolder);
let result: Task[] | undefined = this._store.get(key);
if (!result) {
result = [];
this._store.set(key, result);
}
return result;
}
public add(workspaceFolder: IWorkspace | IWorkspaceFolder | string, ...task: Task[]): void {
const key = TaskMap.getKey(workspaceFolder);
let values = this._store.get(key);
if (!values) {
values = [];
this._store.set(key, values);
}
values.push(...task);
}
public all(): Task[] {
const result: Task[] = [];
this._store.forEach((values) => result.push(...values));
return result;
}
}
export abstract class AbstractTaskService extends Disposable implements ITaskService {
// private static autoDetectTelemetryName: string = 'taskServer.autoDetect';
private static readonly RecentlyUsedTasks_Key = 'workbench.tasks.recentlyUsedTasks';
private static readonly RecentlyUsedTasks_KeyV2 = 'workbench.tasks.recentlyUsedTasks2';
private static readonly PersistentTasks_Key = 'workbench.tasks.persistentTasks';
private static readonly IgnoreTask010DonotShowAgain_key = 'workbench.tasks.ignoreTask010Shown';
public _serviceBrand: undefined;
public static OutputChannelId: string = 'tasks';
public static OutputChannelLabel: string = nls.localize('tasks', "Tasks");
private static _nextHandle: number = 0;
private _tasksReconnected: boolean = false;
private _schemaVersion: JsonSchemaVersion | undefined;
private _executionEngine: ExecutionEngine | undefined;
private _workspaceFolders: IWorkspaceFolder[] | undefined;
private _workspace: IWorkspace | undefined;
private _ignoredWorkspaceFolders: IWorkspaceFolder[] | undefined;
private _showIgnoreMessage?: boolean;
private _providers: Map<number, ITaskProvider>;
private _providerTypes: Map<number, string>;
protected _taskSystemInfos: Map<string, ITaskSystemInfo[]>;
protected _workspaceTasksPromise?: Promise<Map<string, IWorkspaceFolderTaskResult>>;
protected _taskSystem?: ITaskSystem;
protected _taskSystemListeners?: IDisposable[] = [];
private _recentlyUsedTasksV1: LRUCache<string, string> | undefined;
private _recentlyUsedTasks: LRUCache<string, string> | undefined;
private _persistentTasks: LRUCache<string, string> | undefined;
protected _taskRunningState: IContextKey<boolean>;
private _inProgressTasks: Set<string> = new Set();
protected _outputChannel: IOutputChannel;
protected readonly _onDidStateChange: Emitter<ITaskEvent>;
private _waitForSupportedExecutions: Promise<void>;
private _onDidRegisterSupportedExecutions: Emitter<void> = new Emitter();
private _onDidChangeTaskSystemInfo: Emitter<void> = new Emitter();
private _willRestart: boolean = false;
public onDidChangeTaskSystemInfo: Event<void> = this._onDidChangeTaskSystemInfo.event;
constructor(
@IConfigurationService private readonly _configurationService: IConfigurationService,
@IMarkerService protected readonly _markerService: IMarkerService,
@IOutputService protected readonly _outputService: IOutputService,
@IPaneCompositePartService private readonly _paneCompositeService: IPaneCompositePartService,
@IViewsService private readonly _viewsService: IViewsService,
@ICommandService private readonly _commandService: ICommandService,
@IEditorService private readonly _editorService: IEditorService,
@IFileService protected readonly _fileService: IFileService,
@IWorkspaceContextService protected readonly _contextService: IWorkspaceContextService,
@ITelemetryService protected readonly _telemetryService: ITelemetryService,
@ITextFileService private readonly _textFileService: ITextFileService,
@IModelService protected readonly _modelService: IModelService,
@IExtensionService private readonly _extensionService: IExtensionService,
@IQuickInputService private readonly _quickInputService: IQuickInputService,
@IConfigurationResolverService protected readonly _configurationResolverService: IConfigurationResolverService,
@ITerminalService private readonly _terminalService: ITerminalService,
@ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService,
@IStorageService private readonly _storageService: IStorageService,
@IProgressService private readonly _progressService: IProgressService,
@IOpenerService private readonly _openerService: IOpenerService,
@IDialogService protected readonly _dialogService: IDialogService,
@INotificationService private readonly _notificationService: INotificationService,
@IContextKeyService protected readonly _contextKeyService: IContextKeyService,
@IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService,
@ITerminalProfileResolverService private readonly _terminalProfileResolverService: ITerminalProfileResolverService,
@IPathService private readonly _pathService: IPathService,
@ITextModelService private readonly _textModelResolverService: ITextModelService,
@IPreferencesService private readonly _preferencesService: IPreferencesService,
@IViewDescriptorService private readonly _viewDescriptorService: IViewDescriptorService,
@IWorkspaceTrustRequestService private readonly _workspaceTrustRequestService: IWorkspaceTrustRequestService,
@IWorkspaceTrustManagementService private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService,
@ILogService private readonly _logService: ILogService,
@IThemeService private readonly _themeService: IThemeService,
@ILifecycleService private readonly _lifecycleService: ILifecycleService,
@IRemoteAgentService remoteAgentService: IRemoteAgentService,
@IInstantiationService private readonly _instantiationService: IInstantiationService
) {
super();
this._workspaceTasksPromise = undefined;
this._taskSystem = undefined;
this._taskSystemListeners = undefined;
this._outputChannel = this._outputService.getChannel(AbstractTaskService.OutputChannelId)!;
this._providers = new Map<number, ITaskProvider>();
this._providerTypes = new Map<number, string>();
this._taskSystemInfos = new Map<string, ITaskSystemInfo[]>();
this._register(this._contextService.onDidChangeWorkspaceFolders(() => {
const folderSetup = this._computeWorkspaceFolderSetup();
if (this.executionEngine !== folderSetup[2]) {
this._disposeTaskSystemListeners();
this._taskSystem = undefined;
}
this._updateSetup(folderSetup);
return this._updateWorkspaceTasks(TaskRunSource.FolderOpen);
}));
this._register(this._configurationService.onDidChangeConfiguration((e) => {
if (!e.affectsConfiguration('tasks') || (!this._taskSystem && !this._workspaceTasksPromise)) {
return;
}
if (!this._taskSystem || this._taskSystem instanceof TerminalTaskSystem) {
this._outputChannel.clear();
}
this._setTaskLRUCacheLimit();
return this._updateWorkspaceTasks(TaskRunSource.ConfigurationChange);
}));
this._taskRunningState = TASK_RUNNING_STATE.bindTo(_contextKeyService);
this._onDidStateChange = this._register(new Emitter());
this._registerCommands().then(() => TaskCommandsRegistered.bindTo(this._contextKeyService).set(true));
ServerlessWebContext.bindTo(this._contextKeyService).set(Platform.isWeb && !remoteAgentService.getConnection()?.remoteAuthority);
this._configurationResolverService.contributeVariable('defaultBuildTask', async (): Promise<string | undefined> => {
let tasks = await this._getTasksForGroup(TaskGroup.Build);
if (tasks.length > 0) {
const { none, defaults } = this._splitPerGroupType(tasks);
if (defaults.length === 1) {
return defaults[0]._label;
} else if (defaults.length + none.length > 0) {
tasks = defaults.concat(none);
}
}
let entry: ITaskQuickPickEntry | null | undefined;
if (tasks && tasks.length > 0) {
entry = await this._showQuickPick(tasks, nls.localize('TaskService.pickBuildTaskForLabel', 'Select the build task (there is no default build task defined)'));
}
const task: Task | undefined | null = entry ? entry.task : undefined;
if (!task) {
return undefined;
}
return task._label;
});
this._lifecycleService.onBeforeShutdown(e => {
this._willRestart = e.reason !== ShutdownReason.RELOAD;
});
this._register(this.onDidStateChange(e => {
if ((this._willRestart || e.exitReason === TerminalExitReason.User) && e.taskId) {
this.removePersistentTask(e.taskId);
} else if (e.kind === TaskEventKind.Start && e.__task && e.__task.getWorkspaceFolder()) {
this._setPersistentTask(e.__task);
}
}));
this._waitForSupportedExecutions = new Promise(resolve => {
once(this._onDidRegisterSupportedExecutions.event)(() => resolve());
});
if (this._terminalService.getReconnectedTerminals('Task')?.length) {
this._attemptTaskReconnection();
} else {
this._register(this._terminalService.onDidChangeConnectionState(() => {
if (this._terminalService.getReconnectedTerminals('Task')?.length) {
this._attemptTaskReconnection();
}
}));
}
this._upgrade();
}
public registerSupportedExecutions(custom?: boolean, shell?: boolean, process?: boolean) {
if (custom !== undefined) {
const customContext = CustomExecutionSupportedContext.bindTo(this._contextKeyService);
customContext.set(custom);
}
const isVirtual = !!VirtualWorkspaceContext.getValue(this._contextKeyService);
if (shell !== undefined) {
const shellContext = ShellExecutionSupportedContext.bindTo(this._contextKeyService);
shellContext.set(shell && !isVirtual);
}
if (process !== undefined) {
const processContext = ProcessExecutionSupportedContext.bindTo(this._contextKeyService);
processContext.set(process && !isVirtual);
}
this._onDidRegisterSupportedExecutions.fire();
}
private _attemptTaskReconnection(): void {
if (this._lifecycleService.startupKind !== StartupKind.ReloadedWindow) {
this._tasksReconnected = true;
this._storageService.remove(AbstractTaskService.PersistentTasks_Key, StorageScope.WORKSPACE);
}
if (!this._configurationService.getValue(TaskSettingId.Reconnection) || this._tasksReconnected) {
this._tasksReconnected = true;
return;
}
this._getTaskSystem();
this.getWorkspaceTasks().then(async () => {
this._tasksReconnected = await this._reconnectTasks();
});
}
private async _reconnectTasks(): Promise<boolean> {
const tasks = await this.getSavedTasks('persistent');
if (!tasks.length) {
return true;
}
for (const task of tasks) {
if (ConfiguringTask.is(task)) {
const resolved = await this.tryResolveTask(task);
if (resolved) {
this.run(resolved, undefined, TaskRunSource.Reconnect);
}
} else {
this.run(task, undefined, TaskRunSource.Reconnect);
}
}
return true;
}
public get onDidStateChange(): Event<ITaskEvent> {
return this._onDidStateChange.event;
}
public get supportsMultipleTaskExecutions(): boolean {
return this.inTerminal();
}
private async _registerCommands(): Promise<void> {
CommandsRegistry.registerCommand({
id: 'workbench.action.tasks.runTask',
handler: async (accessor, arg) => {
if (await this._trust()) {
this._runTaskCommand(arg);
}
},
description: {
description: 'Run Task',
args: [{
name: 'args',
isOptional: true,
description: nls.localize('runTask.arg', "Filters the tasks shown in the quickpick"),
schema: {
anyOf: [
{
type: 'string',
description: nls.localize('runTask.label', "The task's label or a term to filter by")
},
{
type: 'object',
properties: {
type: {
type: 'string',
description: nls.localize('runTask.type', "The contributed task type")
},
task: {
type: 'string',
description: nls.localize('runTask.task', "The task's label or a term to filter by")
}
}
}
]
}
}]
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.reRunTask', async (accessor, arg) => {
if (await this._trust()) {
this._reRunTaskCommand();
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.restartTask', async (accessor, arg) => {
if (await this._trust()) {
this._runRestartTaskCommand(arg);
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.terminate', async (accessor, arg) => {
if (await this._trust()) {
this._runTerminateCommand(arg);
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.showLog', () => {
this._showOutput();
});
CommandsRegistry.registerCommand('workbench.action.tasks.build', async () => {
if (await this._trust()) {
this._runBuildCommand();
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.test', async () => {
if (await this._trust()) {
this._runTestCommand();
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.configureTaskRunner', async () => {
if (await this._trust()) {
this._runConfigureTasks();
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultBuildTask', async () => {
if (await this._trust()) {
this._runConfigureDefaultBuildTask();
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.configureDefaultTestTask', async () => {
if (await this._trust()) {
this._runConfigureDefaultTestTask();
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.showTasks', async () => {
if (await this._trust()) {
return this.runShowTasks();
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.toggleProblems', () => this._commandService.executeCommand(Markers.TOGGLE_MARKERS_VIEW_ACTION_ID));
CommandsRegistry.registerCommand('workbench.action.tasks.openUserTasks', async () => {
const resource = this._getResourceForKind(TaskSourceKind.User);
if (resource) {
this._openTaskFile(resource, TaskSourceKind.User);
}
});
CommandsRegistry.registerCommand('workbench.action.tasks.openWorkspaceFileTasks', async () => {
const resource = this._getResourceForKind(TaskSourceKind.WorkspaceFile);
if (resource) {
this._openTaskFile(resource, TaskSourceKind.WorkspaceFile);
}
});
}
private get workspaceFolders(): IWorkspaceFolder[] {
if (!this._workspaceFolders) {
this._updateSetup();
}
return this._workspaceFolders!;
}
private get ignoredWorkspaceFolders(): IWorkspaceFolder[] {
if (!this._ignoredWorkspaceFolders) {
this._updateSetup();
}
return this._ignoredWorkspaceFolders!;
}
protected get executionEngine(): ExecutionEngine {
if (this._executionEngine === undefined) {
this._updateSetup();
}
return this._executionEngine!;
}
private get schemaVersion(): JsonSchemaVersion {
if (this._schemaVersion === undefined) {
this._updateSetup();
}
return this._schemaVersion!;
}
private get showIgnoreMessage(): boolean {
if (this._showIgnoreMessage === undefined) {
this._showIgnoreMessage = !this._storageService.getBoolean(AbstractTaskService.IgnoreTask010DonotShowAgain_key, StorageScope.WORKSPACE, false);
}
return this._showIgnoreMessage;
}
private _getActivationEvents(type: string | undefined): string[] {
const result: string[] = [];
result.push('onCommand:workbench.action.tasks.runTask');
if (type) {
// send a specific activation event for this task type
result.push(`onTaskType:${type}`);
} else {
// send activation events for all task types
for (const definition of TaskDefinitionRegistry.all()) {
result.push(`onTaskType:${definition.taskType}`);
}
}
return result;
}
private async _activateTaskProviders(type: string | undefined): Promise<void> {
// We need to first wait for extensions to be registered because we might read
// the `TaskDefinitionRegistry` in case `type` is `undefined`
await this._extensionService.whenInstalledExtensionsRegistered();
await Promise.all(
this._getActivationEvents(type).map(activationEvent => this._extensionService.activateByEvent(activationEvent))
);
}
private _updateSetup(setup?: [IWorkspaceFolder[], IWorkspaceFolder[], ExecutionEngine, JsonSchemaVersion, IWorkspace | undefined]): void {
if (!setup) {
setup = this._computeWorkspaceFolderSetup();
}
this._workspaceFolders = setup[0];
if (this._ignoredWorkspaceFolders) {
if (this._ignoredWorkspaceFolders.length !== setup[1].length) {
this._showIgnoreMessage = undefined;
} else {
const set: Set<string> = new Set();
this._ignoredWorkspaceFolders.forEach(folder => set.add(folder.uri.toString()));
for (const folder of setup[1]) {
if (!set.has(folder.uri.toString())) {
this._showIgnoreMessage = undefined;
break;
}
}
}
}
this._ignoredWorkspaceFolders = setup[1];
this._executionEngine = setup[2];
this._schemaVersion = setup[3];
this._workspace = setup[4];
}
protected _showOutput(runSource: TaskRunSource = TaskRunSource.User): void {
if (!VirtualWorkspaceContext.getValue(this._contextKeyService) && ((runSource === TaskRunSource.User) || (runSource === TaskRunSource.ConfigurationChange))) {
this._notificationService.prompt(Severity.Warning, nls.localize('taskServiceOutputPrompt', 'There are task errors. See the output for details.'),
[{
label: nls.localize('showOutput', "Show output"),
run: () => {
this._outputService.showChannel(this._outputChannel.id, true);
}
}]);
}
}
protected _disposeTaskSystemListeners(): void {
if (this._taskSystemListeners) {
dispose(this._taskSystemListeners);
this._taskSystemListeners = undefined;
}
}
public registerTaskProvider(provider: ITaskProvider, type: string): IDisposable {
if (!provider) {
return {
dispose: () => { }
};
}
const handle = AbstractTaskService._nextHandle++;
this._providers.set(handle, provider);
this._providerTypes.set(handle, type);
return {
dispose: () => {
this._providers.delete(handle);
this._providerTypes.delete(handle);
}
};
}
get hasTaskSystemInfo(): boolean {
const infosCount = Array.from(this._taskSystemInfos.values()).flat().length;
// If there's a remoteAuthority, then we end up with 2 taskSystemInfos,
// one for each extension host.
if (this._environmentService.remoteAuthority) {
return infosCount > 1;
}
return infosCount > 0;
}
public registerTaskSystem(key: string, info: ITaskSystemInfo): void {
// Ideally the Web caller of registerRegisterTaskSystem would use the correct key.
// However, the caller doesn't know about the workspace folders at the time of the call, even though we know about them here.
if (info.platform === Platform.Platform.Web) {
key = this.workspaceFolders.length ? this.workspaceFolders[0].uri.scheme : key;
}
if (!this._taskSystemInfos.has(key)) {
this._taskSystemInfos.set(key, [info]);
} else {
const infos = this._taskSystemInfos.get(key)!;
if (info.platform === Platform.Platform.Web) {
// Web infos should be pushed last.
infos.push(info);
} else {
infos.unshift(info);
}
}
if (this.hasTaskSystemInfo) {
this._onDidChangeTaskSystemInfo.fire();
}
}
private _getTaskSystemInfo(key: string): ITaskSystemInfo | undefined {
const infos = this._taskSystemInfos.get(key);
return (infos && infos.length) ? infos[0] : undefined;
}
public extensionCallbackTaskComplete(task: Task, result: number): Promise<void> {
if (!this._taskSystem) {
return Promise.resolve();
}
return this._taskSystem.customExecutionComplete(task, result);
}
/**
* Get a subset of workspace tasks that match a certain predicate.
*/
private async _findWorkspaceTasks(predicate: (task: ConfiguringTask | Task, workspaceFolder: IWorkspaceFolder) => boolean): Promise<(ConfiguringTask | Task)[]> {
const result: (ConfiguringTask | Task)[] = [];
const tasks = await this.getWorkspaceTasks();
for (const [, workspaceTasks] of tasks) {
if (workspaceTasks.configurations) {
for (const taskName in workspaceTasks.configurations.byIdentifier) {
const task = workspaceTasks.configurations.byIdentifier[taskName];
if (predicate(task, workspaceTasks.workspaceFolder)) {
result.push(task);
}
}
}
if (workspaceTasks.set) {
for (const task of workspaceTasks.set.tasks) {
if (predicate(task, workspaceTasks.workspaceFolder)) {
result.push(task);
}
}
}
}
return result;
}
private async _findWorkspaceTasksInGroup(group: TaskGroup, isDefault: boolean): Promise<(ConfiguringTask | Task)[]> {
return this._findWorkspaceTasks((task) => {
const taskGroup = task.configurationProperties.group;
if (taskGroup && typeof taskGroup !== 'string') {
return (taskGroup._id === group._id && (!isDefault || !!taskGroup.isDefault));
}
return false;
});
}
public async getTask(folder: IWorkspace | IWorkspaceFolder | string, identifier: string | ITaskIdentifier, compareId: boolean = false): Promise<Task | undefined> {
if (!(await this._trust())) {
return;
}
const name = Types.isString(folder) ? folder : isWorkspaceFolder(folder) ? folder.name : folder.configuration ? resources.basename(folder.configuration) : undefined;
if (this.ignoredWorkspaceFolders.some(ignored => ignored.name === name)) {
return Promise.reject(new Error(nls.localize('TaskServer.folderIgnored', 'The folder {0} is ignored since it uses task version 0.1.0', name)));
}
const key: string | KeyedTaskIdentifier | undefined = !Types.isString(identifier)
? TaskDefinition.createTaskIdentifier(identifier, console)
: identifier;
if (key === undefined) {
return Promise.resolve(undefined);
}
// Try to find the task in the workspace
const requestedFolder = TaskMap.getKey(folder);
const matchedTasks = await this._findWorkspaceTasks((task, workspaceFolder) => {
const taskFolder = TaskMap.getKey(workspaceFolder);
if (taskFolder !== requestedFolder && taskFolder !== USER_TASKS_GROUP_KEY) {
return false;
}
return task.matches(key, compareId);
});
matchedTasks.sort(task => task._source.kind === TaskSourceKind.Extension ? 1 : -1);
if (matchedTasks.length > 0) {
// Nice, we found a configured task!
const task = matchedTasks[0];
if (ConfiguringTask.is(task)) {
return this.tryResolveTask(task);
} else {
return task;
}
}
// We didn't find the task, so we need to ask all resolvers about it
const map = await this._getGroupedTasks();
let values = map.get(folder);
values = values.concat(map.get(USER_TASKS_GROUP_KEY));
if (!values) {
return undefined;
}
values = values.filter(task => task.matches(key, compareId)).sort(task => task._source.kind === TaskSourceKind.Extension ? 1 : -1);
return values.length > 0 ? values[0] : undefined;
}
public async tryResolveTask(configuringTask: ConfiguringTask): Promise<Task | undefined> {
if (!(await this._trust())) {
return;
}
await this._activateTaskProviders(configuringTask.type);
let matchingProvider: ITaskProvider | undefined;
let matchingProviderUnavailable: boolean = false;
for (const [handle, provider] of this._providers) {
const providerType = this._providerTypes.get(handle);
if (configuringTask.type === providerType) {
if (providerType && !this._isTaskProviderEnabled(providerType)) {
matchingProviderUnavailable = true;
continue;
}
matchingProvider = provider;
break;
}
}
if (!matchingProvider) {
if (matchingProviderUnavailable) {
this._outputChannel.append(nls.localize(
'TaskService.providerUnavailable',
'Warning: {0} tasks are unavailable in the current environment.\n',
configuringTask.configures.type
));
}
return;
}
// Try to resolve the task first
try {
const resolvedTask = await matchingProvider.resolveTask(configuringTask);
if (resolvedTask && (resolvedTask._id === configuringTask._id)) {
return TaskConfig.createCustomTask(resolvedTask, configuringTask);
}
} catch (error) {
// Ignore errors. The task could not be provided by any of the providers.
}
// The task couldn't be resolved. Instead, use the less efficient provideTask.
const tasks = await this.tasks({ type: configuringTask.type });
for (const task of tasks) {
if (task._id === configuringTask._id) {
return TaskConfig.createCustomTask(<ContributedTask>task, configuringTask);
}
}
return;
}
protected abstract _versionAndEngineCompatible(filter?: ITaskFilter): boolean;
public async tasks(filter?: ITaskFilter): Promise<Task[]> {
if (!(await this._trust())) {
return [];
}
if (!this._versionAndEngineCompatible(filter)) {
return Promise.resolve<Task[]>([]);
}
return this._getGroupedTasks(filter).then((map) => {
if (!filter || !filter.type) {
return map.all();
}
const result: Task[] = [];
map.forEach((tasks) => {
for (const task of tasks) {
if (ContributedTask.is(task) && ((task.defines.type === filter.type) || (task._source.label === filter.type))) {
result.push(task);
} else if (CustomTask.is(task)) {
if (task.type === filter.type) {
result.push(task);
} else {
const customizes = task.customizes();
if (customizes && customizes.type === filter.type) {
result.push(task);
}
}
}
}
});
return result;
});
}
public taskTypes(): string[] {
const types: string[] = [];
if (this._isProvideTasksEnabled()) {
for (const definition of TaskDefinitionRegistry.all()) {
if (this._isTaskProviderEnabled(definition.taskType)) {
types.push(definition.taskType);
}
}
}
return types;
}
public createSorter(): TaskSorter {
return new TaskSorter(this._contextService.getWorkspace() ? this._contextService.getWorkspace().folders : []);
}
private _isActive(): Promise<boolean> {
if (!this._taskSystem) {
return Promise.resolve(false);
}
return this._taskSystem.isActive();
}
public async getActiveTasks(): Promise<Task[]> {
if (!this._taskSystem) {
return [];
}
return this._taskSystem.getActiveTasks();
}
public async getBusyTasks(): Promise<Task[]> {
if (!this._taskSystem) {
return [];
}
return this._taskSystem.getBusyTasks();
}
public getRecentlyUsedTasksV1(): LRUCache<string, string> {
if (this._recentlyUsedTasksV1) {
return this._recentlyUsedTasksV1;
}
const quickOpenHistoryLimit = this._configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
this._recentlyUsedTasksV1 = new LRUCache<string, string>(quickOpenHistoryLimit);
const storageValue = this._storageService.get(AbstractTaskService.RecentlyUsedTasks_Key, StorageScope.WORKSPACE);
if (storageValue) {
try {
const values: string[] = JSON.parse(storageValue);
if (Array.isArray(values)) {
for (const value of values) {
this._recentlyUsedTasksV1.set(value, value);
}
}
} catch (error) {
// Ignore. We use the empty result
}
}
return this._recentlyUsedTasksV1;
}
private _getTasksFromStorage(type: 'persistent' | 'historical'): LRUCache<string, string> {
return type === 'persistent' ? this._getPersistentTasks() : this._getRecentTasks();
}
private _getRecentTasks(): LRUCache<string, string> {
if (this._recentlyUsedTasks) {
return this._recentlyUsedTasks;
}
const quickOpenHistoryLimit = this._configurationService.getValue<number>(QUICKOPEN_HISTORY_LIMIT_CONFIG);
this._recentlyUsedTasks = new LRUCache<string, string>(quickOpenHistoryLimit);
const storageValue = this._storageService.get(AbstractTaskService.RecentlyUsedTasks_KeyV2, StorageScope.WORKSPACE);
if (storageValue) {
try {
const values: [string, string][] = JSON.parse(storageValue);
if (Array.isArray(values)) {
for (const value of values) {
this._recentlyUsedTasks.set(value[0], value[1]);
}
}
} catch (error) {
// Ignore. We use the empty result
}
}
return this._recentlyUsedTasks;
}
private _getPersistentTasks(): LRUCache<string, string> {
if (this._persistentTasks) {
return this._persistentTasks;
}
//TODO: should this # be configurable?
this._persistentTasks = new LRUCache<string, string>(10);
const storageValue = this._storageService.get(AbstractTaskService.PersistentTasks_Key, StorageScope.WORKSPACE);
if (storageValue) {
try {
const values: [string, string][] = JSON.parse(storageValue);
if (Array.isArray(values)) {
for (const value of values) {
this._persistentTasks.set(value[0], value[1]);
}
}
} catch (error) {
// Ignore. We use the empty result
}
}
return this._persistentTasks;
}
private _getFolderFromTaskKey(key: string): { folder: string | undefined; isWorkspaceFile: boolean | undefined } {
const keyValue: { folder: string | undefined; id: string | undefined } = JSON.parse(key);
return {
folder: keyValue.folder, isWorkspaceFile: keyValue.id?.endsWith(TaskSourceKind.WorkspaceFile)
};
}
public async getSavedTasks(type: 'persistent' | 'historical'): Promise<(Task | ConfiguringTask)[]> {
const folderMap: IStringDictionary<IWorkspaceFolder> = Object.create(null);
this.workspaceFolders.forEach(folder => {
folderMap[folder.uri.toString()] = folder;
});
const folderToTasksMap: Map<string, any> = new Map();
const workspaceToTaskMap: Map<string, any> = new Map();
const storedTasks = this._getTasksFromStorage(type);
const tasks: (Task | ConfiguringTask)[] = [];
function addTaskToMap(map: Map<string, any>, folder: string | undefined, task: any) {
if (folder && !map.has(folder)) {
map.set(folder, []);
}
if (folder && (folderMap[folder] || (folder === USER_TASKS_GROUP_KEY)) && task) {
map.get(folder).push(task);
}
}
for (const entry of storedTasks.entries()) {
const key = entry[0];
const task = JSON.parse(entry[1]);
const folderInfo = this._getFolderFromTaskKey(key);
addTaskToMap(folderInfo.isWorkspaceFile ? workspaceToTaskMap : folderToTasksMap, folderInfo.folder, task);
}
const readTasksMap: Map<string, (Task | ConfiguringTask)> = new Map();