diff --git a/CHANGELOG.md b/CHANGELOG.md index b757fb6..5afe073 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Change Log +## 0.3.0 + +- Made dynamic discovery of subcommands for setuptools and django optional (and off by default) + ## 0.2.0 - Additional args support diff --git a/README.md b/README.md index e38415c..ca97b15 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,11 @@ It will then make available the following commands as tasks: ![](doc/static/flit-task-discovery.png) +## Configuration + +- `"pythonTaskProvider.runSetupToolsToDiscoverOptions"` default: `false`, "Run setup.py --help-commands to discover extra commands. Caution, do not enable this for untrusted projects." +- `"pythonTaskProvider.runDjangoToDiscoverOptions"` default: `false`, "Run manage.py --help to discover extra commands. Caution, do not enable this for untrusted projects." + ## Calling from tasks.json If you want to save the task and recall it, add it to `tasks.json`: diff --git a/package.json b/package.json index 40f1b0a..d2aa3c8 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "python-task-provider", "displayName": "Python task provider", "description": "Automatically provide tasks for setuptools and django to the Run Task/tasks.json system.", - "version": "0.2.0", + "version": "0.3.0", "engines": { "vscode": "^1.52.0" }, @@ -20,6 +20,21 @@ ], "main": "./out/extension.js", "contributes": { + "configuration": { + "title": "PythonTaskProvider", + "properties": { + "pythonTaskProvider.runSetupToolsToDiscoverOptions": { + "type": "boolean", + "default": false, + "description": "Run setup.py --help-commands to discover extra commands. Caution, do not enable this for untrusted projects." + }, + "pythonTaskProvider.runDjangoToDiscoverOptions": { + "type": "boolean", + "default": false, + "description": "Run manage.py --help to discover extra commands. Caution, do not enable this for untrusted projects." + } + } + }, "taskDefinitions": [ { "type": "setuptools", diff --git a/src/djangoTaskProvider.ts b/src/djangoTaskProvider.ts index b097577..20271ca 100644 --- a/src/djangoTaskProvider.ts +++ b/src/djangoTaskProvider.ts @@ -1,169 +1,248 @@ -import * as path from 'path'; -import * as fs from 'fs'; -import * as cp from 'child_process'; -import * as vscode from 'vscode'; +import * as path from "path"; +import * as fs from "fs"; +import * as cp from "child_process"; +import * as vscode from "vscode"; export class DjangoTaskProvider implements vscode.TaskProvider { - static DjangoType = 'django'; - private djangoPromise: Thenable | undefined = undefined; + static DjangoType = "django"; + private djangoPromise: Thenable | undefined = undefined; - constructor() { - if (!vscode.workspace.workspaceFolders) { - return; - } - vscode.workspace.workspaceFolders.forEach(workspaceRoot => { - const pattern = path.join(workspaceRoot.uri.fsPath, 'manage.py'); - const fileWatcher = vscode.workspace.createFileSystemWatcher(pattern); - fileWatcher.onDidChange(() => this.djangoPromise = undefined); - fileWatcher.onDidCreate(() => this.djangoPromise = undefined); - fileWatcher.onDidDelete(() => this.djangoPromise = undefined); - }); - } + constructor() { + if (!vscode.workspace.workspaceFolders) { + return; + } + vscode.workspace.workspaceFolders.forEach((workspaceRoot) => { + const pattern = path.join(workspaceRoot.uri.fsPath, "manage.py"); + const fileWatcher = vscode.workspace.createFileSystemWatcher(pattern); + fileWatcher.onDidChange(() => (this.djangoPromise = undefined)); + fileWatcher.onDidCreate(() => (this.djangoPromise = undefined)); + fileWatcher.onDidDelete(() => (this.djangoPromise = undefined)); + }); + } - public provideTasks(): Thenable | undefined { - if (!this.djangoPromise) { - this.djangoPromise = getDjangoTasks(); - } - return this.djangoPromise; - } + public provideTasks(): Thenable | undefined { + if (!this.djangoPromise) { + this.djangoPromise = getDjangoTasks(); + } + return this.djangoPromise; + } - public resolveTask(_task: vscode.Task): vscode.Task | undefined { - const task = _task.definition.task; - var pythonPath = vscode.workspace.getConfiguration('python').get('pythonPath'); - if (!pythonPath){ - pythonPath = 'python'; - } - if (task) { - // resolveTask requires that the same definition object be used. - const definition: DjangoTaskDefinition = _task.definition; - const pythonFile = definition.file ? definition.file : 'manage.py'; - const args = definition.args ? definition.args.join(' ') : ''; - return new vscode.Task(definition, _task.scope ?? vscode.TaskScope.Workspace, definition.task, 'django', new vscode.ShellExecution(`${pythonPath} ${pythonFile} ${definition.task} ${args}`)); - } - return undefined; - } + public resolveTask(_task: vscode.Task): vscode.Task | undefined { + const task = _task.definition.task; + var pythonPath = vscode.workspace + .getConfiguration("python") + .get("pythonPath"); + if (!pythonPath) { + pythonPath = "python"; + } + if (task) { + // resolveTask requires that the same definition object be used. + const definition: DjangoTaskDefinition = _task.definition; + const pythonFile = definition.file ? definition.file : "manage.py"; + const args = definition.args ? definition.args.join(" ") : ""; + return new vscode.Task( + definition, + _task.scope ?? vscode.TaskScope.Workspace, + definition.task, + "django", + new vscode.ShellExecution( + `${pythonPath} ${pythonFile} ${definition.task} ${args}` + ) + ); + } + return undefined; + } } function exists(file: string): Promise { - return new Promise((resolve, _reject) => { - fs.exists(file, (value) => { - resolve(value); - }); - }); + return new Promise((resolve, _reject) => { + fs.exists(file, (value) => { + resolve(value); + }); + }); } -function exec(command: string, options: cp.ExecOptions): Promise<{ stdout: string; stderr: string }> { - return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => { - cp.exec(command, options, (error, stdout, stderr) => { - if (error) { - reject({ error, stdout, stderr }); - } - resolve({ stdout, stderr }); - }); - }); +function exec( + command: string, + options: cp.ExecOptions +): Promise<{ stdout: string; stderr: string }> { + return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => { + cp.exec(command, options, (error, stdout, stderr) => { + if (error) { + reject({ error, stdout, stderr }); + } + resolve({ stdout, stderr }); + }); + }); } let _channel: vscode.OutputChannel; function getOutputChannel(): vscode.OutputChannel { - if (!_channel) { - _channel = vscode.window.createOutputChannel('Django Auto Detection'); - } - return _channel; + if (!_channel) { + _channel = vscode.window.createOutputChannel("Django Auto Detection"); + } + return _channel; } interface DjangoTaskDefinition extends vscode.TaskDefinition { - /** - * The task name - */ - task: string; + /** + * The task name + */ + task: string; - /** - * The python file containing the task - */ - file?: string; + /** + * The python file containing the task + */ + file?: string; - /** - * Optional arguments to the task - */ - args?: string[]; + /** + * Optional arguments to the task + */ + args?: string[]; } function isBuildTask(name: string): boolean { - return false; + return false; } function isTestTask(name: string): boolean { - return false; + return false; +} + +function getBuiltinTasks(): Array { + return [ + "check", + "compilemessages", + "createcachetable", + "dbshell", + "diffsettings", + "dumpdata", + "flush", + "inspectdb", + "loaddata", + "makemessages", + "makemigrations", + "migrate", + "runserver", + "sendtestemail", + "shell", + "showmigrations", + "sqlflush", + "sqlsequencereset", + "squashmigrations", + "startapp", + "startproject", + "test", + "testserver", + ]; } async function getDjangoTasks(): Promise { - const workspaceFolders = vscode.workspace.workspaceFolders; - const result: vscode.Task[] = []; - if (!workspaceFolders || workspaceFolders.length === 0) { - return result; - } - for (const workspaceFolder of workspaceFolders) { - const folderString = workspaceFolder.uri.fsPath; - if (!folderString) { - continue; - } - const managePyFile = path.join(folderString, 'manage.py'); - if (!await exists(managePyFile)) { - continue; - } - var pythonPath = vscode.workspace.getConfiguration('python').get('pythonPath'); - if (!pythonPath){ - pythonPath = 'python'; + const workspaceFolders = vscode.workspace.workspaceFolders; + const result: vscode.Task[] = []; + if (!workspaceFolders || workspaceFolders.length === 0) { + return result; + } + for (const workspaceFolder of workspaceFolders) { + const folderString = workspaceFolder.uri.fsPath; + if (!folderString) { + continue; + } + const managePyFile = path.join(folderString, "manage.py"); + if (!(await exists(managePyFile))) { + continue; + } + var pythonPath = vscode.workspace + .getConfiguration("python") + .get("pythonPath"); + if (!pythonPath) { + pythonPath = "python"; + } + if ( + vscode.workspace + .getConfiguration("pythonTaskProvider") + .get("runDjangoToDiscoverOptions") + ) { + const commandLine = `${pythonPath} ${managePyFile} help`; + var isCommandList = false; + try { + const { stdout, stderr } = await exec(commandLine, { + cwd: folderString, + }); + if (stderr && stderr.length > 0) { + getOutputChannel().appendLine(stderr); + getOutputChannel().show(true); } - const commandLine = `${pythonPath} manage.py help`; - var isCommandList = false; - try { - const { stdout, stderr } = await exec(commandLine, { cwd: folderString }); - if (stderr && stderr.length > 0) { - getOutputChannel().appendLine(stderr); - getOutputChannel().show(true); - } - if (stdout) { - const lines = stdout.split(/\r{0,1}\n/); - for (const line of lines) { - if (line.length === 0) { - continue; - } - if (line.startsWith("Available subcommands:")) { - isCommandList = true; - continue; - } - if (isCommandList) { - const taskName = line.trim().split(" ")[0]; - if (taskName.startsWith("[")) { - continue; - } - const kind: DjangoTaskDefinition = { - type: 'django', - task: taskName - }; - const task = new vscode.Task(kind, workspaceFolder, taskName, 'django', new vscode.ShellExecution(`${pythonPath} manage.py ${taskName}`)); - result.push(task); - const lowerCaseLine = line.toLowerCase(); - if (isBuildTask(lowerCaseLine)) { - task.group = vscode.TaskGroup.Build; - } else if (isTestTask(lowerCaseLine)) { - task.group = vscode.TaskGroup.Test; - } - } - } - } - } catch (err) { - const channel = getOutputChannel(); - if (err.stderr) { - channel.appendLine(err.stderr); - } - if (err.stdout) { - channel.appendLine(err.stdout); - } - channel.appendLine('Auto detecting manage.py commands failed.'); - channel.show(true); - } - } - return result; -} \ No newline at end of file + if (stdout) { + const lines = stdout.split(/\r{0,1}\n/); + for (const line of lines) { + if (line.length === 0) { + continue; + } + if (line.startsWith("Available subcommands:")) { + isCommandList = true; + continue; + } + if (isCommandList) { + const taskName = line.trim().split(" ")[0]; + if (taskName.startsWith("[")) { + continue; + } + const kind: DjangoTaskDefinition = { + type: "django", + task: taskName, + }; + const task = new vscode.Task( + kind, + workspaceFolder, + taskName, + "django", + new vscode.ShellExecution(`${pythonPath} ${managePyFile} ${taskName}`) + ); + result.push(task); + const lowerCaseLine = line.toLowerCase(); + if (isBuildTask(lowerCaseLine)) { + task.group = vscode.TaskGroup.Build; + } else if (isTestTask(lowerCaseLine)) { + task.group = vscode.TaskGroup.Test; + } + } + } + } + } catch (err) { + const channel = getOutputChannel(); + if (err.stderr) { + channel.appendLine(err.stderr); + } + if (err.stdout) { + channel.appendLine(err.stdout); + } + channel.appendLine("Auto detecting manage.py commands failed."); + channel.show(true); + } + } else { + getBuiltinTasks().forEach((taskName) => { + const kind: DjangoTaskDefinition = { + type: "django", + task: taskName, + }; + const task = new vscode.Task( + kind, + workspaceFolder, + taskName, + "django", + new vscode.ShellExecution(`${pythonPath} ${managePyFile} ${taskName}`) + ); + result.push(task); + + if (taskName === "runserver") { + task.group = vscode.TaskGroup.Build; + } + if (taskName === "test") { + task.group = vscode.TaskGroup.Test; + } + }); + } + } + return result; +} diff --git a/src/setupToolsTaskProvider.ts b/src/setupToolsTaskProvider.ts index 6c3b152..ce49484 100644 --- a/src/setupToolsTaskProvider.ts +++ b/src/setupToolsTaskProvider.ts @@ -1,185 +1,247 @@ -import * as path from 'path'; -import * as fs from 'fs'; -import * as cp from 'child_process'; -import * as vscode from 'vscode'; +import * as path from "path"; +import * as fs from "fs"; +import * as cp from "child_process"; +import * as vscode from "vscode"; export class SetupToolsTaskProvider implements vscode.TaskProvider { - static SetupToolsType = 'setuptools'; - private setuptoolsPromise: Thenable | undefined = undefined; + static SetupToolsType = "setuptools"; + private setuptoolsPromise: Thenable | undefined = undefined; - constructor() { - if (!vscode.workspace.workspaceFolders) { - return; - } - vscode.workspace.workspaceFolders.forEach(workspaceRoot => { - const pattern = path.join(workspaceRoot.uri.fsPath, 'setup.py'); - const fileWatcher = vscode.workspace.createFileSystemWatcher(pattern); - fileWatcher.onDidChange(() => this.setuptoolsPromise = undefined); - fileWatcher.onDidCreate(() => this.setuptoolsPromise = undefined); - fileWatcher.onDidDelete(() => this.setuptoolsPromise = undefined); - }); - } + constructor() { + if (!vscode.workspace.workspaceFolders) { + return; + } + vscode.workspace.workspaceFolders.forEach((workspaceRoot) => { + const pattern = path.join(workspaceRoot.uri.fsPath, "setup.py"); + const fileWatcher = vscode.workspace.createFileSystemWatcher(pattern); + fileWatcher.onDidChange(() => (this.setuptoolsPromise = undefined)); + fileWatcher.onDidCreate(() => (this.setuptoolsPromise = undefined)); + fileWatcher.onDidDelete(() => (this.setuptoolsPromise = undefined)); + }); + } - public provideTasks(): Thenable | undefined { - if (!this.setuptoolsPromise) { - this.setuptoolsPromise = getSetupToolsTasks(); - } - return this.setuptoolsPromise; - } + public provideTasks(): Thenable | undefined { + if (!this.setuptoolsPromise) { + this.setuptoolsPromise = getSetupToolsTasks(); + } + return this.setuptoolsPromise; + } - public resolveTask(_task: vscode.Task): vscode.Task | undefined { - const task = _task.definition.task; - var pythonPath = vscode.workspace.getConfiguration('python').get('pythonPath'); - if (!pythonPath){ - pythonPath = 'python'; - } - if (task) { - // resolveTask requires that the same definition object be used. - const definition: SetupToolsTaskDefinition = _task.definition; - const pythonFile = definition.file ? definition.file : 'setup.py'; - const args = definition.args ? definition.args.join(' ') : ''; - return new vscode.Task(definition, _task.scope ?? vscode.TaskScope.Workspace, definition.task, 'setuptools', new vscode.ShellExecution(`${pythonPath} ${pythonFile} ${definition.task} ${args}`)); - } - return undefined; - } + public resolveTask(_task: vscode.Task): vscode.Task | undefined { + const task = _task.definition.task; + var pythonPath = vscode.workspace + .getConfiguration("python") + .get("pythonPath"); + if (!pythonPath) { + pythonPath = "python"; + } + if (task) { + // resolveTask requires that the same definition object be used. + const definition: SetupToolsTaskDefinition = _task.definition; + const pythonFile = definition.file ? definition.file : "setup.py"; + const args = definition.args ? definition.args.join(" ") : ""; + return new vscode.Task( + definition, + _task.scope ?? vscode.TaskScope.Workspace, + definition.task, + "setuptools", + new vscode.ShellExecution( + `${pythonPath} ${pythonFile} ${definition.task} ${args}` + ) + ); + } + return undefined; + } } function exists(file: string): Promise { - return new Promise((resolve, _reject) => { - fs.exists(file, (value) => { - resolve(value); - }); - }); + return new Promise((resolve, _reject) => { + fs.exists(file, (value) => { + resolve(value); + }); + }); } -function exec(command: string, options: cp.ExecOptions): Promise<{ stdout: string; stderr: string }> { - return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => { - cp.exec(command, options, (error, stdout, stderr) => { - if (error) { - reject({ error, stdout, stderr }); - } - resolve({ stdout, stderr }); - }); - }); +function exec( + command: string, + options: cp.ExecOptions +): Promise<{ stdout: string; stderr: string }> { + return new Promise<{ stdout: string; stderr: string }>((resolve, reject) => { + cp.exec(command, options, (error, stdout, stderr) => { + if (error) { + reject({ error, stdout, stderr }); + } + resolve({ stdout, stderr }); + }); + }); } let _channel: vscode.OutputChannel; function getOutputChannel(): vscode.OutputChannel { - if (!_channel) { - _channel = vscode.window.createOutputChannel('Setuptools Auto Detection'); - } - return _channel; + if (!_channel) { + _channel = vscode.window.createOutputChannel("Setuptools Auto Detection"); + } + return _channel; } interface SetupToolsTaskDefinition extends vscode.TaskDefinition { - /** - * The task name - */ - task: string; + /** + * The task name + */ + task: string; - /** - * The python file containing the task - */ - file?: string; + /** + * The python file containing the task + */ + file?: string; - /** - * Optional arguments to the task - */ - args?: string[]; + /** + * Optional arguments to the task + */ + args?: string[]; } -const buildNames: string[] = ['bdist', 'bdist_wheel', 'sdist', 'build']; +const buildNames: string[] = ["bdist", "bdist_wheel", "sdist", "build"]; function isBuildTask(name: string): boolean { - for (const buildName of buildNames) { - if (name.indexOf(buildName) !== -1) { - return true; - } - } - return false; + for (const buildName of buildNames) { + if (name.indexOf(buildName) !== -1) { + return true; + } + } + return false; } -const testNames: string[] = ['test']; +const testNames: string[] = ["test"]; function isTestTask(name: string): boolean { - for (const testName of testNames) { - if (name.indexOf(testName) !== -1) { - return true; - } - } - return false; + for (const testName of testNames) { + if (name.indexOf(testName) !== -1) { + return true; + } + } + return false; +} + +function getBuiltinTasks(): Array { + return [ + "build", + "sdist", + "test", + "bdist", + "bdist_wheel", + "clean", + "check", + "develop", + "install", + ]; } async function getSetupToolsTasks(): Promise { - const workspaceFolders = vscode.workspace.workspaceFolders; - const result: vscode.Task[] = []; - if (!workspaceFolders || workspaceFolders.length === 0) { - return result; - } - for (const workspaceFolder of workspaceFolders) { - const folderString = workspaceFolder.uri.fsPath; - if (!folderString) { - continue; - } - const setupPyFile = path.join(folderString, 'setup.py'); - if (!await exists(setupPyFile)) { - continue; - } - var pythonPath = vscode.workspace.getConfiguration('python').get('pythonPath'); - if (!pythonPath){ - pythonPath = 'python'; + const workspaceFolders = vscode.workspace.workspaceFolders; + const result: vscode.Task[] = []; + if (!workspaceFolders || workspaceFolders.length === 0) { + return result; + } + for (const workspaceFolder of workspaceFolders) { + const folderString = workspaceFolder.uri.fsPath; + if (!folderString) { + continue; + } + const setupPyFile = path.join(folderString, "setup.py"); + if (!(await exists(setupPyFile))) { + continue; + } + var pythonPath = vscode.workspace + .getConfiguration("python") + .get("pythonPath"); + if (!pythonPath) { + pythonPath = "python"; + } + if ( + vscode.workspace + .getConfiguration("pythonTaskProvider") + .get("runSetupToolsToDiscoverOptions") + ) { + const commandLine = `${pythonPath} ${setupPyFile} --help-commands`; + var isStandardCommands = false; + var isExtraCommands = false; + try { + const { stdout, stderr } = await exec(commandLine, { + cwd: folderString, + }); + if (stderr && stderr.length > 0) { + getOutputChannel().appendLine(stderr); + getOutputChannel().show(true); } - const commandLine = `${pythonPath} setup.py --help-commands`; - var isStandardCommands = false; - var isExtraCommands = false; - try { - const { stdout, stderr } = await exec(commandLine, { cwd: folderString }); - if (stderr && stderr.length > 0) { - getOutputChannel().appendLine(stderr); - getOutputChannel().show(true); - } - if (stdout) { - const lines = stdout.split(/\r{0,1}\n/); - for (const line of lines) { - if (line.length === 0) { - isStandardCommands = false; - isExtraCommands = false; - continue; - } - if (line.startsWith("Standard commands:")){ - isStandardCommands = true; - continue; - } - if (line.startsWith("Extra commands:")){ - isExtraCommands = true; - continue; - } - if (isStandardCommands || isExtraCommands){ - const taskName = line.trim().split(" ")[0]; - const kind: SetupToolsTaskDefinition = { - type: 'setuptools', - task: taskName - }; - const task = new vscode.Task(kind, workspaceFolder, taskName, 'setuptools', new vscode.ShellExecution(`${pythonPath} setup.py ${taskName}`)); - result.push(task); - const lowerCaseLine = line.toLowerCase(); - if (isBuildTask(lowerCaseLine)) { - task.group = vscode.TaskGroup.Build; - } else if (isTestTask(lowerCaseLine)) { - task.group = vscode.TaskGroup.Test; - } - } - } - } - } catch (err) { - const channel = getOutputChannel(); - if (err.stderr) { - channel.appendLine(err.stderr); - } - if (err.stdout) { - channel.appendLine(err.stdout); - } - channel.appendLine('Auto detecting setup.py commands failed.'); - channel.show(true); - } - } - return result; -} \ No newline at end of file + if (stdout) { + const lines = stdout.split(/\r{0,1}\n/); + for (const line of lines) { + if (line.length === 0) { + isStandardCommands = false; + isExtraCommands = false; + continue; + } + if (line.startsWith("Standard commands:")) { + isStandardCommands = true; + continue; + } + if (line.startsWith("Extra commands:")) { + isExtraCommands = true; + continue; + } + if (isStandardCommands || isExtraCommands) { + const taskName = line.trim().split(" ")[0]; + const kind: SetupToolsTaskDefinition = { + type: "setuptools", + task: taskName, + }; + const task = new vscode.Task( + kind, + workspaceFolder, + taskName, + "setuptools", + new vscode.ShellExecution(`${pythonPath} setup.py ${taskName}`) + ); + result.push(task); + const lowerCaseLine = line.toLowerCase(); + if (isBuildTask(lowerCaseLine)) { + task.group = vscode.TaskGroup.Build; + } else if (isTestTask(lowerCaseLine)) { + task.group = vscode.TaskGroup.Test; + } + } + } + } + } catch (err) { + const channel = getOutputChannel(); + if (err.stderr) { + channel.appendLine(err.stderr); + } + if (err.stdout) { + channel.appendLine(err.stdout); + } + channel.appendLine("Auto detecting setup.py commands failed."); + channel.show(true); + } + } else { + getBuiltinTasks().forEach((taskName) => { + const kind: SetupToolsTaskDefinition = { + type: "setuptools", + task: taskName, + }; + const task = new vscode.Task( + kind, + workspaceFolder, + taskName, + "setuptools", + new vscode.ShellExecution(`${pythonPath} ${setupPyFile} ${taskName}`) + ); + result.push(task); + + if (taskName === "build") { + task.group = vscode.TaskGroup.Build; + } + }); + } + } + return result; +}