Add flit and poetry providers

This commit is contained in:
Anthony Shaw committed 2021-02-08 17:45:18 +11:00
1 parent 2ec6f65e1c
commit c71869d4db
9 files changed
+264 -6

No files matched your search

+11 -3
View File
@@ -1,9 +1,17 @@
# Change Log
All notable changes to the "python-task-provider" extension will be documented in this file.
## 0.2.0
Check [Keep a Changelog](http://keepachangelog.com/) for recommendations on how to structure this file.
- Additional args support
- Task resolver support for tasks.json
- Support for non-root files (setup.py or manage.py)
- Added flit and poetry discovery via pyproject.toml metadata sections
## [Unreleased]
## 0.1.0
- Setuptools command support
- Django command support
## 0.0.1
- Initial release
+43
View File
@@ -2,6 +2,10 @@
An extension for VS Code that provides tasks to the VS Code Task system for Python applications.
- Discovers setuptools (`setup.py`) sub-commands
- Discovers Django `manage.py` and makes all Django commands available as tasks
- Looks at `pyproject.toml` and detects both flit and poetry then makes those tasks available
## Setuptools Task Provider
Automatically discovers available commands for setuptools (`setup.py`) and exposes them to the **Run Task** command:
@@ -15,6 +19,26 @@ Automatically discovers available subcommands for Django (`manage.py`) and expos
![](doc/static/django-task-discovery.png)
## Poetry Task Provider
The poetry discovery script will look for the existence of `pyproject.toml` and the `[tool.poetry]` section within it.
It will then make available the following commands as tasks:
"new", "init", "install", "update", "add", "remove", "show", "build", "publish", "config", "run", "shell", "check", "search", "lock", "version", "export", "env", "cache"
![](doc/static/poetry-task-discovery.png)
## Flit Task Provider
The flit discovery script will look for the existence of `pyproject.toml` and the `[tool.flit.*]` section within it.
It will then make available the following commands as tasks:
"build", "publish", "install", "init"
![](doc/static/flit-task-discovery.png)
## Calling from tasks.json
If you want to save the task and recall it, add it to `tasks.json`:
@@ -39,6 +63,25 @@ If you want to save the task and recall it, add it to `tasks.json`:
The type is either `django` or `setuptools`, and the `task` is the subcommand. You can optionally provide a property `file` to be specific about which `setup.py` or `manage.py` to use (if you have more than 1).
## Providing additional arguments to tasks
Any tasks which require command-line arguments can be given arguments using the `args` array:
```javascript
{
"version": "2.0.0",
"tasks": [
{
"type": "setuptools",
"task": "build",
"args": ["--generator", "ninja"]
}
]
}
```
## Task Explorer UI Support
If you have the Task Explorer UI extension, it will make these available as UI shortcuts:
![](doc/static/task-explorer-shortcut.png)
Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

+33 -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.1.1",
"version": "0.2.0",
"engines": {
"vscode": "^1.52.0"
},
@@ -60,6 +60,38 @@
"description": "Optional list of arguments to the task"
}
}
},
{
"type": "flit",
"required": [
"task"
],
"properties": {
"task": {
"type": "string",
"description": "The flit command"
},
"args": {
"type": "array",
"description": "Optional list of arguments to the task"
}
}
},
{
"type": "poetry",
"required": [
"task"
],
"properties": {
"task": {
"type": "string",
"description": "The poetry command"
},
"args": {
"type": "array",
"description": "Optional list of arguments to the task"
}
}
}
]
},
+8 -1
View File
@@ -36,7 +36,9 @@ export class DjangoTaskProvider implements vscode.TaskProvider {
if (task) {
// resolveTask requires that the same definition object be used.
const definition: DjangoTaskDefinition = <any>_task.definition;
return new vscode.Task(definition, _task.scope ?? vscode.TaskScope.Workspace, definition.task, 'django', new vscode.ShellExecution(`${pythonPath} ${definition.task}`));
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;
}
@@ -79,6 +81,11 @@ interface DjangoTaskDefinition extends vscode.TaskDefinition {
* The python file containing the task
*/
file?: string;
/**
* Optional arguments to the task
*/
args?: string[];
}
function isBuildTask(name: string): boolean {
+11
View File
@@ -1,9 +1,12 @@
import * as vscode from 'vscode';
import { SetupToolsTaskProvider } from './setupToolsTaskProvider';
import { DjangoTaskProvider } from './djangoTaskProvider';
import { PyProjectTaskProvider } from './pyprojectTaskProvider';
let setupToolsProvider: vscode.Disposable | undefined;
let djangoProvider: vscode.Disposable | undefined;
let flitProvider: vscode.Disposable | undefined;
let poetryProvider: vscode.Disposable | undefined;
export function activate(_context: vscode.ExtensionContext): void {
const workspaceRoots = vscode.workspace.workspaceFolders;
@@ -13,6 +16,8 @@ export function activate(_context: vscode.ExtensionContext): void {
setupToolsProvider = vscode.tasks.registerTaskProvider(SetupToolsTaskProvider.SetupToolsType, new SetupToolsTaskProvider());
djangoProvider = vscode.tasks.registerTaskProvider(DjangoTaskProvider.DjangoType, new DjangoTaskProvider());
flitProvider = vscode.tasks.registerTaskProvider(PyProjectTaskProvider.PoetryType, new PyProjectTaskProvider(PyProjectTaskProvider.PoetryType));
poetryProvider = vscode.tasks.registerTaskProvider(PyProjectTaskProvider.FlitType, new PyProjectTaskProvider(PyProjectTaskProvider.FlitType));
}
export function deactivate(): void {
@@ -22,4 +27,10 @@ export function deactivate(): void {
if (djangoProvider) {
djangoProvider.dispose();
}
if (flitProvider) {
flitProvider.dispose();
}
if (poetryProvider) {
poetryProvider.dispose();
}
}
+150
View File
@@ -0,0 +1,150 @@
import * as path from 'path';
import * as fs from 'fs';
import * as cp from 'child_process';
import * as vscode from 'vscode';
export class PyProjectTaskProvider implements vscode.TaskProvider {
static PoetryType = 'poetry';
static FlitType = 'flit';
private pyprojectPromise: Thenable<vscode.Task[]> | undefined = undefined;
private buildType: string = 'undefined';
constructor(type: string) {
if (!vscode.workspace.workspaceFolders) {
return;
}
this.buildType = type;
vscode.workspace.workspaceFolders.forEach(workspaceRoot => {
const pattern = path.join(workspaceRoot.uri.fsPath, 'pyproject.toml');
const fileWatcher = vscode.workspace.createFileSystemWatcher(pattern);
fileWatcher.onDidChange(() => this.pyprojectPromise = undefined);
fileWatcher.onDidCreate(() => this.pyprojectPromise = undefined);
fileWatcher.onDidDelete(() => this.pyprojectPromise = undefined);
});
}
public provideTasks(): Thenable<vscode.Task[]> | undefined {
if (!this.pyprojectPromise) {
this.pyprojectPromise = getTasks(this.buildType);
}
return this.pyprojectPromise;
}
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: PyProjectTaskDefinition = <any>_task.definition;
const args = definition.args ? definition.args.join(' ') : '';
return new vscode.Task(definition, _task.scope ?? vscode.TaskScope.Workspace, definition.task, definition.type, new vscode.ShellExecution(`${pythonPath} -m ${definition.type} ${definition.task} ${args}`));
}
return undefined;
}
}
function exists(file: string): Promise<boolean> {
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 });
});
});
}
let _channel: vscode.OutputChannel;
function getOutputChannel(): vscode.OutputChannel {
if (!_channel) {
_channel = vscode.window.createOutputChannel('Pyproject.toml Auto Detection');
}
return _channel;
}
interface PyProjectTaskDefinition extends vscode.TaskDefinition {
/**
* The task name
*/
task: string;
/**
* Optional arguments to the task
*/
args?: string[];
}
function getBuiltinTasks(type: string): Array<string> {
if (type === "flit") {
return ["build", "publish", "install", "init"];
} else if (type === "poetry") {
return ["new", "init", "install", "update", "add", "remove", "show", "build", "publish", "config", "run",
"shell", "check", "search", "lock", "version", "export", "env", "cache"];
} else {
return [];
}
}
async function getTasks(buildType: string): 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 pyprojectTomlFile = path.join(folderString, 'pyproject.toml');
if (!await exists(pyprojectTomlFile)) {
continue;
}
var pythonPath = vscode.workspace.getConfiguration('python').get('pythonPath');
if (!pythonPath){
pythonPath = 'python';
}
try {
vscode.workspace.openTextDocument(path.join(folderString, 'pyproject.toml')).then((document) => {
let text = document.getText();
if (text && text.search(`\\[tool\\.${buildType}`) !== -1) {
getBuiltinTasks(buildType).forEach(taskName => {
const kind: PyProjectTaskDefinition = {
type: buildType,
task: taskName
};
const task = new vscode.Task(kind, workspaceFolder, taskName, buildType, new vscode.ShellExecution(`${pythonPath} -m ${buildType} ${taskName}`));
result.push(task);
if (taskName === "build") {
task.group = vscode.TaskGroup.Build;
}
});
}
});
} catch (err) {
const channel = getOutputChannel();
if (err.stderr) {
channel.appendLine(err.stderr);
}
if (err.stdout) {
channel.appendLine(err.stdout);
}
channel.appendLine('Auto detecting pyproject.toml commands failed.');
channel.show(true);
}
}
return result;
}
+8 -1
View File
@@ -36,7 +36,9 @@ export class SetupToolsTaskProvider implements vscode.TaskProvider {
if (task) {
// resolveTask requires that the same definition object be used.
const definition: SetupToolsTaskDefinition = <any>_task.definition;
return new vscode.Task(definition, _task.scope ?? vscode.TaskScope.Workspace, definition.task, 'setuptools', new vscode.ShellExecution(`${pythonPath} ${definition.task}`));
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;
}
@@ -79,6 +81,11 @@ interface SetupToolsTaskDefinition extends vscode.TaskDefinition {
* The python file containing the task
*/
file?: string;
/**
* Optional arguments to the task
*/
args?: string[];
}
const buildNames: string[] = ['bdist', 'bdist_wheel', 'sdist', 'build'];