Make dynamic subcommand discovery optional

This commit is contained in:
Anthony Shaw committed 2021-02-11 19:37:32 +11:00
1 parent c71869d4db
commit 9d610ac4f8
5 files changed
+462 -297

No files matched your search

+4
View File
@@ -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
+5
View File
@@ -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`:
+16 -1
View File
@@ -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",
+219 -140
View File
@@ -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<vscode.Task[]> | undefined = undefined;
static DjangoType = "django";
private djangoPromise: Thenable<vscode.Task[]> | 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<vscode.Task[]> | undefined {
if (!this.djangoPromise) {
this.djangoPromise = getDjangoTasks();
}
return this.djangoPromise;
}
public provideTasks(): Thenable<vscode.Task[]> | 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 = <any>_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 = <any>_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<boolean> {
return new Promise<boolean>((resolve, _reject) => {
fs.exists(file, (value) => {
resolve(value);
});
});
return new Promise<boolean>((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<string> {
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<vscode.Task[]> {
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;
}
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;
}
+218 -156
View File
@@ -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<vscode.Task[]> | undefined = undefined;
static SetupToolsType = "setuptools";
private setuptoolsPromise: Thenable<vscode.Task[]> | 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<vscode.Task[]> | undefined {
if (!this.setuptoolsPromise) {
this.setuptoolsPromise = getSetupToolsTasks();
}
return this.setuptoolsPromise;
}
public provideTasks(): Thenable<vscode.Task[]> | 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 = <any>_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 = <any>_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<boolean> {
return new Promise<boolean>((resolve, _reject) => {
fs.exists(file, (value) => {
resolve(value);
});
});
return new Promise<boolean>((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<string> {
return [
"build",
"sdist",
"test",
"bdist",
"bdist_wheel",
"clean",
"check",
"develop",
"install",
];
}
async function getSetupToolsTasks(): Promise<vscode.Task[]> {
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;
}
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;
}