Make gulp auto detection multi folder aware

This commit is contained in:
Dirk Baeumer 2017-09-15 13:18:01 +02:00
parent 867e521341
commit 575efe5a5d
2 changed files with 242 additions and 108 deletions

View file

@ -31,6 +31,7 @@
"title": "Gulp",
"properties": {
"gulp.autoDetect": {
"scope": "resource",
"type": "string",
"enum": [
"off",

View file

@ -13,49 +13,6 @@ import * as nls from 'vscode-nls';
const localize = nls.config(process.env.VSCODE_NLS_CONFIG)();
type AutoDetect = 'on' | 'off';
let taskProvider: vscode.Disposable | undefined;
export function activate(_context: vscode.ExtensionContext): void {
let workspaceRoot = vscode.workspace.rootPath;
if (!workspaceRoot) {
return;
}
let pattern = path.join(workspaceRoot, 'gulpfile{.babel.js,.js}');
let gulpPromise: Thenable<vscode.Task[]> | undefined = undefined;
let fileWatcher = vscode.workspace.createFileSystemWatcher(pattern);
fileWatcher.onDidChange(() => gulpPromise = undefined);
fileWatcher.onDidCreate(() => gulpPromise = undefined);
fileWatcher.onDidDelete(() => gulpPromise = undefined);
function onConfigurationChanged() {
let autoDetect = vscode.workspace.getConfiguration('gulp').get<AutoDetect>('autoDetect');
if (taskProvider && autoDetect === 'off') {
gulpPromise = undefined;
taskProvider.dispose();
taskProvider = undefined;
} else if (!taskProvider && autoDetect === 'on') {
taskProvider = vscode.workspace.registerTaskProvider('gulp', {
provideTasks: () => {
if (!gulpPromise) {
gulpPromise = getGulpTasks();
}
return gulpPromise;
},
resolveTask(_task: vscode.Task): vscode.Task | undefined {
return undefined;
}
});
}
}
vscode.workspace.onDidChangeConfiguration(onConfigurationChanged);
onConfigurationChanged();
}
export function deactivate(): void {
if (taskProvider) {
taskProvider.dispose();
}
}
function exists(file: string): Promise<boolean> {
return new Promise<boolean>((resolve, _reject) => {
@ -76,19 +33,6 @@ function exec(command: string, options: cp.ExecOptions): Promise<{ stdout: strin
});
}
let _channel: vscode.OutputChannel;
function getOutputChannel(): vscode.OutputChannel {
if (!_channel) {
_channel = vscode.window.createOutputChannel('Gulp Auto Detection');
}
return _channel;
}
interface GulpTaskDefinition extends vscode.TaskDefinition {
task: string;
file?: string;
}
const buildNames: string[] = ['build', 'compile', 'watch'];
function isBuildTask(name: string): boolean {
for (let buildName of buildNames) {
@ -109,69 +53,258 @@ function isTestTask(name: string): boolean {
return false;
}
async function getGulpTasks(): Promise<vscode.Task[]> {
let workspaceRoot = vscode.workspace.rootPath;
let emptyTasks: vscode.Task[] = [];
if (!workspaceRoot) {
return emptyTasks;
let _channel: vscode.OutputChannel;
function getOutputChannel(): vscode.OutputChannel {
if (!_channel) {
_channel = vscode.window.createOutputChannel('Gulp Auto Detection');
}
let gulpfile = path.join(workspaceRoot, 'gulpfile.js');
if (!await exists(gulpfile)) {
gulpfile = path.join(workspaceRoot, 'gulpfile.babel.js');
if (! await exists(gulpfile)) {
return _channel;
}
interface GulpTaskDefinition extends vscode.TaskDefinition {
task: string;
file?: string;
}
class FolderDetector {
private fileWatcher: vscode.FileSystemWatcher;
private promise: Thenable<vscode.Task[]> | undefined;
constructor(private _workspaceFolder: vscode.WorkspaceFolder) {
}
public get workspaceFolder(): vscode.WorkspaceFolder {
return this._workspaceFolder;
}
public isEnabled(): boolean {
return vscode.workspace.getConfiguration('gulp', this._workspaceFolder.uri).get<AutoDetect>('autoDetect') === 'on';
}
public start(): void {
let pattern = path.join(this._workspaceFolder.uri.fsPath, 'gulpfile{.babel.js,.js}');
this.fileWatcher = vscode.workspace.createFileSystemWatcher(pattern);
this.fileWatcher.onDidChange(() => this.promise = undefined);
this.fileWatcher.onDidCreate(() => this.promise = undefined);
this.fileWatcher.onDidDelete(() => this.promise = undefined);
}
public async getTasks(): Promise<vscode.Task[]> {
if (!this.promise) {
this.promise = this.computeTasks();
}
return this.promise;
}
private async computeTasks(): Promise<vscode.Task[]> {
let rootPath = this._workspaceFolder.uri.scheme === 'file' ? this._workspaceFolder.uri.fsPath : undefined;
let emptyTasks: vscode.Task[] = [];
if (!rootPath) {
return emptyTasks;
}
let gulpfile = path.join(rootPath, 'gulpfile.js');
if (!await exists(gulpfile)) {
gulpfile = path.join(rootPath, 'gulpfile.babel.js');
if (! await exists(gulpfile)) {
return emptyTasks;
}
}
let gulpCommand: string;
let platform = process.platform;
if (platform === 'win32' && await exists(path.join(rootPath!, 'node_modules', '.bin', 'gulp.cmd'))) {
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`;
try {
let { stdout, stderr } = await exec(commandLine, { cwd: rootPath });
if (stderr && stderr.length > 0) {
getOutputChannel().appendLine(stderr);
getOutputChannel().show(true);
}
let result: vscode.Task[] = [];
if (stdout) {
let lines = stdout.split(/\r{0,1}\n/);
for (let line of lines) {
if (line.length === 0) {
continue;
}
let kind: GulpTaskDefinition = {
type: 'gulp',
task: line
};
let task = new vscode.Task(kind, this.workspaceFolder, line, 'gulp', new vscode.ShellExecution(`${gulpCommand} ${line}`));
result.push(task);
let lowerCaseLine = line.toLowerCase();
if (isBuildTask(lowerCaseLine)) {
task.group = vscode.TaskGroup.Build;
} else if (isTestTask(lowerCaseLine)) {
task.group = vscode.TaskGroup.Test;
}
}
}
return result;
} catch (err) {
let channel = getOutputChannel();
if (err.stderr) {
channel.appendLine(err.stderr);
}
if (err.stdout) {
channel.appendLine(err.stdout);
}
channel.appendLine(localize('execFailed', 'Auto detecting gulp failed with error: {0}', err.error ? err.error.toString() : 'unknown'));
channel.show(true);
return emptyTasks;
}
}
let gulpCommand: string;
let platform = process.platform;
if (platform === 'win32' && await exists(path.join(workspaceRoot!, 'node_modules', '.bin', 'gulp.cmd'))) {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp.cmd');
} else if ((platform === 'linux' || platform === 'darwin') && await exists(path.join(workspaceRoot!, 'node_modules', '.bin', 'gulp'))) {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp');
} else {
gulpCommand = 'gulp';
public dispose() {
this.promise = undefined;
if (this.fileWatcher) {
this.fileWatcher.dispose();
}
}
}
class TaskDetector {
private taskProvider: vscode.Disposable | undefined;
private detectors: Map<string, FolderDetector> = new Map();
private promise: Promise<vscode.Task[]> | undefined;
constructor() {
}
let commandLine = `${gulpCommand} --tasks-simple --no-color`;
try {
let { stdout, stderr } = await exec(commandLine, { cwd: workspaceRoot });
if (stderr && stderr.length > 0) {
getOutputChannel().appendLine(stderr);
getOutputChannel().show(true);
public start(): void {
let folders = vscode.workspace.workspaceFolders;
if (folders) {
this.updateWorkspaceFolders(folders, []);
}
let result: vscode.Task[] = [];
if (stdout) {
let lines = stdout.split(/\r{0,1}\n/);
for (let line of lines) {
if (line.length === 0) {
continue;
}
let kind: GulpTaskDefinition = {
type: 'gulp',
task: line
};
let task = new vscode.Task(kind, line, 'gulp', new vscode.ShellExecution(`${gulpCommand} ${line}`));
result.push(task);
let lowerCaseLine = line.toLowerCase();
if (isBuildTask(lowerCaseLine)) {
task.group = vscode.TaskGroup.Build;
} else if (isTestTask(lowerCaseLine)) {
task.group = vscode.TaskGroup.Test;
vscode.workspace.onDidChangeWorkspaceFolders((event) => this.updateWorkspaceFolders(event.added, event.removed));
vscode.workspace.onDidChangeConfiguration(this.updateConfiguration, this);
}
public dispose(): void {
if (this.taskProvider) {
this.taskProvider.dispose();
this.taskProvider = undefined;
}
this.detectors.clear();
this.promise = undefined;
}
private updateWorkspaceFolders(added: vscode.WorkspaceFolder[], removed: vscode.WorkspaceFolder[]): void {
let changed = false;
for (let remove of removed) {
let detector = this.detectors.get(remove.uri.toString());
if (detector) {
changed = true;
detector.dispose();
this.detectors.delete(remove.uri.toString());
}
}
for (let add of added) {
let detector = new FolderDetector(add);
if (detector.isEnabled()) {
changed = true;
this.detectors.set(add.uri.toString(), detector);
detector.start();
}
}
if (changed) {
this.promise = undefined;
}
this.updateProvider();
}
private updateConfiguration(): void {
let changed = false;
for (let detector of this.detectors.values()) {
if (!detector.isEnabled()) {
changed = true;
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);
if (detector.isEnabled()) {
changed = true;
this.detectors.set(folder.uri.toString(), detector);
detector.start();
}
}
}
}
return result;
} catch (err) {
let channel = getOutputChannel();
if (err.stderr) {
channel.appendLine(err.stderr);
if (changed) {
this.promise = undefined;
}
if (err.stdout) {
channel.appendLine(err.stdout);
}
channel.appendLine(localize('execFailed', 'Auto detecting gulp failed with error: {0}', err.error ? err.error.toString() : 'unknown'));
channel.show(true);
return emptyTasks;
this.updateProvider();
}
private updateProvider(): void {
if (!this.taskProvider && this.detectors.size > 0) {
this.taskProvider = vscode.workspace.registerTaskProvider('gulp', {
provideTasks: () => {
return this.getTasks();
},
resolveTask(_task: vscode.Task): vscode.Task | undefined {
return undefined;
}
});
}
else if (this.taskProvider && this.detectors.size === 0) {
this.taskProvider.dispose();
this.taskProvider = undefined;
this.promise = undefined;
}
}
public getTasks(): Promise<vscode.Task[]> {
if (!this.promise) {
this.promise = this.computeTasks();
}
return this.promise;
}
private computeTasks(): Promise<vscode.Task[]> {
if (this.detectors.size === 0) {
return Promise.resolve([]);
} else if (this.detectors.size === 1) {
return this.detectors.values().next().value.getTasks();
} else {
let promises: Promise<vscode.Task[]>[] = [];
for (let detector of this.detectors.values()) {
promises.push(detector.getTasks().then((value) => value, () => []));
}
return Promise.all(promises).then((values) => {
let result: vscode.Task[] = [];
for (let tasks of values) {
if (tasks && tasks.length > 0) {
result.push(...tasks);
}
}
return result;
});
}
}
}
let detector: TaskDetector;
export function activate(_context: vscode.ExtensionContext): void {
detector = new TaskDetector();
detector.start();
}
export function deactivate(): void {
detector.dispose();
}