Configure Visual Studio Code to have a default Build Task based on file extension - visual-studio-code

I would like to know if there is a way to define a default Build Task for VSCode depending on file extension.
When working in some folder of Python code, I define the following Build Task:
{
"version": "0.1.0",
"command": "python",
"isShellCommand": true,
"showOutput": "always",
"args": ["${file}"]
}
Then if next time I go to another Python folder, I have to redefine it again.
Is it possible to configure VSCode in such a way that if it detects the current file as a Python script, then it will automatically define the above Build Task?
Thank you in advance for your help!

Update for latest vscode
The following will create a default "build" script, so you can use the keyboard shortcut to build your project. (Below for a javascript project, but shows general outline for other languages/projects.)
(1) Assuming you have a script named "build.js" at the root of your project.
(2) Create a file named "tasks.json" in root of project (workspace) with the following contents:
// tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "mybuildscript", // use same name as in package.json
"group": {
"kind": "build",
"isDefault": true
}
}
]
}
(3) In your package.json, add "scripts" as:
// package.json
{
"name": "my",
"version": "1.0.0",
"description": "",
"scripts": {
"mybuildscript": "node ./build.js"
},
"dependencies": {
"myfs": "^1.0.22"
}
}
I created a rudimentary vscode extension that does all this for you:
https://marketplace.visualstudio.com/items?itemName=gieson.make-build-task
The extension isn't perfect (doesn't cover all the possible ways a project/workspace can be configured), but it's a good starting point.
Here's the repo:
https://github.com/bobtherobot/make-build-task

This is possible, but it requires writing an extension (unless somebody has already written one with a tasks provider for Python). Since 1.14.0, there's a new API which allows extensions to dynamically provide tasks. Check out the Task Provider Example.
Alternatiely, the Code Runner extension probably does the trick in this case as well. It doesn't use the Tasks system though.

Related

Is there are ways to use VSCode tasks.json dependsOn to add dependencies from other projects

I have a multi root workspace with several projects in it. Each project has its own build task that calls an external script to do the build. One project requires all the others to be built prior to it's build as it is required to link against them. I will call this the "app" project from now on.
I have tried using the dependsOn in the app's tasks.json build config, but referencing the name of the external build tasks has no effect if a command is specified, and throws an error if no command is specified. e.g:
{
"label": "build-app",
"group": "build",
"dependsOn": [
"devices"
"app",
],
"dependsOrder": "sequence",
"problemMatcher": []
}
Gives this error, even though the task 'devices' does exist and works in devices/tasks.json file:
Couldn't resolve dependent task 'devices' in workspace folder 'file:///home/simon/git-repos/workspace/app'
Now that suggests it is not searching outside the current workspace folder, so I tried creating a top level "workspace" tasks in the .code-workspace file and referencing the build tasks in there:
{
"label": "build-app",
"group": "build",
"dependsOn": [
"devices"
"app",
],
"dependsOrder": "sequence",
"problemMatcher": []
}
This results in a similar error:
Couldn't resolve dependent task 'devices' in workspace folder 'file:///home/simon/git-repos/workspace/app.code-workspace'
Couldn't resolve dependent task 'app' in workspace folder 'file:///home/simon/git-repos/workspace/app.code-workspace'
Now that looks like the it is not searching outside the .code-workspace file.
I can with a little bit of trickery get it to work the way I want, but I have to specify all the tasks in the app/tasks.json file change directory to dependency project and specify the problem matcher "relative path" for each task. e.g.:
{
"type": "shell",
"label": "devices",
"command": "cd ${workspaceFolder}/../devices && ./build.py",
"problemMatcher": {
"base": "$gcc",
"fileLocation": ["relative", "${workspaceRoot}/../devices"]
},
"group": "build",
},
That is all kind of OK, as I can now do what I want and create a build dependency but the task definitions are not in the correct place. They are all in the app/tasks.json not in each project's own tasks.json. It just seems like the logic is in the wrong place.
I checked the tasks.json Schema at https://code.visualstudio.com/docs/editor/tasks-appendix to see if there were extra parameters you can set on the dependsOn entries, and there is not even a mention of dependsOn or dependsOrder.
Is there are way to configure the tasks in the individual project tasks.json files and reference them in the dependsOn of a task in another project or the top level workspace configuration?
Where can I find the full schema for the tasks.json file? Or the code that is used to read this file in?
Simon.

How to use IDE variables in launch.json in Visual Studio Code

Im using a virtual environment for my python project and I'd like to configure commands to automatize debugging.
So far, I've changed the python.pythonPath in launch.json and my intention is to update all dependencies before building with a custom task, which structure follows like
{
"version": "2.0.0",
"tasks": [{
"label": "echotest",
"command": "python ...", // Could be any other shell command
"args": ["test"],
"type": "shell"
}]
}
So, my question is if there is any way of using the pythonPath variable defined in launch.json inside the command key
My question is answered here in case it helps anyone. My final tasks.json is
{
"version": "2.0.0",
"tasks": [{
"label": "update dependencies",
"command": "${workspaceFolder}\\${config:python.pythonPath} -m pip -r ${workspaceFolder}\\requirements.txt",
"args": [],
"type": "shell"
}]
}
Care with blank spaces in folder names since scaping them with \"doesn't work at all

Visual Studio Code launch.json file for JUnit?

Can someone point me toward a sample launch.json file for JUnit 4 so I can run tests from Visual Studio Code? I am unable to find an example of this online and all attempts to create one have failed.
I am able to run tests manually from the command line. (FWIW, I'm using CentOS.) Here's what I do to run them:
cd /opt/ABBYY/FREngine12/Samples/Java/Hello_VSC/src/test/java
java -cp .:/opt/junit/junit-4.12.jar:/opt/junit/hamcrest-core-1.3.jar org.junit.runner.JUnitCore Hello.AppTest
My Java project is set up to support Maven (I'm not really using Maven -- I've only set it up with Maven because Java debugging in Visual Studio Code will not work without it). So in the .classpath file I've added the following entries, which should add the .jar files from my command line call to the code path:
<classpathentry kind="lib" path="/opt/junit/junit-4.12.jar" />
<classpathentry kind="lib" path="/opt/junit/hamcrest-core-1.3.jar" />
When I try to set up the launch.json file, I'm attempting to do something like this:
{
"type": "java",
"name": "Test-<Hello_VSC>",
"request": "launch",
"cwd": "/opt/ABBYY/FREngine12/Samples/Java/Hello_VSC/src/test/java/",
"console": "internalConsole",
"stopOnEntry": false,
"mainClass": "Hello.AppTest",
"projectName": "Hello_VSC",
"args": "org.junit.runner.JUnitCore Hello.AppTest",
},
However, I get this error message:
Error: Main method not found in class Hello.AppTest, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application
Even if I change cwd to a completely bogus directory, I get the same error message. I don't know if my type parameter is wrong, my cwd parameter is wrong, or if it's something else.
Any suggestions?
Never mind -- I figured it out. I guess I had everything set up correctly with my project, but didn't realize that the proper way to run tests with the Java extensions for Visual Studio Code was to simply click on the Explorer (file) icon, then expand the "Test Explorer" option, explore down to whatever test(s) you want to run, right-click, and then choose your testing options. There is no need to use the launch.json file to do this.
If you search for tasks.json (instead of launch.json), you will get this example
/*
Example for quick Java compilation and unit tests in VS Code.
Works well with simple BlueJ projects.
Hit Ctrl+Shift+B to compile currently open file with javac.
Hit Ctrl+Shift+T to test currently open test class.
See red wiggles for compilation errors / failed assertions or click exclamation mark in the status bar.
Uses a few workarounds for individual commands per task and filename without extension.
This is written for Windows but it should be easy to adopt for Linux and Mac.
*/
{
"version": "0.1.0",
"isShellCommand": true,
"suppressTaskName": true,
"showOutput": "silent",
"windows": {
"command": "powershell",
"args": ["-Command"],
"tasks": [
{
// tests the currently open test class. java has to be in %PATH% and the jUnit-jar in %CLASSPATH%.
"taskName": "junit",
"args": ["$env:CLASSPATH += ';${fileDirname}'; $class = [System.IO.Path]::GetFileNameWithoutExtension('${fileBasename}'); java org.junit.runner.JUnitCore $class | Select-String -NotMatch -Pattern 'at (?!.+${fileBasename})'"],
"isTestCommand": true,
"problemMatcher": {
"owner": "java",
"fileLocation": ["relative", "${fileDirname}"],
"pattern": [
{
"regexp": "^(.*)$",
"message": 1
},
{
"regexp": "^\\s*at .+\\((.+):([0-9]+)\\)$",
"file": 1,
"line": 2
}
]
}
},
]
}
}
But it is in "0.1.0", so you will have to convert it to 2.0.0 first.

TS lint plugin for VS code doesn't track closed files

I'm using VSCode 1.17.2, and using tslint plugin with it to track lint errors. As of now it is working fine with opened files and showing errors on files with red marker and giving error in problems tab. But it is not tracking closed files. Am I missing any configuration? Currently I am using default configuration.
See the documentation for the extension:
The extension lints an individual file only. If you want to lint your
entire workspace or project and want to see the warnings in the
Problems panel, then you can:
use gulp that or define a script inside the package.json that runs
tslint across your project.
define a VS Code task with a problem matcher
that extracts VS Code warnings from the tslint output.
For example, here is an excerpt from a package.json file that defines
a script to run tslint:
{
"name": "tslint-script-demo",
"version": "1.0.0",
"scripts": {
"lint": "tslint tests/*.ts -t verbose"
},
"devDependencies": {
"typescript": "^2.2.2",
"tslint": "^5.0.0" }
}
Next, define a Task which runs the npm script with a problem matcher
that extracts the tslint errors into warnings.
{
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "lint",
"problemMatcher": {
"base": "$tslint5",
"fileLocation": "relative"
}
}
]
}
Finally, when you then run the tslint task you will see the warnings produced by the npm script in the Problems panel and you can
navigate to the errors from there.
Here is the complete setup example setup.

VS Code - Failed to launch external program tsc.exe

I keep getting the "Failed to launch external program tsc.exe" in VS Code. I have installed typescript and set my path to where tsc.exe is located. Any suggestions
Here is my task file
// The command is tsc.
"command": "tsc",
// Show the output window only if unrecognized errors occur.
"showOutput": "silent",
// Under windows use tsc.exe. This ensures we don't need a shell.
"windows": {
"command": "tsc.exe"
},
// args is the HelloWorld program to compile.
"args": ["HelloWorld.ts"],
// use the standard tsc problem matcher to find compile problems
// in the output.
"problemMatcher": "$tsc"
You should try to install tsc this way:
npm install -g typescript
And then change tasks.json to:
...
"windows": {
"command": "tsc.cmd"
},
"args" : ["Myfilename.ts"]
...
And everything should work as expected, also, try to read this:
https://code.visualstudio.com/Docs/tasks
Well,
I came up with my own solution to generate modified version of tasks.json each time you config task runner(CTR), but I don't know if this is a really good pratice as VSCode is brand new I've not found a better solution, If anyone knows how to change CTR in the proper way PLEASE let me know!
There is a file called taskSampleConfig.json that is parsed everytime CTR runs, and this file is inside VSCode folder, so you may change it to:
...
"windows": {
"command": "tsc.cmd"
},
...
Since I can't comment yet I post it as an answer:
Since tsc.cmd must be executed in a command interpreter you need to configure it like this:
"windows": {
"command": "tsc",
"isShellCommand": true
}
The taskSampleConfig.json file is basically used as a template if VSCode can't auto detect a task runner. There is currently no support to customize the templating.
For me it works that way (Using VSCode in Admin-Mode on Win8):
Installing Typescript via npm (as jrabello wrote)
Setting up the task like this:
"version": "0.1.0",
"command": "tsc",
"showOutput": "silent",
"isShellCommand": true
Creating a tsconfig.json for your project with the compiler-options you need:
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"sourceMap": true
}