@theia/task 1.34.2 → 1.34.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/LICENSE +641 -641
  2. package/README.md +193 -193
  3. package/lib/browser/index.d.ts +6 -6
  4. package/lib/browser/index.js +33 -33
  5. package/lib/browser/process/process-task-contribution.d.ts +6 -6
  6. package/lib/browser/process/process-task-contribution.js +43 -43
  7. package/lib/browser/process/process-task-frontend-module.d.ts +2 -2
  8. package/lib/browser/process/process-task-frontend-module.js +27 -27
  9. package/lib/browser/process/process-task-resolver.d.ts +17 -17
  10. package/lib/browser/process/process-task-resolver.js +93 -93
  11. package/lib/browser/provided-task-configurations.d.ts +32 -32
  12. package/lib/browser/provided-task-configurations.js +171 -171
  13. package/lib/browser/provided-task-configurations.spec.d.ts +1 -1
  14. package/lib/browser/provided-task-configurations.spec.js +43 -43
  15. package/lib/browser/quick-open-task.d.ts +129 -129
  16. package/lib/browser/quick-open-task.js +636 -636
  17. package/lib/browser/task-configuration-manager.d.ts +64 -64
  18. package/lib/browser/task-configuration-manager.js +261 -261
  19. package/lib/browser/task-configuration-model.d.ts +32 -32
  20. package/lib/browser/task-configuration-model.js +79 -79
  21. package/lib/browser/task-configurations.d.ts +127 -127
  22. package/lib/browser/task-configurations.js +479 -479
  23. package/lib/browser/task-contribution.d.ts +173 -173
  24. package/lib/browser/task-contribution.js +199 -199
  25. package/lib/browser/task-definition-registry.d.ts +38 -38
  26. package/lib/browser/task-definition-registry.js +131 -131
  27. package/lib/browser/task-definition-registry.spec.d.ts +1 -1
  28. package/lib/browser/task-definition-registry.spec.js +170 -170
  29. package/lib/browser/task-frontend-contribution.d.ts +56 -56
  30. package/lib/browser/task-frontend-contribution.js +353 -353
  31. package/lib/browser/task-frontend-module.d.ts +5 -5
  32. package/lib/browser/task-frontend-module.js +79 -79
  33. package/lib/browser/task-name-resolver.d.ts +13 -13
  34. package/lib/browser/task-name-resolver.js +65 -65
  35. package/lib/browser/task-node.d.ts +9 -9
  36. package/lib/browser/task-node.js +17 -17
  37. package/lib/browser/task-preferences.d.ts +4 -4
  38. package/lib/browser/task-preferences.js +40 -40
  39. package/lib/browser/task-problem-matcher-registry.d.ts +40 -40
  40. package/lib/browser/task-problem-matcher-registry.js +310 -310
  41. package/lib/browser/task-problem-pattern-registry.d.ts +23 -23
  42. package/lib/browser/task-problem-pattern-registry.js +208 -208
  43. package/lib/browser/task-schema-updater.d.ts +58 -58
  44. package/lib/browser/task-schema-updater.js +672 -672
  45. package/lib/browser/task-service.d.ts +276 -276
  46. package/lib/browser/task-service.js +1119 -1119
  47. package/lib/browser/task-source-resolver.d.ts +9 -9
  48. package/lib/browser/task-source-resolver.js +51 -51
  49. package/lib/browser/task-templates.d.ts +13 -13
  50. package/lib/browser/task-templates.js +161 -161
  51. package/lib/browser/task-terminal-widget-manager.d.ts +44 -44
  52. package/lib/browser/task-terminal-widget-manager.js +224 -224
  53. package/lib/browser/tasks-monaco-contribution.d.ts +1 -1
  54. package/lib/browser/tasks-monaco-contribution.js +27 -27
  55. package/lib/common/index.d.ts +3 -3
  56. package/lib/common/index.js +30 -30
  57. package/lib/common/problem-matcher-protocol.d.ts +124 -124
  58. package/lib/common/problem-matcher-protocol.js +132 -132
  59. package/lib/common/process/task-protocol.d.ts +68 -68
  60. package/lib/common/process/task-protocol.js +33 -33
  61. package/lib/common/task-common-module.d.ts +7 -7
  62. package/lib/common/task-common-module.js +33 -33
  63. package/lib/common/task-protocol.d.ts +190 -190
  64. package/lib/common/task-protocol.js +125 -125
  65. package/lib/common/task-watcher.d.ts +17 -17
  66. package/lib/common/task-watcher.js +86 -86
  67. package/lib/node/custom/custom-task-runner-backend-module.d.ts +2 -2
  68. package/lib/node/custom/custom-task-runner-backend-module.js +36 -36
  69. package/lib/node/custom/custom-task-runner-contribution.d.ts +6 -6
  70. package/lib/node/custom/custom-task-runner-contribution.js +42 -42
  71. package/lib/node/custom/custom-task-runner.d.ts +15 -15
  72. package/lib/node/custom/custom-task-runner.js +69 -69
  73. package/lib/node/custom/custom-task.d.ts +20 -20
  74. package/lib/node/custom/custom-task.js +78 -78
  75. package/lib/node/index.d.ts +3 -3
  76. package/lib/node/index.js +30 -30
  77. package/lib/node/process/process-task-runner-backend-module.d.ts +2 -2
  78. package/lib/node/process/process-task-runner-backend-module.js +36 -36
  79. package/lib/node/process/process-task-runner-contribution.d.ts +6 -6
  80. package/lib/node/process/process-task-runner-contribution.js +43 -43
  81. package/lib/node/process/process-task-runner.d.ts +60 -60
  82. package/lib/node/process/process-task-runner.js +352 -352
  83. package/lib/node/process/process-task.d.ts +26 -26
  84. package/lib/node/process/process-task.js +139 -139
  85. package/lib/node/process/process-task.spec.d.ts +1 -1
  86. package/lib/node/process/process-task.spec.js +29 -29
  87. package/lib/node/task-abstract-line-matcher.d.ts +49 -49
  88. package/lib/node/task-abstract-line-matcher.js +278 -278
  89. package/lib/node/task-backend-application-contribution.d.ts +8 -8
  90. package/lib/node/task-backend-application-contribution.js +48 -48
  91. package/lib/node/task-backend-module.d.ts +3 -3
  92. package/lib/node/task-backend-module.js +50 -50
  93. package/lib/node/task-line-matchers.d.ts +27 -27
  94. package/lib/node/task-line-matchers.js +121 -121
  95. package/lib/node/task-manager.d.ts +55 -55
  96. package/lib/node/task-manager.js +135 -135
  97. package/lib/node/task-problem-collector.d.ts +10 -10
  98. package/lib/node/task-problem-collector.js +57 -57
  99. package/lib/node/task-problem-collector.spec.d.ts +1 -1
  100. package/lib/node/task-problem-collector.spec.js +310 -310
  101. package/lib/node/task-runner-protocol.d.ts +16 -16
  102. package/lib/node/task-runner-protocol.js +19 -19
  103. package/lib/node/task-runner.d.ts +50 -50
  104. package/lib/node/task-runner.js +97 -97
  105. package/lib/node/task-server.d.ts +39 -39
  106. package/lib/node/task-server.js +237 -237
  107. package/lib/node/task-server.slow-spec.d.ts +1 -1
  108. package/lib/node/task-server.slow-spec.js +395 -395
  109. package/lib/node/task.d.ts +50 -50
  110. package/lib/node/task.js +77 -77
  111. package/lib/node/test/task-test-container.d.ts +2 -2
  112. package/lib/node/test/task-test-container.js +58 -58
  113. package/package.json +13 -13
  114. package/src/browser/index.ts +22 -22
  115. package/src/browser/process/process-task-contribution.ts +31 -31
  116. package/src/browser/process/process-task-frontend-module.ts +27 -27
  117. package/src/browser/process/process-task-resolver.ts +89 -89
  118. package/src/browser/provided-task-configurations.spec.ts +46 -46
  119. package/src/browser/provided-task-configurations.ts +170 -170
  120. package/src/browser/quick-open-task.ts +701 -701
  121. package/src/browser/style/index.css +19 -19
  122. package/src/browser/task-configuration-manager.ts +256 -256
  123. package/src/browser/task-configuration-model.ts +101 -101
  124. package/src/browser/task-configurations.ts +507 -507
  125. package/src/browser/task-contribution.ts +254 -254
  126. package/src/browser/task-definition-registry.spec.ts +203 -203
  127. package/src/browser/task-definition-registry.ts +128 -128
  128. package/src/browser/task-frontend-contribution.ts +396 -396
  129. package/src/browser/task-frontend-module.ts +86 -86
  130. package/src/browser/task-name-resolver.ts +55 -55
  131. package/src/browser/task-node.ts +37 -37
  132. package/src/browser/task-preferences.ts +40 -40
  133. package/src/browser/task-problem-matcher-registry.ts +308 -308
  134. package/src/browser/task-problem-pattern-registry.ts +195 -195
  135. package/src/browser/task-schema-updater.ts +703 -703
  136. package/src/browser/task-service.ts +1163 -1163
  137. package/src/browser/task-source-resolver.ts +36 -36
  138. package/src/browser/task-templates.ts +168 -168
  139. package/src/browser/task-terminal-widget-manager.ts +221 -221
  140. package/src/browser/tasks-monaco-contribution.ts +27 -27
  141. package/src/common/index.ts +19 -19
  142. package/src/common/problem-matcher-protocol.ts +235 -235
  143. package/src/common/process/task-protocol.ts +97 -97
  144. package/src/common/task-common-module.ts +34 -34
  145. package/src/common/task-protocol.ts +310 -310
  146. package/src/common/task-watcher.ts +78 -78
  147. package/src/node/custom/custom-task-runner-backend-module.ts +37 -37
  148. package/src/node/custom/custom-task-runner-contribution.ts +30 -30
  149. package/src/node/custom/custom-task-runner.ts +60 -60
  150. package/src/node/custom/custom-task.ts +73 -73
  151. package/src/node/index.ts +19 -19
  152. package/src/node/process/process-task-runner-backend-module.ts +37 -37
  153. package/src/node/process/process-task-runner-contribution.ts +31 -31
  154. package/src/node/process/process-task-runner.ts +371 -371
  155. package/src/node/process/process-task.spec.ts +30 -30
  156. package/src/node/process/process-task.ts +147 -147
  157. package/src/node/task-abstract-line-matcher.ts +317 -317
  158. package/src/node/task-backend-application-contribution.ts +36 -36
  159. package/src/node/task-backend-module.ts +57 -57
  160. package/src/node/task-line-matchers.ts +127 -127
  161. package/src/node/task-manager.ts +129 -129
  162. package/src/node/task-problem-collector.spec.ts +338 -338
  163. package/src/node/task-problem-collector.ts +62 -62
  164. package/src/node/task-runner-protocol.ts +33 -33
  165. package/src/node/task-runner.ts +96 -96
  166. package/src/node/task-server.slow-spec.ts +444 -444
  167. package/src/node/task-server.ts +263 -263
  168. package/src/node/task.ts +103 -103
  169. package/src/node/test/task-test-container.ts +63 -63
@@ -1,1163 +1,1163 @@
1
- // *****************************************************************************
2
- // Copyright (C) 2017 Ericsson and others.
3
- //
4
- // This program and the accompanying materials are made available under the
5
- // terms of the Eclipse Public License v. 2.0 which is available at
6
- // http://www.eclipse.org/legal/epl-2.0.
7
- //
8
- // This Source Code may also be made available under the following Secondary
9
- // Licenses when the conditions for such availability set forth in the Eclipse
10
- // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
- // with the GNU Classpath Exception which is available at
12
- // https://www.gnu.org/software/classpath/license.html.
13
- //
14
- // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15
- // *****************************************************************************
16
-
17
- import { ApplicationShell, FrontendApplication, QuickPickValue, WidgetManager, WidgetOpenMode } from '@theia/core/lib/browser';
18
- import { open, OpenerService } from '@theia/core/lib/browser/opener-service';
19
- import { CommandService, ILogger } from '@theia/core/lib/common';
20
- import { MessageService } from '@theia/core/lib/common/message-service';
21
- import { Deferred } from '@theia/core/lib/common/promise-util';
22
- import { QuickPickItemOrSeparator, QuickPickService } from '@theia/core/lib/common/quick-pick-service';
23
- import { LabelProvider } from '@theia/core/lib/browser/label-provider';
24
- import URI from '@theia/core/lib/common/uri';
25
- import { EditorManager } from '@theia/editor/lib/browser';
26
- import { ProblemManager } from '@theia/markers/lib/browser/problem/problem-manager';
27
- import { TerminalService } from '@theia/terminal/lib/browser/base/terminal-service';
28
- import { TerminalWidget } from '@theia/terminal/lib/browser/base/terminal-widget';
29
- import { TerminalWidgetFactoryOptions } from '@theia/terminal/lib/browser/terminal-widget-impl';
30
- import { VariableResolverService } from '@theia/variable-resolver/lib/browser';
31
- import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
32
- import { inject, injectable, named, postConstruct } from '@theia/core/shared/inversify';
33
- import { DiagnosticSeverity, Range } from '@theia/core/shared/vscode-languageserver-protocol';
34
- import {
35
- ApplyToKind,
36
- BackgroundTaskEndedEvent,
37
- DependsOrder,
38
- NamedProblemMatcher,
39
- ProblemMatchData,
40
- ProblemMatcher,
41
- RevealKind,
42
- RunTaskOption,
43
- TaskConfiguration,
44
- TaskConfigurationScope,
45
- TaskCustomization,
46
- TaskExitedEvent,
47
- TaskIdentifier,
48
- TaskInfo,
49
- TaskOutputPresentation,
50
- TaskOutputProcessedEvent,
51
- TaskServer
52
- } from '../common';
53
- import { TaskWatcher } from '../common/task-watcher';
54
- import { ProvidedTaskConfigurations } from './provided-task-configurations';
55
- import { TaskConfigurationClient, TaskConfigurations } from './task-configurations';
56
- import { TaskResolverRegistry } from './task-contribution';
57
- import { TaskDefinitionRegistry } from './task-definition-registry';
58
- import { TaskNameResolver } from './task-name-resolver';
59
- import { TaskSourceResolver } from './task-source-resolver';
60
- import { ProblemMatcherRegistry } from './task-problem-matcher-registry';
61
- import { TaskSchemaUpdater } from './task-schema-updater';
62
- import { TaskConfigurationManager } from './task-configuration-manager';
63
- import { PROBLEMS_WIDGET_ID, ProblemWidget } from '@theia/markers/lib/browser/problem/problem-widget';
64
- import { TaskNode } from './task-node';
65
- import { MonacoWorkspace } from '@theia/monaco/lib/browser/monaco-workspace';
66
- import { TaskTerminalWidgetManager } from './task-terminal-widget-manager';
67
- import { ShellTerminalServerProxy } from '@theia/terminal/lib/common/shell-terminal-protocol';
68
- import { Mutex } from 'async-mutex';
69
-
70
- export interface QuickPickProblemMatcherItem {
71
- problemMatchers: NamedProblemMatcher[] | undefined;
72
- learnMore?: boolean;
73
- }
74
-
75
- interface TaskGraphNode {
76
- taskConfiguration: TaskConfiguration;
77
- node: TaskNode;
78
- }
79
-
80
- export enum TaskEndedTypes {
81
- TaskExited,
82
- BackgroundTaskEnded
83
- }
84
-
85
- export interface TaskEndedInfo {
86
- taskEndedType: TaskEndedTypes,
87
- value: number | boolean | undefined
88
- }
89
-
90
- export interface LastRunTaskInfo {
91
- resolvedTask?: TaskConfiguration;
92
- option?: RunTaskOption
93
- }
94
-
95
- @injectable()
96
- export class TaskService implements TaskConfigurationClient {
97
-
98
- /**
99
- * The last executed task.
100
- */
101
- protected lastTask: LastRunTaskInfo = {resolvedTask: undefined, option: undefined};
102
- protected cachedRecentTasks: TaskConfiguration[] = [];
103
- protected runningTasks = new Map<number, {
104
- exitCode: Deferred<number | undefined>,
105
- terminateSignal: Deferred<string | undefined>,
106
- isBackgroundTaskEnded: Deferred<boolean | undefined>
107
- }>();
108
-
109
- protected taskStartingLock: Mutex = new Mutex();
110
-
111
- @inject(FrontendApplication)
112
- protected readonly app: FrontendApplication;
113
-
114
- @inject(ApplicationShell)
115
- protected readonly shell: ApplicationShell;
116
-
117
- @inject(TaskServer)
118
- protected readonly taskServer: TaskServer;
119
-
120
- @inject(ILogger) @named('task')
121
- protected readonly logger: ILogger;
122
-
123
- @inject(WidgetManager)
124
- protected readonly widgetManager: WidgetManager;
125
-
126
- @inject(TaskWatcher)
127
- protected readonly taskWatcher: TaskWatcher;
128
-
129
- @inject(MessageService)
130
- protected readonly messageService: MessageService;
131
-
132
- @inject(WorkspaceService)
133
- protected readonly workspaceService: WorkspaceService;
134
-
135
- @inject(TaskConfigurations)
136
- protected readonly taskConfigurations: TaskConfigurations;
137
-
138
- @inject(ProvidedTaskConfigurations)
139
- protected readonly providedTaskConfigurations: ProvidedTaskConfigurations;
140
-
141
- @inject(VariableResolverService)
142
- protected readonly variableResolverService: VariableResolverService;
143
-
144
- @inject(TaskResolverRegistry)
145
- protected readonly taskResolverRegistry: TaskResolverRegistry;
146
-
147
- @inject(TerminalService)
148
- protected readonly terminalService: TerminalService;
149
-
150
- @inject(EditorManager)
151
- protected readonly editorManager: EditorManager;
152
-
153
- @inject(ProblemManager)
154
- protected readonly problemManager: ProblemManager;
155
-
156
- @inject(TaskDefinitionRegistry)
157
- protected readonly taskDefinitionRegistry: TaskDefinitionRegistry;
158
-
159
- @inject(ProblemMatcherRegistry)
160
- protected readonly problemMatcherRegistry: ProblemMatcherRegistry;
161
-
162
- @inject(QuickPickService)
163
- protected readonly quickPickService: QuickPickService;
164
-
165
- @inject(OpenerService)
166
- protected readonly openerService: OpenerService;
167
-
168
- @inject(ShellTerminalServerProxy)
169
- protected readonly shellTerminalServer: ShellTerminalServerProxy;
170
-
171
- @inject(TaskNameResolver)
172
- protected readonly taskNameResolver: TaskNameResolver;
173
-
174
- @inject(TaskSourceResolver)
175
- protected readonly taskSourceResolver: TaskSourceResolver;
176
-
177
- @inject(TaskSchemaUpdater)
178
- protected readonly taskSchemaUpdater: TaskSchemaUpdater;
179
-
180
- @inject(TaskConfigurationManager)
181
- protected readonly taskConfigurationManager: TaskConfigurationManager;
182
-
183
- @inject(CommandService)
184
- protected readonly commands: CommandService;
185
-
186
- @inject(LabelProvider)
187
- protected readonly labelProvider: LabelProvider;
188
-
189
- @inject(MonacoWorkspace)
190
- protected monacoWorkspace: MonacoWorkspace;
191
-
192
- @inject(TaskTerminalWidgetManager)
193
- protected readonly taskTerminalWidgetManager: TaskTerminalWidgetManager;
194
-
195
- @postConstruct()
196
- protected init(): void {
197
- this.getRunningTasks().then(tasks =>
198
- tasks.forEach(task => {
199
- if (!this.runningTasks.has(task.taskId)) {
200
- this.runningTasks.set(task.taskId, {
201
- exitCode: new Deferred<number | undefined>(), terminateSignal: new Deferred<string | undefined>(),
202
- isBackgroundTaskEnded: new Deferred<boolean | undefined>()
203
- });
204
- }
205
- }));
206
-
207
- // notify user that task has started
208
- this.taskWatcher.onTaskCreated((event: TaskInfo) => {
209
- if (!this.isEventForThisClient(event.ctx)) {
210
- return;
211
- }
212
- this.runningTasks.set(event.taskId, {
213
- exitCode: new Deferred<number | undefined>(),
214
- terminateSignal: new Deferred<string | undefined>(),
215
- isBackgroundTaskEnded: new Deferred<boolean | undefined>()
216
- });
217
- });
218
-
219
- this.taskWatcher.onOutputProcessed(async (event: TaskOutputProcessedEvent) => {
220
- if (!this.isEventForThisClient(event.ctx)) {
221
- return;
222
- }
223
- if (event.problems) {
224
- const runningTasksInfo: TaskInfo[] = await this.getRunningTasks();
225
- // check if the task is active
226
- const matchedRunningTaskInfo = runningTasksInfo.find(taskInfo => {
227
- const taskConfig = taskInfo.config;
228
- return this.taskDefinitionRegistry.compareTasks(taskConfig, event.config);
229
- });
230
- const isTaskActiveAndOutputSilent = matchedRunningTaskInfo &&
231
- matchedRunningTaskInfo.config.presentation && matchedRunningTaskInfo.config.presentation.reveal === RevealKind.Silent;
232
- event.problems.forEach(problem => {
233
- const existingMarkers = this.problemManager.findMarkers({ owner: problem.description.owner });
234
- const uris = new Set<string>();
235
- existingMarkers.forEach(marker => uris.add(marker.uri));
236
- if (ProblemMatchData.is(problem) && problem.resource) {
237
- // When task.presentation.reveal === RevealKind.Silent, put focus on the terminal only if it is an error
238
- if (isTaskActiveAndOutputSilent && problem.marker.severity === DiagnosticSeverity.Error) {
239
- const terminalId = matchedRunningTaskInfo!.terminalId;
240
- if (terminalId) {
241
- const terminal = this.terminalService.getByTerminalId(terminalId);
242
- if (terminal) {
243
- const focus = !!matchedRunningTaskInfo!.config.presentation!.focus;
244
- if (focus) { // assign focus to the terminal if presentation.focus is true
245
- this.terminalService.open(terminal, { mode: 'activate' });
246
- } else { // show the terminal but not assign focus
247
- this.terminalService.open(terminal, { mode: 'reveal' });
248
- }
249
- }
250
- }
251
- }
252
- const uri = new URI(problem.resource.path).withScheme(problem.resource.scheme);
253
- const document = this.monacoWorkspace.getTextDocument(uri.toString());
254
- if (problem.description.applyTo === ApplyToKind.openDocuments && !!document ||
255
- problem.description.applyTo === ApplyToKind.closedDocuments && !document ||
256
- problem.description.applyTo === ApplyToKind.allDocuments
257
- ) {
258
- if (uris.has(uri.toString())) {
259
- const newData = [
260
- ...existingMarkers
261
- .filter(marker => marker.uri === uri.toString())
262
- .map(markerData => markerData.data),
263
- problem.marker
264
- ];
265
- this.problemManager.setMarkers(uri, problem.description.owner, newData);
266
- } else {
267
- this.problemManager.setMarkers(uri, problem.description.owner, [problem.marker]);
268
- }
269
- }
270
- } else { // should have received an event for finding the "background task begins" pattern
271
- uris.forEach(uriString => this.problemManager.setMarkers(new URI(uriString), problem.description.owner, []));
272
- }
273
- });
274
- }
275
- });
276
-
277
- this.taskWatcher.onBackgroundTaskEnded((event: BackgroundTaskEndedEvent) => {
278
- if (!this.isEventForThisClient(event.ctx)) {
279
- return;
280
- }
281
-
282
- if (!this.runningTasks.has(event.taskId)) {
283
- this.runningTasks.set(event.taskId, {
284
- exitCode: new Deferred<number | undefined>(),
285
- terminateSignal: new Deferred<string | undefined>(),
286
- isBackgroundTaskEnded: new Deferred<boolean | undefined>()
287
- });
288
- }
289
- this.runningTasks.get(event.taskId)!.isBackgroundTaskEnded.resolve(true);
290
- });
291
-
292
- // notify user that task has finished
293
- this.taskWatcher.onTaskExit((event: TaskExitedEvent) => {
294
- if (!this.isEventForThisClient(event.ctx)) {
295
- return;
296
- }
297
- if (!this.runningTasks.has(event.taskId)) {
298
- this.runningTasks.set(event.taskId, {
299
- exitCode: new Deferred<number | undefined>(),
300
- terminateSignal: new Deferred<string | undefined>(),
301
- isBackgroundTaskEnded: new Deferred<boolean | undefined>()
302
- });
303
- }
304
- this.runningTasks.get(event.taskId)!.exitCode.resolve(event.code);
305
- this.runningTasks.get(event.taskId)!.terminateSignal.resolve(event.signal);
306
- setTimeout(() => this.runningTasks.delete(event.taskId), 60 * 1000);
307
-
308
- const taskConfig = event.config;
309
- const taskIdentifier = taskConfig ? this.getTaskIdentifier(taskConfig) : event.taskId.toString();
310
- if (event.code !== undefined) {
311
- if (event.code !== 0) {
312
- const eventTaskConfig = event.config;
313
- if (eventTaskConfig && eventTaskConfig.presentation && eventTaskConfig.presentation.reveal === RevealKind.Silent && event.terminalId) {
314
- const terminal = this.terminalService.getByTerminalId(event.terminalId);
315
- const focus = !!eventTaskConfig.presentation.focus;
316
- if (terminal) {
317
- if (focus) { // assign focus to the terminal if presentation.focus is true
318
- this.terminalService.open(terminal, { mode: 'activate' });
319
- } else { // show the terminal but not assign focus
320
- this.terminalService.open(terminal, { mode: 'reveal' });
321
- }
322
- }
323
- }
324
- this.messageService.error(`Task '${taskIdentifier}' has exited with code ${event.code}.`);
325
- }
326
- } else if (event.signal !== undefined) {
327
- this.messageService.info(`Task '${taskIdentifier}' was terminated by signal ${event.signal}.`);
328
- } else {
329
- console.error('Invalid TaskExitedEvent received, neither code nor signal is set.');
330
- }
331
- });
332
- }
333
-
334
- protected getTaskIdentifier(taskConfig: TaskConfiguration): string {
335
- const taskName = this.taskNameResolver.resolve(taskConfig);
336
- const sourceStrUri = this.taskSourceResolver.resolve(taskConfig);
337
- return `${taskName} (${this.labelProvider.getName(new URI(sourceStrUri))})`;
338
- }
339
-
340
- /**
341
- * Client should call this method to indicate that a new user-level action related to tasks has been started,
342
- * like invoking "Run Task..."
343
- * This method returns a token that can be used with various methods in this service.
344
- * As long as a client uses the same token, task providers will only asked once to contribute
345
- * tasks and the set of tasks will be cached. Each time the a new token is used, the cache of
346
- * contributed tasks is cleared.
347
- * @returns a token to be used for task-related actions
348
- */
349
- startUserAction(): number {
350
- return this.providedTaskConfigurations.startUserAction();
351
- }
352
-
353
- /**
354
- * Returns an array of the task configurations configured in tasks.json and provided by the extensions.
355
- * @param token The cache token for the user interaction in progress
356
- */
357
- async getTasks(token: number): Promise<TaskConfiguration[]> {
358
- const configuredTasks = await this.getConfiguredTasks(token);
359
- const providedTasks = await this.getProvidedTasks(token);
360
- const notCustomizedProvidedTasks = providedTasks.filter(provided =>
361
- !configuredTasks.some(configured => this.taskDefinitionRegistry.compareTasks(configured, provided))
362
- );
363
- return [...configuredTasks, ...notCustomizedProvidedTasks];
364
- }
365
-
366
- /**
367
- * Returns an array of the valid task configurations which are configured in tasks.json files
368
- * @param token The cache token for the user interaction in progress
369
- *
370
- */
371
- async getConfiguredTasks(token: number): Promise<TaskConfiguration[]> {
372
- const invalidTaskConfig = this.taskConfigurations.getInvalidTaskConfigurations()[0];
373
- if (invalidTaskConfig) {
374
- const widget = <ProblemWidget>await this.widgetManager.getOrCreateWidget(PROBLEMS_WIDGET_ID);
375
- const isProblemsWidgetVisible = widget && widget.isVisible;
376
- const currentEditorUri = this.editorManager.currentEditor && this.editorManager.currentEditor.editor.getResourceUri();
377
- let isInvalidTaskConfigFileOpen = false;
378
- if (currentEditorUri) {
379
- const folderUri = this.workspaceService.getWorkspaceRootUri(currentEditorUri);
380
- if (folderUri && folderUri.toString() === invalidTaskConfig._scope) {
381
- isInvalidTaskConfigFileOpen = true;
382
- }
383
- }
384
- const warningMessage = 'Invalid task configurations are found. Open tasks.json and find details in the Problems view.';
385
- if (!isProblemsWidgetVisible || !isInvalidTaskConfigFileOpen) {
386
- this.messageService.warn(warningMessage, 'Open').then(actionOpen => {
387
- if (actionOpen) {
388
- if (invalidTaskConfig && invalidTaskConfig._scope) {
389
- this.taskConfigurationManager.openConfiguration(invalidTaskConfig._scope);
390
- }
391
- if (!isProblemsWidgetVisible) {
392
- this.commands.executeCommand('problemsView:toggle');
393
- }
394
- }
395
- });
396
- } else {
397
- this.messageService.warn(warningMessage);
398
- }
399
- }
400
-
401
- const validTaskConfigs = await this.taskConfigurations.getTasks(token);
402
- return validTaskConfigs;
403
- }
404
-
405
- /**
406
- * Returns an array of the task configurations which are provided by the extensions.
407
- * @param token The cache token for the user interaction in progress
408
- */
409
- getProvidedTasks(token: number): Promise<TaskConfiguration[]> {
410
- return this.providedTaskConfigurations.getTasks(token);
411
- }
412
-
413
- addRecentTasks(tasks: TaskConfiguration | TaskConfiguration[]): void {
414
- if (Array.isArray(tasks)) {
415
- tasks.forEach(task => this.addRecentTasks(task));
416
- } else {
417
- const ind = this.cachedRecentTasks.findIndex(recent => this.taskDefinitionRegistry.compareTasks(recent, tasks));
418
- if (ind >= 0) {
419
- this.cachedRecentTasks.splice(ind, 1);
420
- }
421
- this.cachedRecentTasks.unshift(tasks);
422
- }
423
- }
424
-
425
- get recentTasks(): TaskConfiguration[] {
426
- return this.cachedRecentTasks;
427
- }
428
-
429
- set recentTasks(recent: TaskConfiguration[]) {
430
- this.cachedRecentTasks = recent;
431
- }
432
-
433
- /**
434
- * Clears the list of recently used tasks.
435
- */
436
- clearRecentTasks(): void {
437
- this.cachedRecentTasks = [];
438
- }
439
-
440
- /**
441
- * Open user ser
442
- */
443
- openUserTasks(): Promise<void> {
444
- return this.taskConfigurations.openUserTasks();
445
- }
446
-
447
- /**
448
- * Returns a task configuration provided by an extension by task source, scope and label.
449
- * If there are no task configuration, returns undefined.
450
- * @param token The cache token for the user interaction in progress
451
- * @param source The source for configured tasks
452
- * @param label The label of the task to find
453
- * @param scope The task scope to look in
454
- */
455
- async getProvidedTask(token: number, source: string, label: string, scope: TaskConfigurationScope): Promise<TaskConfiguration | undefined> {
456
- return this.providedTaskConfigurations.getTask(token, source, label, scope);
457
- }
458
-
459
- /** Returns an array of running tasks 'TaskInfo' objects */
460
- getRunningTasks(): Promise<TaskInfo[]> {
461
- return this.taskServer.getTasks(this.getContext());
462
- }
463
-
464
- async customExecutionComplete(id: number, exitCode: number | undefined): Promise<void> {
465
- return this.taskServer.customExecutionComplete(id, exitCode);
466
- }
467
-
468
- /** Returns an array of task types that are registered, including the default types */
469
- getRegisteredTaskTypes(): Promise<string[]> {
470
- return this.taskSchemaUpdater.getRegisteredTaskTypes();
471
- }
472
-
473
- /**
474
- * Get the last executed task.
475
- *
476
- * @returns the last executed task or `undefined`.
477
- */
478
- getLastTask(): LastRunTaskInfo {
479
- return this.lastTask;
480
- }
481
-
482
- /**
483
- * Runs a task, by task configuration label.
484
- * Note, it looks for a task configured in tasks.json only.
485
- * @param token The cache token for the user interaction in progress
486
- * @param scope The scope where to look for tasks
487
- * @param taskLabel the label to look for
488
- */
489
- async runConfiguredTask(token: number, scope: TaskConfigurationScope, taskLabel: string): Promise<void> {
490
- const task = this.taskConfigurations.getTask(scope, taskLabel);
491
- if (!task) {
492
- this.logger.error(`Can't get task launch configuration for label: ${taskLabel}`);
493
- return;
494
- }
495
-
496
- this.run(token, task._source, taskLabel, scope);
497
- }
498
-
499
- /**
500
- * Run the last executed task.
501
- * @param token The cache token for the user interaction in progress
502
- */
503
- async runLastTask(token: number): Promise<TaskInfo | undefined> {
504
- if (!this.lastTask?.resolvedTask) {
505
- return;
506
- }
507
- if (!this.lastTask.resolvedTask.runOptions?.reevaluateOnRerun) {
508
- return this.runResolvedTask(this.lastTask.resolvedTask, this.lastTask.option);
509
- }
510
- const { _source, label, _scope } = this.lastTask.resolvedTask;
511
- return this.run(token, _source, label, _scope);
512
- }
513
-
514
- /**
515
- * Runs a task, by the source and label of the task configuration.
516
- * It looks for configured and detected tasks.
517
- * @param token The cache token for the user interaction in progress
518
- * @param source The source for configured tasks
519
- * @param taskLabel The label to look for
520
- * @param scope The scope where to look for tasks
521
- */
522
- async run(token: number, source: string, taskLabel: string, scope: TaskConfigurationScope): Promise<TaskInfo | undefined> {
523
- let task: TaskConfiguration | undefined;
524
- task = this.taskConfigurations.getTask(scope, taskLabel);
525
- if (!task) { // if a configured task cannot be found, search from detected tasks
526
- task = await this.getProvidedTask(token, source, taskLabel, scope);
527
- if (!task) { // find from the customized detected tasks
528
- task = await this.taskConfigurations.getCustomizedTask(token, scope, taskLabel);
529
- }
530
- if (!task) {
531
- this.logger.error(`Can't get task launch configuration for label: ${taskLabel}`);
532
- return;
533
- }
534
- }
535
- const customizationObject = await this.getTaskCustomization(task);
536
-
537
- if (!customizationObject.problemMatcher) {
538
- // ask the user what s/he wants to use to parse the task output
539
- const items = this.getCustomizeProblemMatcherItems();
540
- const selected = await this.quickPickService.show(items, {
541
- placeholder: 'Select for which kind of errors and warnings to scan the task output'
542
- });
543
- if (selected && ('value' in selected)) {
544
- if (selected.value?.problemMatchers) {
545
- let matcherNames: string[] = [];
546
- if (selected.value.problemMatchers && selected.value.problemMatchers.length === 0) { // never parse output for this task
547
- matcherNames = [];
548
- } else if (selected.value.problemMatchers && selected.value.problemMatchers.length > 0) { // continue with user-selected parser
549
- matcherNames = selected.value.problemMatchers.map(matcher => matcher.name);
550
- }
551
- customizationObject.problemMatcher = matcherNames;
552
-
553
- // write the selected matcher (or the decision of "never parse") into the `tasks.json`
554
- this.updateTaskConfiguration(token, task, { problemMatcher: matcherNames });
555
- } else if (selected.value?.learnMore) { // user wants to learn more about parsing task output
556
- open(this.openerService, new URI('https://code.visualstudio.com/docs/editor/tasks#_processing-task-output-with-problem-matchers'));
557
- }
558
- // else, continue the task with no parser
559
- } else { // do not start the task in case that the user did not select any item from the list
560
- return;
561
- }
562
- }
563
-
564
- const resolvedMatchers = await this.resolveProblemMatchers(task, customizationObject);
565
- const runTaskOption: RunTaskOption = {
566
- customization: { ...customizationObject, ...{ problemMatcher: resolvedMatchers } }
567
- };
568
-
569
- if (task.dependsOn) {
570
- return this.runCompoundTask(token, task, runTaskOption);
571
- } else {
572
- return this.runTask(task, runTaskOption).catch(error => {
573
- console.error('Error at launching task', error);
574
- return undefined;
575
- });
576
- }
577
- }
578
-
579
- /**
580
- * Runs a compound task
581
- * @param token The cache token for the user interaction in progress
582
- * @param task The task to be executed
583
- * @param option options for executing the task
584
- */
585
- async runCompoundTask(token: number, task: TaskConfiguration, option?: RunTaskOption): Promise<TaskInfo | undefined> {
586
- const tasks = await this.getWorkspaceTasks(token, task._scope);
587
- try {
588
- const rootNode = new TaskNode(task, [], []);
589
- this.detectDirectedAcyclicGraph(task, rootNode, tasks);
590
- } catch (error) {
591
- console.error(`Error at launching task '${task.label}'`, error);
592
- this.messageService.error(error.message);
593
- return undefined;
594
- }
595
- return this.runTasksGraph(task, tasks, option).catch(error => {
596
- console.error(`Error at launching task '${task.label}'`, error);
597
- return undefined;
598
- });
599
- }
600
-
601
- /**
602
- * A recursive function that runs a task and all its sub tasks that it depends on.
603
- * A task can be executed only when all of its dependencies have been executed, or when it doesn’t have any dependencies at all.
604
- */
605
- async runTasksGraph(task: TaskConfiguration, tasks: TaskConfiguration[], option?: RunTaskOption): Promise<TaskInfo | undefined> {
606
- if (task && task.dependsOn) {
607
- // In case it is an array of task dependencies
608
- if (Array.isArray(task.dependsOn) && task.dependsOn.length > 0) {
609
- const dependentTasks: { 'task': TaskConfiguration; 'taskCustomization': TaskCustomization; 'resolvedMatchers': ProblemMatcher[] | undefined }[] = [];
610
- for (let i = 0; i < task.dependsOn.length; i++) {
611
- // It may be a string (a task label) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
612
- const taskIdentifier = task.dependsOn[i];
613
- const dependentTask = this.getDependentTask(taskIdentifier, tasks);
614
- const taskCustomization = await this.getTaskCustomization(dependentTask);
615
- const resolvedMatchers = await this.resolveProblemMatchers(dependentTask, taskCustomization);
616
- dependentTasks.push({ 'task': dependentTask, 'taskCustomization': taskCustomization, 'resolvedMatchers': resolvedMatchers });
617
- // In case the 'dependsOrder' is 'sequence'
618
- if (task.dependsOrder && task.dependsOrder === DependsOrder.Sequence) {
619
- await this.runTasksGraph(dependentTask, tasks, {
620
- customization: { ...taskCustomization, ...{ problemMatcher: resolvedMatchers } }
621
- });
622
- }
623
- }
624
- // In case the 'dependsOrder' is 'parallel'
625
- if (((!task.dependsOrder) || (task.dependsOrder && task.dependsOrder === DependsOrder.Parallel))) {
626
- const promises = dependentTasks.map(item =>
627
- this.runTasksGraph(item.task, tasks, {
628
- customization: { ...item.taskCustomization, ...{ problemMatcher: item.resolvedMatchers } }
629
- })
630
- );
631
- await Promise.all(promises);
632
- }
633
- } else if (!Array.isArray(task.dependsOn)) {
634
- // In case it is a string (a task label) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
635
- const taskIdentifier = task.dependsOn;
636
- const dependentTask = this.getDependentTask(taskIdentifier, tasks);
637
- const taskCustomization = await this.getTaskCustomization(dependentTask);
638
- const resolvedMatchers = await this.resolveProblemMatchers(dependentTask, taskCustomization);
639
- await this.runTasksGraph(dependentTask, tasks, {
640
- customization: { ...taskCustomization, ...{ problemMatcher: resolvedMatchers } }
641
- });
642
- }
643
- }
644
-
645
- const taskInfo = await this.runTask(task, option);
646
- if (taskInfo) {
647
- const getExitCodePromise: Promise<TaskEndedInfo> = this.getExitCode(taskInfo.taskId).then(result => ({ taskEndedType: TaskEndedTypes.TaskExited, value: result }));
648
- const isBackgroundTaskEndedPromise: Promise<TaskEndedInfo> = this.isBackgroundTaskEnded(taskInfo.taskId).then(result =>
649
- ({ taskEndedType: TaskEndedTypes.BackgroundTaskEnded, value: result }));
650
-
651
- // After start running the task, we wait for the task process to exit and if it is a background task, we also wait for a feedback
652
- // that a background task is active, as soon as one of the promises fulfills, we can continue and analyze the results.
653
- const taskEndedInfo: TaskEndedInfo = await Promise.race([getExitCodePromise, isBackgroundTaskEndedPromise]);
654
-
655
- if ((taskEndedInfo.taskEndedType === TaskEndedTypes.TaskExited && taskEndedInfo.value !== 0) ||
656
- (taskEndedInfo.taskEndedType === TaskEndedTypes.BackgroundTaskEnded && !taskEndedInfo.value)) {
657
- throw new Error('The task: ' + task.label + ' terminated with exit code ' + taskEndedInfo.value + '.');
658
- }
659
- }
660
- return taskInfo;
661
- }
662
-
663
- /**
664
- * Creates a graph of dependencies tasks from the root task and verify there is no DAG (Directed Acyclic Graph).
665
- * In case of detection of a circular dependency, an error is thrown with a message which describes the detected circular reference.
666
- */
667
- detectDirectedAcyclicGraph(task: TaskConfiguration, taskNode: TaskNode, tasks: TaskConfiguration[]): void {
668
- if (task && task.dependsOn) {
669
- // In case the 'dependsOn' is an array
670
- if (Array.isArray(task.dependsOn) && task.dependsOn.length > 0) {
671
- for (let i = 0; i < task.dependsOn.length; i++) {
672
- const childNode = this.createChildTaskNode(task, taskNode, task.dependsOn[i], tasks);
673
- this.detectDirectedAcyclicGraph(childNode.taskConfiguration, childNode.node, tasks);
674
- }
675
- } else if (!Array.isArray(task.dependsOn)) {
676
- const childNode = this.createChildTaskNode(task, taskNode, task.dependsOn, tasks);
677
- this.detectDirectedAcyclicGraph(childNode.taskConfiguration, childNode.node, tasks);
678
- }
679
- }
680
- }
681
-
682
- // 'childTaskIdentifier' may be a string (a task label) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
683
- createChildTaskNode(task: TaskConfiguration, taskNode: TaskNode, childTaskIdentifier: string | TaskIdentifier, tasks: TaskConfiguration[]): TaskGraphNode {
684
- const childTaskConfiguration = this.getDependentTask(childTaskIdentifier, tasks);
685
-
686
- // If current task and child task are identical or if
687
- // one of the child tasks is identical to one of the current task ancestors, then raise an error
688
- if (this.taskDefinitionRegistry.compareTasks(task, childTaskConfiguration) ||
689
- taskNode.parentsID.filter(t => this.taskDefinitionRegistry.compareTasks(childTaskConfiguration, t)).length > 0) {
690
- const fromNode = task.label;
691
- const toNode = childTaskConfiguration.label;
692
- throw new Error('Circular reference detected: ' + fromNode + ' --> ' + toNode);
693
- }
694
- const childNode = new TaskNode(childTaskConfiguration, [], Object.assign([], taskNode.parentsID));
695
- childNode.addParentDependency(taskNode.taskId);
696
- taskNode.addChildDependency(childNode);
697
- return { 'taskConfiguration': childTaskConfiguration, 'node': childNode };
698
- }
699
-
700
- /**
701
- * Gets task configuration by task label or by a JSON object which represents a task identifier
702
- *
703
- * @param taskIdentifier The task label (string) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
704
- * @param tasks an array of the task configurations
705
- * @returns the correct TaskConfiguration object which matches the taskIdentifier
706
- */
707
- getDependentTask(taskIdentifier: string | TaskIdentifier, tasks: TaskConfiguration[]): TaskConfiguration {
708
- const notEnoughDataError = 'The information provided in the "dependsOn" is not enough for matching the correct task !';
709
- let currentTaskChildConfiguration: TaskConfiguration;
710
- if (typeof (taskIdentifier) !== 'string') {
711
- // TaskIdentifier object does not support tasks of type 'shell' (The same behavior as in VS Code).
712
- // So if we want the 'dependsOn' property to include tasks of type 'shell',
713
- // then we must mention their labels (in the 'dependsOn' property) and not to create a task identifier object for them.
714
- currentTaskChildConfiguration = this.getTaskByTaskIdentifier(taskIdentifier, tasks);
715
- if (!currentTaskChildConfiguration.type) {
716
- this.messageService.error(notEnoughDataError);
717
- throw new Error(notEnoughDataError);
718
- }
719
- return currentTaskChildConfiguration;
720
- } else {
721
- currentTaskChildConfiguration = tasks.filter(t => taskIdentifier === this.taskNameResolver.resolve(t))[0];
722
- return currentTaskChildConfiguration;
723
- }
724
- }
725
-
726
- /**
727
- * Gets the matched task from an array of task configurations by TaskIdentifier.
728
- * In case that more than one task configuration matches, we returns the first one.
729
- *
730
- * @param taskIdentifier The task label (string) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
731
- * @param tasks An array of task configurations.
732
- * @returns The correct TaskConfiguration object which matches the taskIdentifier.
733
- */
734
- getTaskByTaskIdentifier(taskIdentifier: TaskIdentifier, tasks: TaskConfiguration[]): TaskConfiguration {
735
- const requiredProperties = Object.keys(taskIdentifier);
736
- const taskWithAllProperties = tasks.find(task => requiredProperties.every(property => task.hasOwnProperty(property) && task[property] === taskIdentifier[property]));
737
- return taskWithAllProperties ?? { label: '', _scope: '', type: '' }; // Fall back to empty TaskConfiguration
738
- }
739
-
740
- async runTask(task: TaskConfiguration, option?: RunTaskOption): Promise<TaskInfo | undefined> {
741
- console.debug('entering runTask');
742
- const releaseLock = await this.taskStartingLock.acquire();
743
- console.debug('got lock');
744
-
745
- try {
746
- // resolve problemMatchers
747
- if (!option && task.problemMatcher) {
748
- const customizationObject: TaskCustomization = { type: task.taskType, problemMatcher: task.problemMatcher, runOptions: task.runOptions };
749
- const resolvedMatchers = await this.resolveProblemMatchers(task, customizationObject);
750
- option = {
751
- customization: { ...customizationObject, ...{ problemMatcher: resolvedMatchers } }
752
- };
753
- }
754
-
755
- const runningTasksInfo: TaskInfo[] = await this.getRunningTasks();
756
- // check if the task is active
757
- const matchedRunningTaskInfo = runningTasksInfo.find(taskInfo => {
758
- const taskConfig = taskInfo.config;
759
- return this.taskDefinitionRegistry.compareTasks(taskConfig, task);
760
- });
761
- console.debug(`running task ${JSON.stringify(task)}, already running = ${!!matchedRunningTaskInfo}`);
762
-
763
- if (matchedRunningTaskInfo) { // the task is active
764
- releaseLock();
765
- console.debug('released lock');
766
- const taskName = this.taskNameResolver.resolve(task);
767
- const terminalId = matchedRunningTaskInfo.terminalId;
768
- if (terminalId) {
769
- const terminal = this.terminalService.getByTerminalId(terminalId);
770
- if (terminal) {
771
- if (TaskOutputPresentation.shouldSetFocusToTerminal(task)) { // assign focus to the terminal if presentation.focus is true
772
- this.terminalService.open(terminal, { mode: 'activate' });
773
- } else if (TaskOutputPresentation.shouldAlwaysRevealTerminal(task)) { // show the terminal but not assign focus
774
- this.terminalService.open(terminal, { mode: 'reveal' });
775
- }
776
- }
777
- }
778
- const selectedAction = await this.messageService.info(`The task '${taskName}' is already active`, 'Terminate Task', 'Restart Task');
779
- if (selectedAction === 'Terminate Task') {
780
- await this.terminateTask(matchedRunningTaskInfo);
781
- } else if (selectedAction === 'Restart Task') {
782
- return this.restartTask(matchedRunningTaskInfo, option);
783
- }
784
- } else { // run task as the task is not active
785
- console.debug('task about to start');
786
- const taskInfo = await this.doRunTask(task, option);
787
- releaseLock();
788
- console.debug('release lock 2');
789
- return taskInfo;
790
- }
791
- } catch (e) {
792
- releaseLock();
793
- throw e;
794
- }
795
- }
796
-
797
- /**
798
- * Terminates a task that is actively running.
799
- * @param activeTaskInfo the TaskInfo of the task that is actively running
800
- */
801
- async terminateTask(activeTaskInfo: TaskInfo): Promise<void> {
802
- const taskId = activeTaskInfo.taskId;
803
- return this.kill(taskId);
804
- }
805
-
806
- /**
807
- * Terminates a task that is actively running, and restarts it.
808
- * @param activeTaskInfo the TaskInfo of the task that is actively running
809
- */
810
- async restartTask(activeTaskInfo: TaskInfo, option?: RunTaskOption): Promise<TaskInfo | undefined> {
811
- await this.terminateTask(activeTaskInfo);
812
- return this.doRunTask(activeTaskInfo.config, option);
813
- }
814
-
815
- protected async doRunTask(task: TaskConfiguration, option?: RunTaskOption): Promise<TaskInfo | undefined> {
816
- let overridePropertiesFunction: (task: TaskConfiguration) => void = () => { };
817
- if (option && option.customization) {
818
- const taskDefinition = this.taskDefinitionRegistry.getDefinition(task);
819
- if (taskDefinition) { // use the customization object to override the task config
820
- overridePropertiesFunction = tsk => {
821
- Object.keys(option.customization!).forEach(customizedProperty => {
822
- // properties used to define the task cannot be customized
823
- if (customizedProperty !== 'type' && !taskDefinition.properties.all.some(pDefinition => pDefinition === customizedProperty)) {
824
- tsk[customizedProperty] = option.customization![customizedProperty];
825
- }
826
- });
827
- };
828
- }
829
- }
830
- overridePropertiesFunction(task);
831
- this.addRecentTasks(task);
832
- try {
833
- const resolver = await this.taskResolverRegistry.getTaskResolver(task.type);
834
- const resolvedTask = resolver ? await resolver.resolveTask(task) : task;
835
- const executionResolver = this.taskResolverRegistry.getExecutionResolver(resolvedTask.taskType || resolvedTask.type);
836
- overridePropertiesFunction(resolvedTask);
837
- const taskToRun = executionResolver ? await executionResolver.resolveTask(resolvedTask) : resolvedTask;
838
-
839
- await this.removeProblemMarkers(option);
840
- return this.runResolvedTask(taskToRun, option);
841
- } catch (error) {
842
- const errMessage = `Error resolving task '${task.label}': ${error}`;
843
- this.logger.error(errMessage);
844
- }
845
- return undefined;
846
- }
847
-
848
- /**
849
- * Runs the first task with the given label.
850
- *
851
- * @param token The cache token for the user interaction in progress
852
- * @param taskLabel The label of the task to be executed
853
- */
854
- async runTaskByLabel(token: number, taskLabel: string): Promise<TaskInfo | undefined> {
855
- const tasks: TaskConfiguration[] = await this.getTasks(token);
856
- for (const task of tasks) {
857
- if (task.label === taskLabel) {
858
- return this.runTask(task);
859
- }
860
- }
861
- return;
862
- }
863
-
864
- /**
865
- * Runs a task identified by the given identifier, but only if found in the given workspace folder
866
- *
867
- * @param token The cache token for the user interaction in progress
868
- * @param workspaceFolderUri The folder to restrict the search to
869
- * @param taskIdentifier The identifier to look for
870
- */
871
- async runWorkspaceTask(token: number, workspaceFolderUri: string | undefined, taskIdentifier: string | TaskIdentifier): Promise<TaskInfo | undefined> {
872
- const tasks = await this.getWorkspaceTasks(token, workspaceFolderUri);
873
- const task = this.getDependentTask(taskIdentifier, tasks);
874
- if (!task) {
875
- return undefined;
876
- }
877
-
878
- const taskCustomization = await this.getTaskCustomization(task);
879
- const resolvedMatchers = await this.resolveProblemMatchers(task, taskCustomization);
880
- try {
881
- const rootNode = new TaskNode(task, [], []);
882
- this.detectDirectedAcyclicGraph(task, rootNode, tasks);
883
- } catch (error) {
884
- this.logger.error(error.message);
885
- this.messageService.error(error.message);
886
- return undefined;
887
- }
888
- return this.runTasksGraph(task, tasks, {
889
- customization: { ...taskCustomization, ...{ problemMatcher: resolvedMatchers } }
890
- }).catch(error => {
891
- console.log(error.message);
892
- return undefined;
893
- });
894
- }
895
-
896
- /**
897
- * Updates the task configuration in the `tasks.json`.
898
- * The task config, together with updates, will be written into the `tasks.json` if it is not found in the file.
899
- *
900
- * @param token The cache token for the user interaction in progress
901
- * @param task task that the updates will be applied to
902
- * @param update the updates to be applied
903
- */
904
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
905
- async updateTaskConfiguration(token: number, task: TaskConfiguration, update: { [name: string]: any }): Promise<void> {
906
- if (update.problemMatcher) {
907
- if (Array.isArray(update.problemMatcher)) {
908
- update.problemMatcher.forEach((name, index) => {
909
- if (!name.startsWith('$')) {
910
- update.problemMatcher[index] = `$${update.problemMatcher[index]}`;
911
- }
912
- });
913
- } else if (!update.problemMatcher.startsWith('$')) {
914
- update.problemMatcher = `$${update.problemMatcher}`;
915
- }
916
- }
917
- this.taskConfigurations.updateTaskConfig(token, task, update);
918
- }
919
-
920
- protected async getWorkspaceTasks(token: number, restrictToFolder: TaskConfigurationScope | undefined): Promise<TaskConfiguration[]> {
921
- const tasks = await this.getTasks(token);
922
- // if we pass undefined, return everything, otherwise only tasks with the same uri or workspace/global scope tasks
923
- return tasks.filter(t => typeof t._scope !== 'string' || t._scope === restrictToFolder);
924
- }
925
-
926
- protected async resolveProblemMatchers(task: TaskConfiguration, customizationObject: TaskCustomization): Promise<ProblemMatcher[] | undefined> {
927
- const notResolvedMatchers = customizationObject.problemMatcher ?
928
- (Array.isArray(customizationObject.problemMatcher) ? customizationObject.problemMatcher : [customizationObject.problemMatcher]) : undefined;
929
- let resolvedMatchers: ProblemMatcher[] | undefined = [];
930
- if (notResolvedMatchers) {
931
- // resolve matchers before passing them to the server
932
- for (const matcher of notResolvedMatchers) {
933
- let resolvedMatcher: ProblemMatcher | undefined;
934
- await this.problemMatcherRegistry.onReady();
935
- if (typeof matcher === 'string') {
936
- resolvedMatcher = this.problemMatcherRegistry.get(matcher);
937
- } else {
938
- resolvedMatcher = await this.problemMatcherRegistry.getProblemMatcherFromContribution(matcher);
939
- }
940
- if (resolvedMatcher) {
941
- const scope = task._scope || task._source;
942
- if (resolvedMatcher.filePrefix && scope) {
943
- const options = {
944
- context: new URI(scope).withScheme('file'),
945
- configurationSection: 'tasks'
946
- };
947
- const resolvedPrefix = await this.variableResolverService.resolve(resolvedMatcher.filePrefix, options);
948
- Object.assign(resolvedMatcher, { filePrefix: resolvedPrefix });
949
- }
950
- resolvedMatchers.push(resolvedMatcher);
951
- }
952
- }
953
- } else {
954
- resolvedMatchers = undefined;
955
- }
956
- return resolvedMatchers;
957
- }
958
-
959
- protected async getTaskCustomization(task: TaskConfiguration): Promise<TaskCustomization> {
960
- const customizationObject: TaskCustomization = { type: '', _scope: task._scope, runOptions: task.runOptions };
961
- const customizationFound = this.taskConfigurations.getCustomizationForTask(task);
962
- if (customizationFound) {
963
- Object.assign(customizationObject, customizationFound);
964
- } else {
965
- Object.assign(customizationObject, {
966
- type: task.type,
967
- problemMatcher: task.problemMatcher
968
- });
969
- }
970
- return customizationObject;
971
- }
972
-
973
- protected async removeProblemMarkers(option?: RunTaskOption): Promise<void> {
974
- if (option && option.customization) {
975
- const matchersFromOption = option.customization.problemMatcher || [];
976
- for (const matcher of matchersFromOption) {
977
- if (matcher && matcher.owner) {
978
- const existingMarkers = this.problemManager.findMarkers({ owner: matcher.owner });
979
- const uris = new Set<string>();
980
- existingMarkers.forEach(marker => uris.add(marker.uri));
981
- uris.forEach(uriString => this.problemManager.setMarkers(new URI(uriString), matcher.owner, []));
982
- }
983
- }
984
- }
985
- }
986
-
987
- /**
988
- * Runs the resolved task and opens terminal widget if the task is based on a terminal process
989
- * @param resolvedTask the resolved task
990
- * @param option options to run the resolved task
991
- */
992
- protected async runResolvedTask(resolvedTask: TaskConfiguration, option?: RunTaskOption): Promise<TaskInfo | undefined> {
993
- const taskLabel = resolvedTask.label;
994
- let taskInfo: TaskInfo | undefined;
995
- try {
996
- taskInfo = await this.taskServer.run(resolvedTask, this.getContext(), option);
997
- this.lastTask = {resolvedTask, option };
998
- this.logger.debug(`Task created. Task id: ${taskInfo.taskId}`);
999
-
1000
- /**
1001
- * open terminal widget if the task is based on a terminal process (type: 'shell' or 'process')
1002
- *
1003
- * @todo Use a different mechanism to determine if the task should be attached?
1004
- * Reason: Maybe a new task type wants to also be displayed in a terminal.
1005
- */
1006
- if (typeof taskInfo.terminalId === 'number') {
1007
- await this.attach(taskInfo.terminalId, taskInfo);
1008
- }
1009
- return taskInfo;
1010
- } catch (error) {
1011
- const errorStr = `Error launching task '${taskLabel}': ${error.message}`;
1012
- this.logger.error(errorStr);
1013
- this.messageService.error(errorStr);
1014
- if (taskInfo && typeof taskInfo.terminalId === 'number') {
1015
- this.shellTerminalServer.onAttachAttempted(taskInfo.terminalId);
1016
- }
1017
- }
1018
- }
1019
-
1020
- protected getCustomizeProblemMatcherItems(): Array<QuickPickValue<QuickPickProblemMatcherItem> | QuickPickItemOrSeparator> {
1021
- const items: Array<QuickPickValue<QuickPickProblemMatcherItem> | QuickPickItemOrSeparator> = [];
1022
- items.push({
1023
- label: 'Continue without scanning the task output',
1024
- value: { problemMatchers: undefined }
1025
- });
1026
- items.push({
1027
- label: 'Never scan the task output',
1028
- value: { problemMatchers: [] }
1029
- });
1030
- items.push({
1031
- label: 'Learn more about scanning the task output',
1032
- value: { problemMatchers: undefined, learnMore: true }
1033
- });
1034
- items.push({ type: 'separator', label: 'registered parsers' });
1035
-
1036
- const registeredProblemMatchers = this.problemMatcherRegistry.getAll();
1037
- items.push(...registeredProblemMatchers.map(matcher =>
1038
- ({
1039
- label: matcher.label,
1040
- value: { problemMatchers: [matcher] },
1041
- description: matcher.name.startsWith('$') ? matcher.name : `$${matcher.name}`
1042
- })
1043
- ));
1044
- return items;
1045
- }
1046
-
1047
- /**
1048
- * Run selected text in the last active terminal.
1049
- */
1050
- async runSelectedText(): Promise<void> {
1051
- if (!this.editorManager.currentEditor) { return; }
1052
- const startLine = this.editorManager.currentEditor.editor.selection.start.line;
1053
- const startCharacter = this.editorManager.currentEditor.editor.selection.start.character;
1054
- const endLine = this.editorManager.currentEditor.editor.selection.end.line;
1055
- const endCharacter = this.editorManager.currentEditor.editor.selection.end.character;
1056
- let selectedRange: Range = Range.create(startLine, startCharacter, endLine, endCharacter);
1057
- // if no text is selected, default to selecting entire line
1058
- if (startLine === endLine && startCharacter === endCharacter) {
1059
- selectedRange = Range.create(startLine, 0, endLine + 1, 0);
1060
- }
1061
- const selectedText: string = this.editorManager.currentEditor.editor.document.getText(selectedRange).trimRight() + '\n';
1062
- let terminal = this.terminalService.lastUsedTerminal;
1063
- if (!terminal || terminal.kind !== 'user' || (await terminal.hasChildProcesses())) {
1064
- terminal = <TerminalWidget>await this.terminalService.newTerminal(<TerminalWidgetFactoryOptions>{ created: new Date().toString() });
1065
- await terminal.start();
1066
- this.terminalService.open(terminal);
1067
- }
1068
- terminal.sendText(selectedText);
1069
- }
1070
-
1071
- async attach(terminalId: number, taskInfo: TaskInfo): Promise<number | void> {
1072
- let widgetOpenMode: WidgetOpenMode = 'open';
1073
- if (taskInfo) {
1074
- const terminalWidget = this.terminalService.getByTerminalId(terminalId);
1075
- if (terminalWidget) {
1076
- this.messageService.error('Task is already running in terminal');
1077
- return this.terminalService.open(terminalWidget, { mode: 'activate' });
1078
- }
1079
- if (TaskOutputPresentation.shouldAlwaysRevealTerminal(taskInfo.config)) {
1080
- if (TaskOutputPresentation.shouldSetFocusToTerminal(taskInfo.config)) { // assign focus to the terminal if presentation.focus is true
1081
- widgetOpenMode = 'activate';
1082
- } else { // show the terminal but not assign focus
1083
- widgetOpenMode = 'reveal';
1084
- }
1085
- }
1086
- }
1087
- const { taskId } = taskInfo;
1088
- // Create / find a terminal widget to display an execution output of a task that was launched as a command inside a shell.
1089
- const widget = await this.taskTerminalWidgetManager.open({
1090
- created: new Date().toString(),
1091
- id: this.getTerminalWidgetId(terminalId),
1092
- title: taskInfo
1093
- ? `Task: ${taskInfo.config.label}`
1094
- : `Task: #${taskId}`,
1095
- destroyTermOnClose: true
1096
- }, {
1097
- widgetOptions: { area: 'bottom' },
1098
- mode: widgetOpenMode,
1099
- taskInfo
1100
- });
1101
- return widget.start(terminalId);
1102
- }
1103
-
1104
- protected getTerminalWidgetId(terminalId: number): string | undefined {
1105
- const terminalWidget = this.terminalService.getByTerminalId(terminalId);
1106
- if (terminalWidget) {
1107
- return terminalWidget.id;
1108
- }
1109
- }
1110
-
1111
- /**
1112
- * Opens an editor to configure the given task.
1113
- *
1114
- * @param token The cache token for the user interaction in progress
1115
- * @param task The task to configure
1116
- */
1117
- async configure(token: number, task: TaskConfiguration): Promise<void> {
1118
- Object.assign(task, { label: this.taskNameResolver.resolve(task) });
1119
- await this.taskConfigurations.configure(token, task);
1120
- }
1121
-
1122
- protected isEventForThisClient(context: string | undefined): boolean {
1123
- if (context === this.getContext()) {
1124
- return true;
1125
- }
1126
- return false;
1127
- }
1128
-
1129
- taskConfigurationChanged(event: string[]): void {
1130
- // do nothing for now
1131
- }
1132
-
1133
- protected getContext(): string | undefined {
1134
- return this.workspaceService.workspace?.resource.toString();
1135
- }
1136
-
1137
- /** Kill task for a given id if task is found */
1138
- async kill(id: number): Promise<void> {
1139
- try {
1140
- await this.taskServer.kill(id);
1141
- } catch (error) {
1142
- this.logger.error(`Error killing task '${id}': ${error}`);
1143
- this.messageService.error(`Error killing task '${id}': ${error}`);
1144
- return;
1145
- }
1146
- this.logger.debug(`Task killed. Task id: ${id}`);
1147
- }
1148
-
1149
- async isBackgroundTaskEnded(id: number): Promise<boolean | undefined> {
1150
- const completedTask = this.runningTasks.get(id);
1151
- return completedTask && completedTask.isBackgroundTaskEnded!.promise;
1152
- }
1153
-
1154
- async getExitCode(id: number): Promise<number | undefined> {
1155
- const completedTask = this.runningTasks.get(id);
1156
- return completedTask && completedTask.exitCode.promise;
1157
- }
1158
-
1159
- async getTerminateSignal(id: number): Promise<string | undefined> {
1160
- const completedTask = this.runningTasks.get(id);
1161
- return completedTask && completedTask.terminateSignal.promise;
1162
- }
1163
- }
1
+ // *****************************************************************************
2
+ // Copyright (C) 2017 Ericsson and others.
3
+ //
4
+ // This program and the accompanying materials are made available under the
5
+ // terms of the Eclipse Public License v. 2.0 which is available at
6
+ // http://www.eclipse.org/legal/epl-2.0.
7
+ //
8
+ // This Source Code may also be made available under the following Secondary
9
+ // Licenses when the conditions for such availability set forth in the Eclipse
10
+ // Public License v. 2.0 are satisfied: GNU General Public License, version 2
11
+ // with the GNU Classpath Exception which is available at
12
+ // https://www.gnu.org/software/classpath/license.html.
13
+ //
14
+ // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
15
+ // *****************************************************************************
16
+
17
+ import { ApplicationShell, FrontendApplication, QuickPickValue, WidgetManager, WidgetOpenMode } from '@theia/core/lib/browser';
18
+ import { open, OpenerService } from '@theia/core/lib/browser/opener-service';
19
+ import { CommandService, ILogger } from '@theia/core/lib/common';
20
+ import { MessageService } from '@theia/core/lib/common/message-service';
21
+ import { Deferred } from '@theia/core/lib/common/promise-util';
22
+ import { QuickPickItemOrSeparator, QuickPickService } from '@theia/core/lib/common/quick-pick-service';
23
+ import { LabelProvider } from '@theia/core/lib/browser/label-provider';
24
+ import URI from '@theia/core/lib/common/uri';
25
+ import { EditorManager } from '@theia/editor/lib/browser';
26
+ import { ProblemManager } from '@theia/markers/lib/browser/problem/problem-manager';
27
+ import { TerminalService } from '@theia/terminal/lib/browser/base/terminal-service';
28
+ import { TerminalWidget } from '@theia/terminal/lib/browser/base/terminal-widget';
29
+ import { TerminalWidgetFactoryOptions } from '@theia/terminal/lib/browser/terminal-widget-impl';
30
+ import { VariableResolverService } from '@theia/variable-resolver/lib/browser';
31
+ import { WorkspaceService } from '@theia/workspace/lib/browser/workspace-service';
32
+ import { inject, injectable, named, postConstruct } from '@theia/core/shared/inversify';
33
+ import { DiagnosticSeverity, Range } from '@theia/core/shared/vscode-languageserver-protocol';
34
+ import {
35
+ ApplyToKind,
36
+ BackgroundTaskEndedEvent,
37
+ DependsOrder,
38
+ NamedProblemMatcher,
39
+ ProblemMatchData,
40
+ ProblemMatcher,
41
+ RevealKind,
42
+ RunTaskOption,
43
+ TaskConfiguration,
44
+ TaskConfigurationScope,
45
+ TaskCustomization,
46
+ TaskExitedEvent,
47
+ TaskIdentifier,
48
+ TaskInfo,
49
+ TaskOutputPresentation,
50
+ TaskOutputProcessedEvent,
51
+ TaskServer
52
+ } from '../common';
53
+ import { TaskWatcher } from '../common/task-watcher';
54
+ import { ProvidedTaskConfigurations } from './provided-task-configurations';
55
+ import { TaskConfigurationClient, TaskConfigurations } from './task-configurations';
56
+ import { TaskResolverRegistry } from './task-contribution';
57
+ import { TaskDefinitionRegistry } from './task-definition-registry';
58
+ import { TaskNameResolver } from './task-name-resolver';
59
+ import { TaskSourceResolver } from './task-source-resolver';
60
+ import { ProblemMatcherRegistry } from './task-problem-matcher-registry';
61
+ import { TaskSchemaUpdater } from './task-schema-updater';
62
+ import { TaskConfigurationManager } from './task-configuration-manager';
63
+ import { PROBLEMS_WIDGET_ID, ProblemWidget } from '@theia/markers/lib/browser/problem/problem-widget';
64
+ import { TaskNode } from './task-node';
65
+ import { MonacoWorkspace } from '@theia/monaco/lib/browser/monaco-workspace';
66
+ import { TaskTerminalWidgetManager } from './task-terminal-widget-manager';
67
+ import { ShellTerminalServerProxy } from '@theia/terminal/lib/common/shell-terminal-protocol';
68
+ import { Mutex } from 'async-mutex';
69
+
70
+ export interface QuickPickProblemMatcherItem {
71
+ problemMatchers: NamedProblemMatcher[] | undefined;
72
+ learnMore?: boolean;
73
+ }
74
+
75
+ interface TaskGraphNode {
76
+ taskConfiguration: TaskConfiguration;
77
+ node: TaskNode;
78
+ }
79
+
80
+ export enum TaskEndedTypes {
81
+ TaskExited,
82
+ BackgroundTaskEnded
83
+ }
84
+
85
+ export interface TaskEndedInfo {
86
+ taskEndedType: TaskEndedTypes,
87
+ value: number | boolean | undefined
88
+ }
89
+
90
+ export interface LastRunTaskInfo {
91
+ resolvedTask?: TaskConfiguration;
92
+ option?: RunTaskOption
93
+ }
94
+
95
+ @injectable()
96
+ export class TaskService implements TaskConfigurationClient {
97
+
98
+ /**
99
+ * The last executed task.
100
+ */
101
+ protected lastTask: LastRunTaskInfo = {resolvedTask: undefined, option: undefined};
102
+ protected cachedRecentTasks: TaskConfiguration[] = [];
103
+ protected runningTasks = new Map<number, {
104
+ exitCode: Deferred<number | undefined>,
105
+ terminateSignal: Deferred<string | undefined>,
106
+ isBackgroundTaskEnded: Deferred<boolean | undefined>
107
+ }>();
108
+
109
+ protected taskStartingLock: Mutex = new Mutex();
110
+
111
+ @inject(FrontendApplication)
112
+ protected readonly app: FrontendApplication;
113
+
114
+ @inject(ApplicationShell)
115
+ protected readonly shell: ApplicationShell;
116
+
117
+ @inject(TaskServer)
118
+ protected readonly taskServer: TaskServer;
119
+
120
+ @inject(ILogger) @named('task')
121
+ protected readonly logger: ILogger;
122
+
123
+ @inject(WidgetManager)
124
+ protected readonly widgetManager: WidgetManager;
125
+
126
+ @inject(TaskWatcher)
127
+ protected readonly taskWatcher: TaskWatcher;
128
+
129
+ @inject(MessageService)
130
+ protected readonly messageService: MessageService;
131
+
132
+ @inject(WorkspaceService)
133
+ protected readonly workspaceService: WorkspaceService;
134
+
135
+ @inject(TaskConfigurations)
136
+ protected readonly taskConfigurations: TaskConfigurations;
137
+
138
+ @inject(ProvidedTaskConfigurations)
139
+ protected readonly providedTaskConfigurations: ProvidedTaskConfigurations;
140
+
141
+ @inject(VariableResolverService)
142
+ protected readonly variableResolverService: VariableResolverService;
143
+
144
+ @inject(TaskResolverRegistry)
145
+ protected readonly taskResolverRegistry: TaskResolverRegistry;
146
+
147
+ @inject(TerminalService)
148
+ protected readonly terminalService: TerminalService;
149
+
150
+ @inject(EditorManager)
151
+ protected readonly editorManager: EditorManager;
152
+
153
+ @inject(ProblemManager)
154
+ protected readonly problemManager: ProblemManager;
155
+
156
+ @inject(TaskDefinitionRegistry)
157
+ protected readonly taskDefinitionRegistry: TaskDefinitionRegistry;
158
+
159
+ @inject(ProblemMatcherRegistry)
160
+ protected readonly problemMatcherRegistry: ProblemMatcherRegistry;
161
+
162
+ @inject(QuickPickService)
163
+ protected readonly quickPickService: QuickPickService;
164
+
165
+ @inject(OpenerService)
166
+ protected readonly openerService: OpenerService;
167
+
168
+ @inject(ShellTerminalServerProxy)
169
+ protected readonly shellTerminalServer: ShellTerminalServerProxy;
170
+
171
+ @inject(TaskNameResolver)
172
+ protected readonly taskNameResolver: TaskNameResolver;
173
+
174
+ @inject(TaskSourceResolver)
175
+ protected readonly taskSourceResolver: TaskSourceResolver;
176
+
177
+ @inject(TaskSchemaUpdater)
178
+ protected readonly taskSchemaUpdater: TaskSchemaUpdater;
179
+
180
+ @inject(TaskConfigurationManager)
181
+ protected readonly taskConfigurationManager: TaskConfigurationManager;
182
+
183
+ @inject(CommandService)
184
+ protected readonly commands: CommandService;
185
+
186
+ @inject(LabelProvider)
187
+ protected readonly labelProvider: LabelProvider;
188
+
189
+ @inject(MonacoWorkspace)
190
+ protected monacoWorkspace: MonacoWorkspace;
191
+
192
+ @inject(TaskTerminalWidgetManager)
193
+ protected readonly taskTerminalWidgetManager: TaskTerminalWidgetManager;
194
+
195
+ @postConstruct()
196
+ protected init(): void {
197
+ this.getRunningTasks().then(tasks =>
198
+ tasks.forEach(task => {
199
+ if (!this.runningTasks.has(task.taskId)) {
200
+ this.runningTasks.set(task.taskId, {
201
+ exitCode: new Deferred<number | undefined>(), terminateSignal: new Deferred<string | undefined>(),
202
+ isBackgroundTaskEnded: new Deferred<boolean | undefined>()
203
+ });
204
+ }
205
+ }));
206
+
207
+ // notify user that task has started
208
+ this.taskWatcher.onTaskCreated((event: TaskInfo) => {
209
+ if (!this.isEventForThisClient(event.ctx)) {
210
+ return;
211
+ }
212
+ this.runningTasks.set(event.taskId, {
213
+ exitCode: new Deferred<number | undefined>(),
214
+ terminateSignal: new Deferred<string | undefined>(),
215
+ isBackgroundTaskEnded: new Deferred<boolean | undefined>()
216
+ });
217
+ });
218
+
219
+ this.taskWatcher.onOutputProcessed(async (event: TaskOutputProcessedEvent) => {
220
+ if (!this.isEventForThisClient(event.ctx)) {
221
+ return;
222
+ }
223
+ if (event.problems) {
224
+ const runningTasksInfo: TaskInfo[] = await this.getRunningTasks();
225
+ // check if the task is active
226
+ const matchedRunningTaskInfo = runningTasksInfo.find(taskInfo => {
227
+ const taskConfig = taskInfo.config;
228
+ return this.taskDefinitionRegistry.compareTasks(taskConfig, event.config);
229
+ });
230
+ const isTaskActiveAndOutputSilent = matchedRunningTaskInfo &&
231
+ matchedRunningTaskInfo.config.presentation && matchedRunningTaskInfo.config.presentation.reveal === RevealKind.Silent;
232
+ event.problems.forEach(problem => {
233
+ const existingMarkers = this.problemManager.findMarkers({ owner: problem.description.owner });
234
+ const uris = new Set<string>();
235
+ existingMarkers.forEach(marker => uris.add(marker.uri));
236
+ if (ProblemMatchData.is(problem) && problem.resource) {
237
+ // When task.presentation.reveal === RevealKind.Silent, put focus on the terminal only if it is an error
238
+ if (isTaskActiveAndOutputSilent && problem.marker.severity === DiagnosticSeverity.Error) {
239
+ const terminalId = matchedRunningTaskInfo!.terminalId;
240
+ if (terminalId) {
241
+ const terminal = this.terminalService.getByTerminalId(terminalId);
242
+ if (terminal) {
243
+ const focus = !!matchedRunningTaskInfo!.config.presentation!.focus;
244
+ if (focus) { // assign focus to the terminal if presentation.focus is true
245
+ this.terminalService.open(terminal, { mode: 'activate' });
246
+ } else { // show the terminal but not assign focus
247
+ this.terminalService.open(terminal, { mode: 'reveal' });
248
+ }
249
+ }
250
+ }
251
+ }
252
+ const uri = new URI(problem.resource.path).withScheme(problem.resource.scheme);
253
+ const document = this.monacoWorkspace.getTextDocument(uri.toString());
254
+ if (problem.description.applyTo === ApplyToKind.openDocuments && !!document ||
255
+ problem.description.applyTo === ApplyToKind.closedDocuments && !document ||
256
+ problem.description.applyTo === ApplyToKind.allDocuments
257
+ ) {
258
+ if (uris.has(uri.toString())) {
259
+ const newData = [
260
+ ...existingMarkers
261
+ .filter(marker => marker.uri === uri.toString())
262
+ .map(markerData => markerData.data),
263
+ problem.marker
264
+ ];
265
+ this.problemManager.setMarkers(uri, problem.description.owner, newData);
266
+ } else {
267
+ this.problemManager.setMarkers(uri, problem.description.owner, [problem.marker]);
268
+ }
269
+ }
270
+ } else { // should have received an event for finding the "background task begins" pattern
271
+ uris.forEach(uriString => this.problemManager.setMarkers(new URI(uriString), problem.description.owner, []));
272
+ }
273
+ });
274
+ }
275
+ });
276
+
277
+ this.taskWatcher.onBackgroundTaskEnded((event: BackgroundTaskEndedEvent) => {
278
+ if (!this.isEventForThisClient(event.ctx)) {
279
+ return;
280
+ }
281
+
282
+ if (!this.runningTasks.has(event.taskId)) {
283
+ this.runningTasks.set(event.taskId, {
284
+ exitCode: new Deferred<number | undefined>(),
285
+ terminateSignal: new Deferred<string | undefined>(),
286
+ isBackgroundTaskEnded: new Deferred<boolean | undefined>()
287
+ });
288
+ }
289
+ this.runningTasks.get(event.taskId)!.isBackgroundTaskEnded.resolve(true);
290
+ });
291
+
292
+ // notify user that task has finished
293
+ this.taskWatcher.onTaskExit((event: TaskExitedEvent) => {
294
+ if (!this.isEventForThisClient(event.ctx)) {
295
+ return;
296
+ }
297
+ if (!this.runningTasks.has(event.taskId)) {
298
+ this.runningTasks.set(event.taskId, {
299
+ exitCode: new Deferred<number | undefined>(),
300
+ terminateSignal: new Deferred<string | undefined>(),
301
+ isBackgroundTaskEnded: new Deferred<boolean | undefined>()
302
+ });
303
+ }
304
+ this.runningTasks.get(event.taskId)!.exitCode.resolve(event.code);
305
+ this.runningTasks.get(event.taskId)!.terminateSignal.resolve(event.signal);
306
+ setTimeout(() => this.runningTasks.delete(event.taskId), 60 * 1000);
307
+
308
+ const taskConfig = event.config;
309
+ const taskIdentifier = taskConfig ? this.getTaskIdentifier(taskConfig) : event.taskId.toString();
310
+ if (event.code !== undefined) {
311
+ if (event.code !== 0) {
312
+ const eventTaskConfig = event.config;
313
+ if (eventTaskConfig && eventTaskConfig.presentation && eventTaskConfig.presentation.reveal === RevealKind.Silent && event.terminalId) {
314
+ const terminal = this.terminalService.getByTerminalId(event.terminalId);
315
+ const focus = !!eventTaskConfig.presentation.focus;
316
+ if (terminal) {
317
+ if (focus) { // assign focus to the terminal if presentation.focus is true
318
+ this.terminalService.open(terminal, { mode: 'activate' });
319
+ } else { // show the terminal but not assign focus
320
+ this.terminalService.open(terminal, { mode: 'reveal' });
321
+ }
322
+ }
323
+ }
324
+ this.messageService.error(`Task '${taskIdentifier}' has exited with code ${event.code}.`);
325
+ }
326
+ } else if (event.signal !== undefined) {
327
+ this.messageService.info(`Task '${taskIdentifier}' was terminated by signal ${event.signal}.`);
328
+ } else {
329
+ console.error('Invalid TaskExitedEvent received, neither code nor signal is set.');
330
+ }
331
+ });
332
+ }
333
+
334
+ protected getTaskIdentifier(taskConfig: TaskConfiguration): string {
335
+ const taskName = this.taskNameResolver.resolve(taskConfig);
336
+ const sourceStrUri = this.taskSourceResolver.resolve(taskConfig);
337
+ return `${taskName} (${this.labelProvider.getName(new URI(sourceStrUri))})`;
338
+ }
339
+
340
+ /**
341
+ * Client should call this method to indicate that a new user-level action related to tasks has been started,
342
+ * like invoking "Run Task..."
343
+ * This method returns a token that can be used with various methods in this service.
344
+ * As long as a client uses the same token, task providers will only asked once to contribute
345
+ * tasks and the set of tasks will be cached. Each time the a new token is used, the cache of
346
+ * contributed tasks is cleared.
347
+ * @returns a token to be used for task-related actions
348
+ */
349
+ startUserAction(): number {
350
+ return this.providedTaskConfigurations.startUserAction();
351
+ }
352
+
353
+ /**
354
+ * Returns an array of the task configurations configured in tasks.json and provided by the extensions.
355
+ * @param token The cache token for the user interaction in progress
356
+ */
357
+ async getTasks(token: number): Promise<TaskConfiguration[]> {
358
+ const configuredTasks = await this.getConfiguredTasks(token);
359
+ const providedTasks = await this.getProvidedTasks(token);
360
+ const notCustomizedProvidedTasks = providedTasks.filter(provided =>
361
+ !configuredTasks.some(configured => this.taskDefinitionRegistry.compareTasks(configured, provided))
362
+ );
363
+ return [...configuredTasks, ...notCustomizedProvidedTasks];
364
+ }
365
+
366
+ /**
367
+ * Returns an array of the valid task configurations which are configured in tasks.json files
368
+ * @param token The cache token for the user interaction in progress
369
+ *
370
+ */
371
+ async getConfiguredTasks(token: number): Promise<TaskConfiguration[]> {
372
+ const invalidTaskConfig = this.taskConfigurations.getInvalidTaskConfigurations()[0];
373
+ if (invalidTaskConfig) {
374
+ const widget = <ProblemWidget>await this.widgetManager.getOrCreateWidget(PROBLEMS_WIDGET_ID);
375
+ const isProblemsWidgetVisible = widget && widget.isVisible;
376
+ const currentEditorUri = this.editorManager.currentEditor && this.editorManager.currentEditor.editor.getResourceUri();
377
+ let isInvalidTaskConfigFileOpen = false;
378
+ if (currentEditorUri) {
379
+ const folderUri = this.workspaceService.getWorkspaceRootUri(currentEditorUri);
380
+ if (folderUri && folderUri.toString() === invalidTaskConfig._scope) {
381
+ isInvalidTaskConfigFileOpen = true;
382
+ }
383
+ }
384
+ const warningMessage = 'Invalid task configurations are found. Open tasks.json and find details in the Problems view.';
385
+ if (!isProblemsWidgetVisible || !isInvalidTaskConfigFileOpen) {
386
+ this.messageService.warn(warningMessage, 'Open').then(actionOpen => {
387
+ if (actionOpen) {
388
+ if (invalidTaskConfig && invalidTaskConfig._scope) {
389
+ this.taskConfigurationManager.openConfiguration(invalidTaskConfig._scope);
390
+ }
391
+ if (!isProblemsWidgetVisible) {
392
+ this.commands.executeCommand('problemsView:toggle');
393
+ }
394
+ }
395
+ });
396
+ } else {
397
+ this.messageService.warn(warningMessage);
398
+ }
399
+ }
400
+
401
+ const validTaskConfigs = await this.taskConfigurations.getTasks(token);
402
+ return validTaskConfigs;
403
+ }
404
+
405
+ /**
406
+ * Returns an array of the task configurations which are provided by the extensions.
407
+ * @param token The cache token for the user interaction in progress
408
+ */
409
+ getProvidedTasks(token: number): Promise<TaskConfiguration[]> {
410
+ return this.providedTaskConfigurations.getTasks(token);
411
+ }
412
+
413
+ addRecentTasks(tasks: TaskConfiguration | TaskConfiguration[]): void {
414
+ if (Array.isArray(tasks)) {
415
+ tasks.forEach(task => this.addRecentTasks(task));
416
+ } else {
417
+ const ind = this.cachedRecentTasks.findIndex(recent => this.taskDefinitionRegistry.compareTasks(recent, tasks));
418
+ if (ind >= 0) {
419
+ this.cachedRecentTasks.splice(ind, 1);
420
+ }
421
+ this.cachedRecentTasks.unshift(tasks);
422
+ }
423
+ }
424
+
425
+ get recentTasks(): TaskConfiguration[] {
426
+ return this.cachedRecentTasks;
427
+ }
428
+
429
+ set recentTasks(recent: TaskConfiguration[]) {
430
+ this.cachedRecentTasks = recent;
431
+ }
432
+
433
+ /**
434
+ * Clears the list of recently used tasks.
435
+ */
436
+ clearRecentTasks(): void {
437
+ this.cachedRecentTasks = [];
438
+ }
439
+
440
+ /**
441
+ * Open user ser
442
+ */
443
+ openUserTasks(): Promise<void> {
444
+ return this.taskConfigurations.openUserTasks();
445
+ }
446
+
447
+ /**
448
+ * Returns a task configuration provided by an extension by task source, scope and label.
449
+ * If there are no task configuration, returns undefined.
450
+ * @param token The cache token for the user interaction in progress
451
+ * @param source The source for configured tasks
452
+ * @param label The label of the task to find
453
+ * @param scope The task scope to look in
454
+ */
455
+ async getProvidedTask(token: number, source: string, label: string, scope: TaskConfigurationScope): Promise<TaskConfiguration | undefined> {
456
+ return this.providedTaskConfigurations.getTask(token, source, label, scope);
457
+ }
458
+
459
+ /** Returns an array of running tasks 'TaskInfo' objects */
460
+ getRunningTasks(): Promise<TaskInfo[]> {
461
+ return this.taskServer.getTasks(this.getContext());
462
+ }
463
+
464
+ async customExecutionComplete(id: number, exitCode: number | undefined): Promise<void> {
465
+ return this.taskServer.customExecutionComplete(id, exitCode);
466
+ }
467
+
468
+ /** Returns an array of task types that are registered, including the default types */
469
+ getRegisteredTaskTypes(): Promise<string[]> {
470
+ return this.taskSchemaUpdater.getRegisteredTaskTypes();
471
+ }
472
+
473
+ /**
474
+ * Get the last executed task.
475
+ *
476
+ * @returns the last executed task or `undefined`.
477
+ */
478
+ getLastTask(): LastRunTaskInfo {
479
+ return this.lastTask;
480
+ }
481
+
482
+ /**
483
+ * Runs a task, by task configuration label.
484
+ * Note, it looks for a task configured in tasks.json only.
485
+ * @param token The cache token for the user interaction in progress
486
+ * @param scope The scope where to look for tasks
487
+ * @param taskLabel the label to look for
488
+ */
489
+ async runConfiguredTask(token: number, scope: TaskConfigurationScope, taskLabel: string): Promise<void> {
490
+ const task = this.taskConfigurations.getTask(scope, taskLabel);
491
+ if (!task) {
492
+ this.logger.error(`Can't get task launch configuration for label: ${taskLabel}`);
493
+ return;
494
+ }
495
+
496
+ this.run(token, task._source, taskLabel, scope);
497
+ }
498
+
499
+ /**
500
+ * Run the last executed task.
501
+ * @param token The cache token for the user interaction in progress
502
+ */
503
+ async runLastTask(token: number): Promise<TaskInfo | undefined> {
504
+ if (!this.lastTask?.resolvedTask) {
505
+ return;
506
+ }
507
+ if (!this.lastTask.resolvedTask.runOptions?.reevaluateOnRerun) {
508
+ return this.runResolvedTask(this.lastTask.resolvedTask, this.lastTask.option);
509
+ }
510
+ const { _source, label, _scope } = this.lastTask.resolvedTask;
511
+ return this.run(token, _source, label, _scope);
512
+ }
513
+
514
+ /**
515
+ * Runs a task, by the source and label of the task configuration.
516
+ * It looks for configured and detected tasks.
517
+ * @param token The cache token for the user interaction in progress
518
+ * @param source The source for configured tasks
519
+ * @param taskLabel The label to look for
520
+ * @param scope The scope where to look for tasks
521
+ */
522
+ async run(token: number, source: string, taskLabel: string, scope: TaskConfigurationScope): Promise<TaskInfo | undefined> {
523
+ let task: TaskConfiguration | undefined;
524
+ task = this.taskConfigurations.getTask(scope, taskLabel);
525
+ if (!task) { // if a configured task cannot be found, search from detected tasks
526
+ task = await this.getProvidedTask(token, source, taskLabel, scope);
527
+ if (!task) { // find from the customized detected tasks
528
+ task = await this.taskConfigurations.getCustomizedTask(token, scope, taskLabel);
529
+ }
530
+ if (!task) {
531
+ this.logger.error(`Can't get task launch configuration for label: ${taskLabel}`);
532
+ return;
533
+ }
534
+ }
535
+ const customizationObject = await this.getTaskCustomization(task);
536
+
537
+ if (!customizationObject.problemMatcher) {
538
+ // ask the user what s/he wants to use to parse the task output
539
+ const items = this.getCustomizeProblemMatcherItems();
540
+ const selected = await this.quickPickService.show(items, {
541
+ placeholder: 'Select for which kind of errors and warnings to scan the task output'
542
+ });
543
+ if (selected && ('value' in selected)) {
544
+ if (selected.value?.problemMatchers) {
545
+ let matcherNames: string[] = [];
546
+ if (selected.value.problemMatchers && selected.value.problemMatchers.length === 0) { // never parse output for this task
547
+ matcherNames = [];
548
+ } else if (selected.value.problemMatchers && selected.value.problemMatchers.length > 0) { // continue with user-selected parser
549
+ matcherNames = selected.value.problemMatchers.map(matcher => matcher.name);
550
+ }
551
+ customizationObject.problemMatcher = matcherNames;
552
+
553
+ // write the selected matcher (or the decision of "never parse") into the `tasks.json`
554
+ this.updateTaskConfiguration(token, task, { problemMatcher: matcherNames });
555
+ } else if (selected.value?.learnMore) { // user wants to learn more about parsing task output
556
+ open(this.openerService, new URI('https://code.visualstudio.com/docs/editor/tasks#_processing-task-output-with-problem-matchers'));
557
+ }
558
+ // else, continue the task with no parser
559
+ } else { // do not start the task in case that the user did not select any item from the list
560
+ return;
561
+ }
562
+ }
563
+
564
+ const resolvedMatchers = await this.resolveProblemMatchers(task, customizationObject);
565
+ const runTaskOption: RunTaskOption = {
566
+ customization: { ...customizationObject, ...{ problemMatcher: resolvedMatchers } }
567
+ };
568
+
569
+ if (task.dependsOn) {
570
+ return this.runCompoundTask(token, task, runTaskOption);
571
+ } else {
572
+ return this.runTask(task, runTaskOption).catch(error => {
573
+ console.error('Error at launching task', error);
574
+ return undefined;
575
+ });
576
+ }
577
+ }
578
+
579
+ /**
580
+ * Runs a compound task
581
+ * @param token The cache token for the user interaction in progress
582
+ * @param task The task to be executed
583
+ * @param option options for executing the task
584
+ */
585
+ async runCompoundTask(token: number, task: TaskConfiguration, option?: RunTaskOption): Promise<TaskInfo | undefined> {
586
+ const tasks = await this.getWorkspaceTasks(token, task._scope);
587
+ try {
588
+ const rootNode = new TaskNode(task, [], []);
589
+ this.detectDirectedAcyclicGraph(task, rootNode, tasks);
590
+ } catch (error) {
591
+ console.error(`Error at launching task '${task.label}'`, error);
592
+ this.messageService.error(error.message);
593
+ return undefined;
594
+ }
595
+ return this.runTasksGraph(task, tasks, option).catch(error => {
596
+ console.error(`Error at launching task '${task.label}'`, error);
597
+ return undefined;
598
+ });
599
+ }
600
+
601
+ /**
602
+ * A recursive function that runs a task and all its sub tasks that it depends on.
603
+ * A task can be executed only when all of its dependencies have been executed, or when it doesn’t have any dependencies at all.
604
+ */
605
+ async runTasksGraph(task: TaskConfiguration, tasks: TaskConfiguration[], option?: RunTaskOption): Promise<TaskInfo | undefined> {
606
+ if (task && task.dependsOn) {
607
+ // In case it is an array of task dependencies
608
+ if (Array.isArray(task.dependsOn) && task.dependsOn.length > 0) {
609
+ const dependentTasks: { 'task': TaskConfiguration; 'taskCustomization': TaskCustomization; 'resolvedMatchers': ProblemMatcher[] | undefined }[] = [];
610
+ for (let i = 0; i < task.dependsOn.length; i++) {
611
+ // It may be a string (a task label) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
612
+ const taskIdentifier = task.dependsOn[i];
613
+ const dependentTask = this.getDependentTask(taskIdentifier, tasks);
614
+ const taskCustomization = await this.getTaskCustomization(dependentTask);
615
+ const resolvedMatchers = await this.resolveProblemMatchers(dependentTask, taskCustomization);
616
+ dependentTasks.push({ 'task': dependentTask, 'taskCustomization': taskCustomization, 'resolvedMatchers': resolvedMatchers });
617
+ // In case the 'dependsOrder' is 'sequence'
618
+ if (task.dependsOrder && task.dependsOrder === DependsOrder.Sequence) {
619
+ await this.runTasksGraph(dependentTask, tasks, {
620
+ customization: { ...taskCustomization, ...{ problemMatcher: resolvedMatchers } }
621
+ });
622
+ }
623
+ }
624
+ // In case the 'dependsOrder' is 'parallel'
625
+ if (((!task.dependsOrder) || (task.dependsOrder && task.dependsOrder === DependsOrder.Parallel))) {
626
+ const promises = dependentTasks.map(item =>
627
+ this.runTasksGraph(item.task, tasks, {
628
+ customization: { ...item.taskCustomization, ...{ problemMatcher: item.resolvedMatchers } }
629
+ })
630
+ );
631
+ await Promise.all(promises);
632
+ }
633
+ } else if (!Array.isArray(task.dependsOn)) {
634
+ // In case it is a string (a task label) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
635
+ const taskIdentifier = task.dependsOn;
636
+ const dependentTask = this.getDependentTask(taskIdentifier, tasks);
637
+ const taskCustomization = await this.getTaskCustomization(dependentTask);
638
+ const resolvedMatchers = await this.resolveProblemMatchers(dependentTask, taskCustomization);
639
+ await this.runTasksGraph(dependentTask, tasks, {
640
+ customization: { ...taskCustomization, ...{ problemMatcher: resolvedMatchers } }
641
+ });
642
+ }
643
+ }
644
+
645
+ const taskInfo = await this.runTask(task, option);
646
+ if (taskInfo) {
647
+ const getExitCodePromise: Promise<TaskEndedInfo> = this.getExitCode(taskInfo.taskId).then(result => ({ taskEndedType: TaskEndedTypes.TaskExited, value: result }));
648
+ const isBackgroundTaskEndedPromise: Promise<TaskEndedInfo> = this.isBackgroundTaskEnded(taskInfo.taskId).then(result =>
649
+ ({ taskEndedType: TaskEndedTypes.BackgroundTaskEnded, value: result }));
650
+
651
+ // After start running the task, we wait for the task process to exit and if it is a background task, we also wait for a feedback
652
+ // that a background task is active, as soon as one of the promises fulfills, we can continue and analyze the results.
653
+ const taskEndedInfo: TaskEndedInfo = await Promise.race([getExitCodePromise, isBackgroundTaskEndedPromise]);
654
+
655
+ if ((taskEndedInfo.taskEndedType === TaskEndedTypes.TaskExited && taskEndedInfo.value !== 0) ||
656
+ (taskEndedInfo.taskEndedType === TaskEndedTypes.BackgroundTaskEnded && !taskEndedInfo.value)) {
657
+ throw new Error('The task: ' + task.label + ' terminated with exit code ' + taskEndedInfo.value + '.');
658
+ }
659
+ }
660
+ return taskInfo;
661
+ }
662
+
663
+ /**
664
+ * Creates a graph of dependencies tasks from the root task and verify there is no DAG (Directed Acyclic Graph).
665
+ * In case of detection of a circular dependency, an error is thrown with a message which describes the detected circular reference.
666
+ */
667
+ detectDirectedAcyclicGraph(task: TaskConfiguration, taskNode: TaskNode, tasks: TaskConfiguration[]): void {
668
+ if (task && task.dependsOn) {
669
+ // In case the 'dependsOn' is an array
670
+ if (Array.isArray(task.dependsOn) && task.dependsOn.length > 0) {
671
+ for (let i = 0; i < task.dependsOn.length; i++) {
672
+ const childNode = this.createChildTaskNode(task, taskNode, task.dependsOn[i], tasks);
673
+ this.detectDirectedAcyclicGraph(childNode.taskConfiguration, childNode.node, tasks);
674
+ }
675
+ } else if (!Array.isArray(task.dependsOn)) {
676
+ const childNode = this.createChildTaskNode(task, taskNode, task.dependsOn, tasks);
677
+ this.detectDirectedAcyclicGraph(childNode.taskConfiguration, childNode.node, tasks);
678
+ }
679
+ }
680
+ }
681
+
682
+ // 'childTaskIdentifier' may be a string (a task label) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
683
+ createChildTaskNode(task: TaskConfiguration, taskNode: TaskNode, childTaskIdentifier: string | TaskIdentifier, tasks: TaskConfiguration[]): TaskGraphNode {
684
+ const childTaskConfiguration = this.getDependentTask(childTaskIdentifier, tasks);
685
+
686
+ // If current task and child task are identical or if
687
+ // one of the child tasks is identical to one of the current task ancestors, then raise an error
688
+ if (this.taskDefinitionRegistry.compareTasks(task, childTaskConfiguration) ||
689
+ taskNode.parentsID.filter(t => this.taskDefinitionRegistry.compareTasks(childTaskConfiguration, t)).length > 0) {
690
+ const fromNode = task.label;
691
+ const toNode = childTaskConfiguration.label;
692
+ throw new Error('Circular reference detected: ' + fromNode + ' --> ' + toNode);
693
+ }
694
+ const childNode = new TaskNode(childTaskConfiguration, [], Object.assign([], taskNode.parentsID));
695
+ childNode.addParentDependency(taskNode.taskId);
696
+ taskNode.addChildDependency(childNode);
697
+ return { 'taskConfiguration': childTaskConfiguration, 'node': childNode };
698
+ }
699
+
700
+ /**
701
+ * Gets task configuration by task label or by a JSON object which represents a task identifier
702
+ *
703
+ * @param taskIdentifier The task label (string) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
704
+ * @param tasks an array of the task configurations
705
+ * @returns the correct TaskConfiguration object which matches the taskIdentifier
706
+ */
707
+ getDependentTask(taskIdentifier: string | TaskIdentifier, tasks: TaskConfiguration[]): TaskConfiguration {
708
+ const notEnoughDataError = 'The information provided in the "dependsOn" is not enough for matching the correct task !';
709
+ let currentTaskChildConfiguration: TaskConfiguration;
710
+ if (typeof (taskIdentifier) !== 'string') {
711
+ // TaskIdentifier object does not support tasks of type 'shell' (The same behavior as in VS Code).
712
+ // So if we want the 'dependsOn' property to include tasks of type 'shell',
713
+ // then we must mention their labels (in the 'dependsOn' property) and not to create a task identifier object for them.
714
+ currentTaskChildConfiguration = this.getTaskByTaskIdentifier(taskIdentifier, tasks);
715
+ if (!currentTaskChildConfiguration.type) {
716
+ this.messageService.error(notEnoughDataError);
717
+ throw new Error(notEnoughDataError);
718
+ }
719
+ return currentTaskChildConfiguration;
720
+ } else {
721
+ currentTaskChildConfiguration = tasks.filter(t => taskIdentifier === this.taskNameResolver.resolve(t))[0];
722
+ return currentTaskChildConfiguration;
723
+ }
724
+ }
725
+
726
+ /**
727
+ * Gets the matched task from an array of task configurations by TaskIdentifier.
728
+ * In case that more than one task configuration matches, we returns the first one.
729
+ *
730
+ * @param taskIdentifier The task label (string) or a JSON object which represents a TaskIdentifier (e.g. {"type":"npm", "script":"script1"})
731
+ * @param tasks An array of task configurations.
732
+ * @returns The correct TaskConfiguration object which matches the taskIdentifier.
733
+ */
734
+ getTaskByTaskIdentifier(taskIdentifier: TaskIdentifier, tasks: TaskConfiguration[]): TaskConfiguration {
735
+ const requiredProperties = Object.keys(taskIdentifier);
736
+ const taskWithAllProperties = tasks.find(task => requiredProperties.every(property => task.hasOwnProperty(property) && task[property] === taskIdentifier[property]));
737
+ return taskWithAllProperties ?? { label: '', _scope: '', type: '' }; // Fall back to empty TaskConfiguration
738
+ }
739
+
740
+ async runTask(task: TaskConfiguration, option?: RunTaskOption): Promise<TaskInfo | undefined> {
741
+ console.debug('entering runTask');
742
+ const releaseLock = await this.taskStartingLock.acquire();
743
+ console.debug('got lock');
744
+
745
+ try {
746
+ // resolve problemMatchers
747
+ if (!option && task.problemMatcher) {
748
+ const customizationObject: TaskCustomization = { type: task.taskType, problemMatcher: task.problemMatcher, runOptions: task.runOptions };
749
+ const resolvedMatchers = await this.resolveProblemMatchers(task, customizationObject);
750
+ option = {
751
+ customization: { ...customizationObject, ...{ problemMatcher: resolvedMatchers } }
752
+ };
753
+ }
754
+
755
+ const runningTasksInfo: TaskInfo[] = await this.getRunningTasks();
756
+ // check if the task is active
757
+ const matchedRunningTaskInfo = runningTasksInfo.find(taskInfo => {
758
+ const taskConfig = taskInfo.config;
759
+ return this.taskDefinitionRegistry.compareTasks(taskConfig, task);
760
+ });
761
+ console.debug(`running task ${JSON.stringify(task)}, already running = ${!!matchedRunningTaskInfo}`);
762
+
763
+ if (matchedRunningTaskInfo) { // the task is active
764
+ releaseLock();
765
+ console.debug('released lock');
766
+ const taskName = this.taskNameResolver.resolve(task);
767
+ const terminalId = matchedRunningTaskInfo.terminalId;
768
+ if (terminalId) {
769
+ const terminal = this.terminalService.getByTerminalId(terminalId);
770
+ if (terminal) {
771
+ if (TaskOutputPresentation.shouldSetFocusToTerminal(task)) { // assign focus to the terminal if presentation.focus is true
772
+ this.terminalService.open(terminal, { mode: 'activate' });
773
+ } else if (TaskOutputPresentation.shouldAlwaysRevealTerminal(task)) { // show the terminal but not assign focus
774
+ this.terminalService.open(terminal, { mode: 'reveal' });
775
+ }
776
+ }
777
+ }
778
+ const selectedAction = await this.messageService.info(`The task '${taskName}' is already active`, 'Terminate Task', 'Restart Task');
779
+ if (selectedAction === 'Terminate Task') {
780
+ await this.terminateTask(matchedRunningTaskInfo);
781
+ } else if (selectedAction === 'Restart Task') {
782
+ return this.restartTask(matchedRunningTaskInfo, option);
783
+ }
784
+ } else { // run task as the task is not active
785
+ console.debug('task about to start');
786
+ const taskInfo = await this.doRunTask(task, option);
787
+ releaseLock();
788
+ console.debug('release lock 2');
789
+ return taskInfo;
790
+ }
791
+ } catch (e) {
792
+ releaseLock();
793
+ throw e;
794
+ }
795
+ }
796
+
797
+ /**
798
+ * Terminates a task that is actively running.
799
+ * @param activeTaskInfo the TaskInfo of the task that is actively running
800
+ */
801
+ async terminateTask(activeTaskInfo: TaskInfo): Promise<void> {
802
+ const taskId = activeTaskInfo.taskId;
803
+ return this.kill(taskId);
804
+ }
805
+
806
+ /**
807
+ * Terminates a task that is actively running, and restarts it.
808
+ * @param activeTaskInfo the TaskInfo of the task that is actively running
809
+ */
810
+ async restartTask(activeTaskInfo: TaskInfo, option?: RunTaskOption): Promise<TaskInfo | undefined> {
811
+ await this.terminateTask(activeTaskInfo);
812
+ return this.doRunTask(activeTaskInfo.config, option);
813
+ }
814
+
815
+ protected async doRunTask(task: TaskConfiguration, option?: RunTaskOption): Promise<TaskInfo | undefined> {
816
+ let overridePropertiesFunction: (task: TaskConfiguration) => void = () => { };
817
+ if (option && option.customization) {
818
+ const taskDefinition = this.taskDefinitionRegistry.getDefinition(task);
819
+ if (taskDefinition) { // use the customization object to override the task config
820
+ overridePropertiesFunction = tsk => {
821
+ Object.keys(option.customization!).forEach(customizedProperty => {
822
+ // properties used to define the task cannot be customized
823
+ if (customizedProperty !== 'type' && !taskDefinition.properties.all.some(pDefinition => pDefinition === customizedProperty)) {
824
+ tsk[customizedProperty] = option.customization![customizedProperty];
825
+ }
826
+ });
827
+ };
828
+ }
829
+ }
830
+ overridePropertiesFunction(task);
831
+ this.addRecentTasks(task);
832
+ try {
833
+ const resolver = await this.taskResolverRegistry.getTaskResolver(task.type);
834
+ const resolvedTask = resolver ? await resolver.resolveTask(task) : task;
835
+ const executionResolver = this.taskResolverRegistry.getExecutionResolver(resolvedTask.taskType || resolvedTask.type);
836
+ overridePropertiesFunction(resolvedTask);
837
+ const taskToRun = executionResolver ? await executionResolver.resolveTask(resolvedTask) : resolvedTask;
838
+
839
+ await this.removeProblemMarkers(option);
840
+ return this.runResolvedTask(taskToRun, option);
841
+ } catch (error) {
842
+ const errMessage = `Error resolving task '${task.label}': ${error}`;
843
+ this.logger.error(errMessage);
844
+ }
845
+ return undefined;
846
+ }
847
+
848
+ /**
849
+ * Runs the first task with the given label.
850
+ *
851
+ * @param token The cache token for the user interaction in progress
852
+ * @param taskLabel The label of the task to be executed
853
+ */
854
+ async runTaskByLabel(token: number, taskLabel: string): Promise<TaskInfo | undefined> {
855
+ const tasks: TaskConfiguration[] = await this.getTasks(token);
856
+ for (const task of tasks) {
857
+ if (task.label === taskLabel) {
858
+ return this.runTask(task);
859
+ }
860
+ }
861
+ return;
862
+ }
863
+
864
+ /**
865
+ * Runs a task identified by the given identifier, but only if found in the given workspace folder
866
+ *
867
+ * @param token The cache token for the user interaction in progress
868
+ * @param workspaceFolderUri The folder to restrict the search to
869
+ * @param taskIdentifier The identifier to look for
870
+ */
871
+ async runWorkspaceTask(token: number, workspaceFolderUri: string | undefined, taskIdentifier: string | TaskIdentifier): Promise<TaskInfo | undefined> {
872
+ const tasks = await this.getWorkspaceTasks(token, workspaceFolderUri);
873
+ const task = this.getDependentTask(taskIdentifier, tasks);
874
+ if (!task) {
875
+ return undefined;
876
+ }
877
+
878
+ const taskCustomization = await this.getTaskCustomization(task);
879
+ const resolvedMatchers = await this.resolveProblemMatchers(task, taskCustomization);
880
+ try {
881
+ const rootNode = new TaskNode(task, [], []);
882
+ this.detectDirectedAcyclicGraph(task, rootNode, tasks);
883
+ } catch (error) {
884
+ this.logger.error(error.message);
885
+ this.messageService.error(error.message);
886
+ return undefined;
887
+ }
888
+ return this.runTasksGraph(task, tasks, {
889
+ customization: { ...taskCustomization, ...{ problemMatcher: resolvedMatchers } }
890
+ }).catch(error => {
891
+ console.log(error.message);
892
+ return undefined;
893
+ });
894
+ }
895
+
896
+ /**
897
+ * Updates the task configuration in the `tasks.json`.
898
+ * The task config, together with updates, will be written into the `tasks.json` if it is not found in the file.
899
+ *
900
+ * @param token The cache token for the user interaction in progress
901
+ * @param task task that the updates will be applied to
902
+ * @param update the updates to be applied
903
+ */
904
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
905
+ async updateTaskConfiguration(token: number, task: TaskConfiguration, update: { [name: string]: any }): Promise<void> {
906
+ if (update.problemMatcher) {
907
+ if (Array.isArray(update.problemMatcher)) {
908
+ update.problemMatcher.forEach((name, index) => {
909
+ if (!name.startsWith('$')) {
910
+ update.problemMatcher[index] = `$${update.problemMatcher[index]}`;
911
+ }
912
+ });
913
+ } else if (!update.problemMatcher.startsWith('$')) {
914
+ update.problemMatcher = `$${update.problemMatcher}`;
915
+ }
916
+ }
917
+ this.taskConfigurations.updateTaskConfig(token, task, update);
918
+ }
919
+
920
+ protected async getWorkspaceTasks(token: number, restrictToFolder: TaskConfigurationScope | undefined): Promise<TaskConfiguration[]> {
921
+ const tasks = await this.getTasks(token);
922
+ // if we pass undefined, return everything, otherwise only tasks with the same uri or workspace/global scope tasks
923
+ return tasks.filter(t => typeof t._scope !== 'string' || t._scope === restrictToFolder);
924
+ }
925
+
926
+ protected async resolveProblemMatchers(task: TaskConfiguration, customizationObject: TaskCustomization): Promise<ProblemMatcher[] | undefined> {
927
+ const notResolvedMatchers = customizationObject.problemMatcher ?
928
+ (Array.isArray(customizationObject.problemMatcher) ? customizationObject.problemMatcher : [customizationObject.problemMatcher]) : undefined;
929
+ let resolvedMatchers: ProblemMatcher[] | undefined = [];
930
+ if (notResolvedMatchers) {
931
+ // resolve matchers before passing them to the server
932
+ for (const matcher of notResolvedMatchers) {
933
+ let resolvedMatcher: ProblemMatcher | undefined;
934
+ await this.problemMatcherRegistry.onReady();
935
+ if (typeof matcher === 'string') {
936
+ resolvedMatcher = this.problemMatcherRegistry.get(matcher);
937
+ } else {
938
+ resolvedMatcher = await this.problemMatcherRegistry.getProblemMatcherFromContribution(matcher);
939
+ }
940
+ if (resolvedMatcher) {
941
+ const scope = task._scope || task._source;
942
+ if (resolvedMatcher.filePrefix && scope) {
943
+ const options = {
944
+ context: new URI(scope).withScheme('file'),
945
+ configurationSection: 'tasks'
946
+ };
947
+ const resolvedPrefix = await this.variableResolverService.resolve(resolvedMatcher.filePrefix, options);
948
+ Object.assign(resolvedMatcher, { filePrefix: resolvedPrefix });
949
+ }
950
+ resolvedMatchers.push(resolvedMatcher);
951
+ }
952
+ }
953
+ } else {
954
+ resolvedMatchers = undefined;
955
+ }
956
+ return resolvedMatchers;
957
+ }
958
+
959
+ protected async getTaskCustomization(task: TaskConfiguration): Promise<TaskCustomization> {
960
+ const customizationObject: TaskCustomization = { type: '', _scope: task._scope, runOptions: task.runOptions };
961
+ const customizationFound = this.taskConfigurations.getCustomizationForTask(task);
962
+ if (customizationFound) {
963
+ Object.assign(customizationObject, customizationFound);
964
+ } else {
965
+ Object.assign(customizationObject, {
966
+ type: task.type,
967
+ problemMatcher: task.problemMatcher
968
+ });
969
+ }
970
+ return customizationObject;
971
+ }
972
+
973
+ protected async removeProblemMarkers(option?: RunTaskOption): Promise<void> {
974
+ if (option && option.customization) {
975
+ const matchersFromOption = option.customization.problemMatcher || [];
976
+ for (const matcher of matchersFromOption) {
977
+ if (matcher && matcher.owner) {
978
+ const existingMarkers = this.problemManager.findMarkers({ owner: matcher.owner });
979
+ const uris = new Set<string>();
980
+ existingMarkers.forEach(marker => uris.add(marker.uri));
981
+ uris.forEach(uriString => this.problemManager.setMarkers(new URI(uriString), matcher.owner, []));
982
+ }
983
+ }
984
+ }
985
+ }
986
+
987
+ /**
988
+ * Runs the resolved task and opens terminal widget if the task is based on a terminal process
989
+ * @param resolvedTask the resolved task
990
+ * @param option options to run the resolved task
991
+ */
992
+ protected async runResolvedTask(resolvedTask: TaskConfiguration, option?: RunTaskOption): Promise<TaskInfo | undefined> {
993
+ const taskLabel = resolvedTask.label;
994
+ let taskInfo: TaskInfo | undefined;
995
+ try {
996
+ taskInfo = await this.taskServer.run(resolvedTask, this.getContext(), option);
997
+ this.lastTask = {resolvedTask, option };
998
+ this.logger.debug(`Task created. Task id: ${taskInfo.taskId}`);
999
+
1000
+ /**
1001
+ * open terminal widget if the task is based on a terminal process (type: 'shell' or 'process')
1002
+ *
1003
+ * @todo Use a different mechanism to determine if the task should be attached?
1004
+ * Reason: Maybe a new task type wants to also be displayed in a terminal.
1005
+ */
1006
+ if (typeof taskInfo.terminalId === 'number') {
1007
+ await this.attach(taskInfo.terminalId, taskInfo);
1008
+ }
1009
+ return taskInfo;
1010
+ } catch (error) {
1011
+ const errorStr = `Error launching task '${taskLabel}': ${error.message}`;
1012
+ this.logger.error(errorStr);
1013
+ this.messageService.error(errorStr);
1014
+ if (taskInfo && typeof taskInfo.terminalId === 'number') {
1015
+ this.shellTerminalServer.onAttachAttempted(taskInfo.terminalId);
1016
+ }
1017
+ }
1018
+ }
1019
+
1020
+ protected getCustomizeProblemMatcherItems(): Array<QuickPickValue<QuickPickProblemMatcherItem> | QuickPickItemOrSeparator> {
1021
+ const items: Array<QuickPickValue<QuickPickProblemMatcherItem> | QuickPickItemOrSeparator> = [];
1022
+ items.push({
1023
+ label: 'Continue without scanning the task output',
1024
+ value: { problemMatchers: undefined }
1025
+ });
1026
+ items.push({
1027
+ label: 'Never scan the task output',
1028
+ value: { problemMatchers: [] }
1029
+ });
1030
+ items.push({
1031
+ label: 'Learn more about scanning the task output',
1032
+ value: { problemMatchers: undefined, learnMore: true }
1033
+ });
1034
+ items.push({ type: 'separator', label: 'registered parsers' });
1035
+
1036
+ const registeredProblemMatchers = this.problemMatcherRegistry.getAll();
1037
+ items.push(...registeredProblemMatchers.map(matcher =>
1038
+ ({
1039
+ label: matcher.label,
1040
+ value: { problemMatchers: [matcher] },
1041
+ description: matcher.name.startsWith('$') ? matcher.name : `$${matcher.name}`
1042
+ })
1043
+ ));
1044
+ return items;
1045
+ }
1046
+
1047
+ /**
1048
+ * Run selected text in the last active terminal.
1049
+ */
1050
+ async runSelectedText(): Promise<void> {
1051
+ if (!this.editorManager.currentEditor) { return; }
1052
+ const startLine = this.editorManager.currentEditor.editor.selection.start.line;
1053
+ const startCharacter = this.editorManager.currentEditor.editor.selection.start.character;
1054
+ const endLine = this.editorManager.currentEditor.editor.selection.end.line;
1055
+ const endCharacter = this.editorManager.currentEditor.editor.selection.end.character;
1056
+ let selectedRange: Range = Range.create(startLine, startCharacter, endLine, endCharacter);
1057
+ // if no text is selected, default to selecting entire line
1058
+ if (startLine === endLine && startCharacter === endCharacter) {
1059
+ selectedRange = Range.create(startLine, 0, endLine + 1, 0);
1060
+ }
1061
+ const selectedText: string = this.editorManager.currentEditor.editor.document.getText(selectedRange).trimRight() + '\n';
1062
+ let terminal = this.terminalService.lastUsedTerminal;
1063
+ if (!terminal || terminal.kind !== 'user' || (await terminal.hasChildProcesses())) {
1064
+ terminal = <TerminalWidget>await this.terminalService.newTerminal(<TerminalWidgetFactoryOptions>{ created: new Date().toString() });
1065
+ await terminal.start();
1066
+ this.terminalService.open(terminal);
1067
+ }
1068
+ terminal.sendText(selectedText);
1069
+ }
1070
+
1071
+ async attach(terminalId: number, taskInfo: TaskInfo): Promise<number | void> {
1072
+ let widgetOpenMode: WidgetOpenMode = 'open';
1073
+ if (taskInfo) {
1074
+ const terminalWidget = this.terminalService.getByTerminalId(terminalId);
1075
+ if (terminalWidget) {
1076
+ this.messageService.error('Task is already running in terminal');
1077
+ return this.terminalService.open(terminalWidget, { mode: 'activate' });
1078
+ }
1079
+ if (TaskOutputPresentation.shouldAlwaysRevealTerminal(taskInfo.config)) {
1080
+ if (TaskOutputPresentation.shouldSetFocusToTerminal(taskInfo.config)) { // assign focus to the terminal if presentation.focus is true
1081
+ widgetOpenMode = 'activate';
1082
+ } else { // show the terminal but not assign focus
1083
+ widgetOpenMode = 'reveal';
1084
+ }
1085
+ }
1086
+ }
1087
+ const { taskId } = taskInfo;
1088
+ // Create / find a terminal widget to display an execution output of a task that was launched as a command inside a shell.
1089
+ const widget = await this.taskTerminalWidgetManager.open({
1090
+ created: new Date().toString(),
1091
+ id: this.getTerminalWidgetId(terminalId),
1092
+ title: taskInfo
1093
+ ? `Task: ${taskInfo.config.label}`
1094
+ : `Task: #${taskId}`,
1095
+ destroyTermOnClose: true
1096
+ }, {
1097
+ widgetOptions: { area: 'bottom' },
1098
+ mode: widgetOpenMode,
1099
+ taskInfo
1100
+ });
1101
+ return widget.start(terminalId);
1102
+ }
1103
+
1104
+ protected getTerminalWidgetId(terminalId: number): string | undefined {
1105
+ const terminalWidget = this.terminalService.getByTerminalId(terminalId);
1106
+ if (terminalWidget) {
1107
+ return terminalWidget.id;
1108
+ }
1109
+ }
1110
+
1111
+ /**
1112
+ * Opens an editor to configure the given task.
1113
+ *
1114
+ * @param token The cache token for the user interaction in progress
1115
+ * @param task The task to configure
1116
+ */
1117
+ async configure(token: number, task: TaskConfiguration): Promise<void> {
1118
+ Object.assign(task, { label: this.taskNameResolver.resolve(task) });
1119
+ await this.taskConfigurations.configure(token, task);
1120
+ }
1121
+
1122
+ protected isEventForThisClient(context: string | undefined): boolean {
1123
+ if (context === this.getContext()) {
1124
+ return true;
1125
+ }
1126
+ return false;
1127
+ }
1128
+
1129
+ taskConfigurationChanged(event: string[]): void {
1130
+ // do nothing for now
1131
+ }
1132
+
1133
+ protected getContext(): string | undefined {
1134
+ return this.workspaceService.workspace?.resource.toString();
1135
+ }
1136
+
1137
+ /** Kill task for a given id if task is found */
1138
+ async kill(id: number): Promise<void> {
1139
+ try {
1140
+ await this.taskServer.kill(id);
1141
+ } catch (error) {
1142
+ this.logger.error(`Error killing task '${id}': ${error}`);
1143
+ this.messageService.error(`Error killing task '${id}': ${error}`);
1144
+ return;
1145
+ }
1146
+ this.logger.debug(`Task killed. Task id: ${id}`);
1147
+ }
1148
+
1149
+ async isBackgroundTaskEnded(id: number): Promise<boolean | undefined> {
1150
+ const completedTask = this.runningTasks.get(id);
1151
+ return completedTask && completedTask.isBackgroundTaskEnded!.promise;
1152
+ }
1153
+
1154
+ async getExitCode(id: number): Promise<number | undefined> {
1155
+ const completedTask = this.runningTasks.get(id);
1156
+ return completedTask && completedTask.exitCode.promise;
1157
+ }
1158
+
1159
+ async getTerminateSignal(id: number): Promise<string | undefined> {
1160
+ const completedTask = this.runningTasks.get(id);
1161
+ return completedTask && completedTask.terminateSignal.promise;
1162
+ }
1163
+ }