Skip to content

Commit

Permalink
Adding support for TaskProvider.resolveTask (#71027)
Browse files Browse the repository at this point in the history
* Adding support for TaskProvider.resolveTask.

* Reorganize task grouping and resolution async code for readability.

* Made small changes and implmented resolveTask for gulp
  • Loading branch information
joelday authored and alexr00 committed Jul 3, 2019
1 parent 9b28638 commit b6089b1
Show file tree
Hide file tree
Showing 9 changed files with 197 additions and 62 deletions.
107 changes: 74 additions & 33 deletions extensions/gulp/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,24 @@ function showError() {
});
}

async function findGulpCommand(rootPath: string): Promise<string> {
let gulpCommand: string;
let platform = process.platform;
if (platform === 'win32' && await exists(path.join(rootPath, 'node_modules', '.bin', 'gulp.cmd'))) {
const globalGulp = path.join(process.env.APPDATA ? process.env.APPDATA : '', 'npm', 'gulp.cmd');
if (await exists(globalGulp)) {
gulpCommand = '"' + globalGulp + '"';
} else {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp.cmd');
}
} else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(rootPath, 'node_modules', '.bin', 'gulp'))) {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp');
} else {
gulpCommand = 'gulp';
}
return gulpCommand;
}

interface GulpTaskDefinition extends vscode.TaskDefinition {
task: string;
file?: string;
Expand All @@ -77,7 +95,9 @@ class FolderDetector {
private fileWatcher: vscode.FileSystemWatcher | undefined;
private promise: Thenable<vscode.Task[]> | undefined;

constructor(private _workspaceFolder: vscode.WorkspaceFolder) {
constructor(
private _workspaceFolder: vscode.WorkspaceFolder,
private _gulpCommand: Promise<string>) {
}

public get workspaceFolder(): vscode.WorkspaceFolder {
Expand All @@ -97,10 +117,28 @@ class FolderDetector {
}

public async getTasks(): Promise<vscode.Task[]> {
if (!this.promise) {
this.promise = this.computeTasks();
if (this.isEnabled()) {
if (!this.promise) {
this.promise = this.computeTasks();
}
return this.promise;
} else {
return [];
}
}

public async getTask(_task: vscode.Task): Promise<vscode.Task | undefined> {
const gulpTask = (<any>_task.definition).task;
if (gulpTask) {
let kind: GulpTaskDefinition = {
type: 'gulp',
task: gulpTask
};
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
let task = new vscode.Task(kind, this.workspaceFolder, gulpTask, 'gulp', new vscode.ShellExecution(await this._gulpCommand, [gulpTask], options));
return task;
}
return this.promise;
return undefined;
}

private async computeTasks(): Promise<vscode.Task[]> {
Expand All @@ -117,22 +155,7 @@ class FolderDetector {
}
}

let gulpCommand: string;
let platform = process.platform;
if (platform === 'win32' && await exists(path.join(rootPath!, 'node_modules', '.bin', 'gulp.cmd'))) {
const globalGulp = path.join(process.env.APPDATA ? process.env.APPDATA : '', 'npm', 'gulp.cmd');
if (await exists(globalGulp)) {
gulpCommand = '"' + globalGulp + '"';
} else {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp.cmd');
}
} else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(rootPath!, 'node_modules', '.bin', 'gulp'))) {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp');
} else {
gulpCommand = 'gulp';
}

let commandLine = `${gulpCommand} --tasks-simple --no-color`;
let commandLine = `${await this._gulpCommand} --tasks-simple --no-color`;
try {
let { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
if (stderr && stderr.length > 0) {
Expand All @@ -151,7 +174,7 @@ class FolderDetector {
task: line
};
let options: vscode.ShellExecutionOptions = { cwd: this.workspaceFolder.uri.fsPath };
let task = new vscode.Task(kind, this.workspaceFolder, line, 'gulp', new vscode.ShellExecution(gulpCommand, [line], options));
let task = new vscode.Task(kind, this.workspaceFolder, line, 'gulp', new vscode.ShellExecution(await this._gulpCommand, [line], options));
result.push(task);
let lowerCaseLine = line.toLowerCase();
if (isBuildTask(lowerCaseLine)) {
Expand Down Expand Up @@ -218,9 +241,9 @@ class TaskDetector {
}
}
for (let add of added) {
let detector = new FolderDetector(add);
let detector = new FolderDetector(add, findGulpCommand(add.uri.fsPath));
this.detectors.set(add.uri.toString(), detector);
if (detector.isEnabled()) {
this.detectors.set(add.uri.toString(), detector);
detector.start();
}
}
Expand All @@ -229,18 +252,16 @@ class TaskDetector {

private updateConfiguration(): void {
for (let detector of this.detectors.values()) {
if (!detector.isEnabled()) {
detector.dispose();
this.detectors.delete(detector.workspaceFolder.uri.toString());
}
detector.dispose();
this.detectors.delete(detector.workspaceFolder.uri.toString());
}
let folders = vscode.workspace.workspaceFolders;
if (folders) {
for (let folder of folders) {
if (!this.detectors.has(folder.uri.toString())) {
let detector = new FolderDetector(folder);
let detector = new FolderDetector(folder, findGulpCommand(folder.uri.fsPath));
this.detectors.set(folder.uri.toString(), detector);
if (detector.isEnabled()) {
this.detectors.set(folder.uri.toString(), detector);
detector.start();
}
}
Expand All @@ -251,12 +272,13 @@ class TaskDetector {

private updateProvider(): void {
if (!this.taskProvider && this.detectors.size > 0) {
const thisCapture = this;
this.taskProvider = vscode.workspace.registerTaskProvider('gulp', {
provideTasks: () => {
return this.getTasks();
provideTasks(): Promise<vscode.Task[]> {
return thisCapture.getTasks();
},
resolveTask(_task: vscode.Task): vscode.Task | undefined {
return undefined;
resolveTask(_task: vscode.Task): Promise<vscode.Task | undefined> {
return thisCapture.getTask(_task);
}
});
}
Expand Down Expand Up @@ -291,6 +313,25 @@ class TaskDetector {
});
}
}

public async getTask(task: vscode.Task): Promise<vscode.Task | undefined> {
if (this.detectors.size === 0) {
return undefined;
} else if (this.detectors.size === 1) {
return this.detectors.values().next().value.getTask(task);
} else {
if ((task.scope === vscode.TaskScope.Workspace) || (task.scope === vscode.TaskScope.Global)) {
// Not supported, we don't have enough info to create the task.
return undefined;
} else if (task.scope) {
const detector = this.detectors.get(task.scope.uri.toString());
if (detector) {
return detector.getTask(task);
}
}
return undefined;
}
}
}

let detector: TaskDetector;
Expand Down
29 changes: 22 additions & 7 deletions src/vs/workbench/api/browser/mainThreadTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { IDisposable } from 'vs/base/common/lifecycle';
import { IWorkspaceContextService, IWorkspaceFolder } from 'vs/platform/workspace/common/workspace';

import {
ContributedTask, KeyedTaskIdentifier, TaskExecution, Task, TaskEvent, TaskEventKind,
ContributedTask, ConfiguringTask, KeyedTaskIdentifier, TaskExecution, Task, TaskEvent, TaskEventKind,
PresentationOptions, CommandOptions, CommandConfiguration, RuntimeType, CustomTask, TaskScope, TaskSource,
TaskSourceKind, ExtensionTaskSource, RunOptions, TaskSet, TaskDefinition
} from 'vs/workbench/contrib/tasks/common/tasks';
Expand Down Expand Up @@ -304,8 +304,8 @@ namespace TaskHandleDTO {
}

namespace TaskDTO {
export function from(task: Task): TaskDTO | undefined {
if (task === undefined || task === null || (!CustomTask.is(task) && !ContributedTask.is(task))) {
export function from(task: Task | ConfiguringTask): TaskDTO | undefined {
if (task === undefined || task === null || (!CustomTask.is(task) && !ContributedTask.is(task) && !ConfiguringTask.is(task))) {
return undefined;
}
const result: TaskDTO = {
Expand All @@ -314,7 +314,7 @@ namespace TaskDTO {
definition: TaskDefinitionDTO.from(task.getDefinition()),
source: TaskSourceDTO.from(task._source),
execution: undefined,
presentationOptions: task.command ? TaskPresentationOptionsDTO.from(task.command.presentation) : undefined,
presentationOptions: !ConfiguringTask.is(task) && task.command ? TaskPresentationOptionsDTO.from(task.command.presentation) : undefined,
isBackground: task.configurationProperties.isBackground,
problemMatchers: [],
hasDefinedMatchers: ContributedTask.is(task) ? task.hasDefinedMatchers : false,
Expand All @@ -323,7 +323,7 @@ namespace TaskDTO {
if (task.configurationProperties.group) {
result.group = task.configurationProperties.group;
}
if (task.command) {
if (!ConfiguringTask.is(task) && task.command) {
if (task.command.runtime === RuntimeType.Process) {
result.execution = ProcessExecutionDTO.from(task.command);
} else if (task.command.runtime === RuntimeType.Shell) {
Expand Down Expand Up @@ -442,7 +442,7 @@ export class MainThreadTask implements MainThreadTaskShape {
});
}

public $registerTaskProvider(handle: number): Promise<void> {
public $registerTaskProvider(handle: number, type: string): Promise<void> {
const provider: ITaskProvider = {
provideTasks: (validTypes: IStringDictionary<boolean>) => {
return Promise.resolve(this._proxy.$provideTasks(handle, validTypes)).then((value) => {
Expand All @@ -460,9 +460,24 @@ export class MainThreadTask implements MainThreadTaskShape {
extension: value.extension
} as TaskSet;
});
},
resolveTask: (task: ConfiguringTask) => {
const dto = TaskDTO.from(task);

if (dto) {
dto.name = ((dto.name === undefined) ? '' : dto.name); // Using an empty name causes the name to default to the one given by the provider.
return Promise.resolve(this._proxy.$resolveTask(handle, dto)).then(resolvedTask => {
if (resolvedTask) {
return TaskDTO.to(resolvedTask, this._workspaceContextServer, true);
}

return undefined;
});
}
return Promise.resolve<ContributedTask | undefined>(undefined);
}
};
const disposable = this._taskService.registerTaskProvider(provider);
const disposable = this._taskService.registerTaskProvider(provider, type);
this._providers.set(handle, { disposable, provider });
return Promise.resolve(undefined);
}
Expand Down
3 changes: 2 additions & 1 deletion src/vs/workbench/api/common/extHost.protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -635,7 +635,7 @@ export interface MainThreadSearchShape extends IDisposable {

export interface MainThreadTaskShape extends IDisposable {
$createTaskId(task: tasks.TaskDTO): Promise<string>;
$registerTaskProvider(handle: number): Promise<void>;
$registerTaskProvider(handle: number, type: string): Promise<void>;
$unregisterTaskProvider(handle: number): Promise<void>;
$fetchTasks(filter?: tasks.TaskFilterDTO): Promise<tasks.TaskDTO[]>;
$executeTask(task: tasks.TaskHandleDTO | tasks.TaskDTO): Promise<tasks.TaskExecutionDTO>;
Expand Down Expand Up @@ -1183,6 +1183,7 @@ export interface ExtHostSCMShape {

export interface ExtHostTaskShape {
$provideTasks(handle: number, validTypes: { [key: string]: boolean; }): Thenable<tasks.TaskSetDTO>;
$resolveTask(handle: number, taskDTO: tasks.TaskDTO): Thenable<tasks.TaskDTO | undefined>;
$onDidStartTask(execution: tasks.TaskExecutionDTO, terminalId: number): void;
$onDidStartTaskProcess(value: tasks.TaskProcessStartedDTO): void;
$onDidEndTaskProcess(value: tasks.TaskProcessEndedDTO): void;
Expand Down
4 changes: 2 additions & 2 deletions src/vs/workbench/api/node/extHost.api.impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -675,7 +675,7 @@ export function createApiFactory(
return extHostDocumentContentProviders.registerTextDocumentContentProvider(scheme, provider);
},
registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
return extHostTask.registerTaskProvider(extension, provider);
return extHostTask.registerTaskProvider(extension, type, provider);
},
registerFileSystemProvider(scheme, provider, options) {
return extHostFileSystem.registerFileSystemProvider(scheme, provider, options);
Expand Down Expand Up @@ -776,7 +776,7 @@ export function createApiFactory(

const tasks: typeof vscode.tasks = {
registerTaskProvider: (type: string, provider: vscode.TaskProvider) => {
return extHostTask.registerTaskProvider(extension, provider);
return extHostTask.registerTaskProvider(extension, type, provider);
},
fetchTasks: (filter?: vscode.TaskFilter): Thenable<vscode.Task[]> => {
return extHostTask.fetchTasks(filter);
Expand Down
57 changes: 45 additions & 12 deletions src/vs/workbench/api/node/extHostTask.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,7 @@ namespace TaskExecutionDTO {
}

interface HandlerData {
type: string;
provider: vscode.TaskProvider;
extension: IExtensionDescription;
}
Expand Down Expand Up @@ -492,13 +493,13 @@ export class ExtHostTask implements ExtHostTaskShape {
this._activeCustomExecutions = new Map<string, CustomExecutionData>();
}

public registerTaskProvider(extension: IExtensionDescription, provider: vscode.TaskProvider): vscode.Disposable {
public registerTaskProvider(extension: IExtensionDescription, type: string, provider: vscode.TaskProvider): vscode.Disposable {
if (!provider) {
return new types.Disposable(() => { });
}
const handle = this.nextHandle();
this._handlers.set(handle, { provider, extension });
this._proxy.$registerTaskProvider(handle);
this._handlers.set(handle, { type, provider, extension });
this._proxy.$registerTaskProvider(handle, type);
return new types.Disposable(() => {
this._handlers.delete(handle);
this._proxy.$unregisterTaskProvider(handle);
Expand Down Expand Up @@ -652,15 +653,10 @@ export class ExtHostTask implements ExtHostTaskShape {
taskDTOs.push(taskDTO);

if (CustomExecutionDTO.is(taskDTO.execution)) {
taskIdPromises.push(new Promise((resolve) => {
// The ID is calculated on the main thread task side, so, let's call into it here.
// We need the task id's pre-computed for custom task executions because when OnDidStartTask
// is invoked, we have to be able to map it back to our data.
this._proxy.$createTaskId(taskDTO).then((taskId) => {
this._providedCustomExecutions.set(taskId, new CustomExecutionData(<vscode.CustomExecution>(<vscode.Task2>task).execution2, this._terminalService));
resolve();
});
}));
// The ID is calculated on the main thread task side, so, let's call into it here.
// We need the task id's pre-computed for custom task executions because when OnDidStartTask
// is invoked, we have to be able to map it back to our data.
taskIdPromises.push(this.addCustomExecution(taskDTO, <vscode.Task2>task));
}
}
}
Expand All @@ -680,6 +676,38 @@ export class ExtHostTask implements ExtHostTaskShape {
});
}

public async $resolveTask(handle: number, taskDTO: TaskDTO): Promise<TaskDTO | undefined> {
const handler = this._handlers.get(handle);
if (!handler) {
return Promise.reject(new Error('no handler found'));
}

if (taskDTO.definition.type !== handler.type) {
throw new Error(`Unexpected: Task of type [${taskDTO.definition.type}] cannot be resolved by provider of type [${handler.type}].`);
}

const task = await TaskDTO.to(taskDTO, this._workspaceProvider);
if (!task) {
throw new Error('Unexpected: Task cannot be resolved.');
}

const resolvedTask = await handler.provider.resolveTask(task, CancellationToken.None);
if (!resolvedTask) {
return;
}

const resolvedTaskDTO: TaskDTO | undefined = TaskDTO.from(resolvedTask, handler.extension);
if (!resolvedTaskDTO) {
throw new Error('Unexpected: Task cannot be resolved.');
}

if (CustomExecutionDTO.is(resolvedTaskDTO.execution)) {
await this.addCustomExecution(taskDTO, <vscode.Task2>task);
}

return resolvedTaskDTO;
}

public async $resolveVariables(uriComponents: UriComponents, toResolve: { process?: { name: string; cwd?: string; path?: string }, variables: string[] }): Promise<{ process?: string, variables: { [key: string]: string; } }> {
const configProvider = await this._configurationService.getConfigProvider();
const uri: URI = URI.revive(uriComponents);
Expand Down Expand Up @@ -725,6 +753,11 @@ export class ExtHostTask implements ExtHostTaskShape {
return this._handleCounter++;
}

private async addCustomExecution(taskDTO: TaskDTO, task: vscode.Task2): Promise<void> {
const taskId = await this._proxy.$createTaskId(taskDTO);
this._providedCustomExecutions.set(taskId, new CustomExecutionData(<vscode.CustomExecution>(<vscode.Task2>task).execution2, this._terminalService));
}

private async getTaskExecution(execution: TaskExecutionDTO | string, task?: vscode.Task): Promise<TaskExecutionImpl> {
if (typeof execution === 'string') {
const taskExecution = this._taskExecutions.get(execution);
Expand Down
Loading

0 comments on commit b6089b1

Please sign in to comment.