Callum
Callum

Reputation: 534

Auto run command from vscode extension on file save

I can I auto execute 2 separate commands upon file saving in VS Code?

I want the two commands to do the following:

    1. Format the document in focus
    2. Sort the documents Imports

Upvotes: 32

Views: 51262

Answers (8)

iCasture
iCasture

Reputation: 1

Use this VSCode extension: Run on Save by pucelle.

The Run on Save extension by emeraldwalk supports executing shell commands but does not allow running VS Code commands (commands provided by other extensions). In contrast, Run on Save by pucelle includes this capability. To enable it, set the commands[].runIn property to vscode.

Here’s an example configuration:

{
    "runOnSave.statusMessageTimeout": 3000,
    "runOnSave.commands": [
        {
            // Match scss files except names start with `_`.
            "match": ".*\\.scss$",
            "notMatch": "[\\\\\\/]_[^\\\\\\/]*\\.scss$",
            "command": "node-sass ${file} ${fileDirname}/${fileBasenameNoExtension}.css",
            "runIn": "backend",
            "runningStatusMessage": "Compiling ${fileBasename}",
            "finishStatusMessage": "${fileBasename} compiled"
        },
        {
            // Match less files except names start with `_`.
            "globMatch": "**/[^_]*.less",
            "command": "node-sass ${file} ${fileDirname}/${fileBasenameNoExtension}.css",
            "runIn": "terminal"
        },
        {
            // Match any python files by path.
            "match": ".*\\.py$",
            "command": "python.runLinting",
            "runIn": "vscode"
        },
        {
            // Match any python files by language id.
            "languages": ["python"],
            "command": "python.runLinting",
            "runIn": "vscode"
        }
    ]
}

Upvotes: 0

Raphaël Balet
Raphaël Balet

Reputation: 8481

For

  1. Format the document in focus
  2. Sort the documents Imports

You could add the following element to your settings.json file (Ctrl + ,)

"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
  "source.organizeImports": "explicit"
},

Upvotes: 0

AKUMA no ONI
AKUMA no ONI

Reputation: 11819

There is no default support for running Tasks, or Commands, on save (onSave). However, there is 3rd party support via the VSCode extension "Run on Save".

Here is the link: https://marketplace.visualstudio.com/items?itemName=emeraldwalk.RunOnSave

This is a very popular extension, I used it once a while back and it worked well for my use-case.

Also if you just want to lint, or format code, on save that can be done through VSCode settings.

EDIT June 20, 2021 @ 9:04pm UTC

If you want to add the command to your settings you have to configure a the extension, which is explained in the extensions README.md, that can be viewed by clicking on the extensions icon in the VSCode extensions explorer.

Configuration

Add "emeraldwalk.runonsave" configuration to user or workspace settings.

  • "shell" - (optional) shell path to be used with child_process.exec options that runs commands.
  • "autoClearConsole" - (optional) clear VSCode output console every time commands run. Defaults to false.
  • "commands" - array of commands that will be run whenever a file is saved.
    • "match" - a regex for matching which files to run commands on

    NOTE Since this is a Regex, and also in a JSON string backslashes have to be double escaped such as when targetting folders. e.g. "match": "some\\\\folder\\\\.*"

    • "cmd" - command to run. Can include parameters that will be replaced at runtime (see Placeholder Tokens section below).
    • "isAsync" (optional) - defaults to false. If true, next command will be run before this one finishes.

Sample Config

This sample configuration will run echo statements including the saved file path. In this sample, the first command is async, so the second command will get executed immediately even if first hasn't completed. Since the second isn't async, the third command won't execute until the second is complete.

"emeraldwalk.runonsave": {
    "commands": [
        {
            "match": ".*",
            "isAsync": true,
            "cmd": "echo 'I run for all files.'"
        },
        {
            "match": "\\.txt$",
            "cmd": "echo 'I am a .txt file ${file}.'"
        },
        {
            "match": "\\.js$",
            "cmd": "echo 'I am a .js file ${file}.'"
        },
        {
            "match": ".*",
            "cmd": "echo 'I am ${env.USERNAME}.'"
        }
    ]
}


Configuring a command to execute when you save, isn't going to be as simple as hitting [F1] to open the quick-input, and finding the extensions task that you want to run. You will have to follow the instructions, and when you get stuck, you might have to come back and ask a question about the issue you are experiencing, or google it however; if your a Linux user, or you have a lot of MS-Dos or Powershell experience, this will be pretty straight forward.

Upvotes: 33

Charlie Parker
Charlie Parker

Reputation: 5201

yes install https://marketplace.visualstudio.com/items?itemName=emeraldwalk.RunOnSave

Demo setting.json


{
    "files.exclude": {
        "**/.git": true,
        "**/.svn": true,
        "**/.hg": true,
        "**/CVS": true,
        "**/.DS_Store": true,
        "**/Thumbs.db": true,
        "**/*.olean": true
    },
    "explorer.confirmDragAndDrop": false,
    "terminal.integrated.inheritEnv": false,
    "redhat.telemetry.enabled": true,
    "vs-kubernetes": {
        "vscode-kubernetes.helm-path-mac": "/Users/me/.vs-kubernetes/tools/helm/darwin-arm64/helm",
        "vscode-kubernetes.minikube-path-mac": "/Users/me/.vs-kubernetes/tools/minikube/darwin-arm64/minikube"
    },
    "emeraldwalk.runonsave": {
            "commands": [
                {
                    "match": ".*",
                    "isAsync": true,
                    "cmd": "rsync -avz ~/repo g5:~/"
                },
                {
                    "match": ".*",
                    "isAsync": true,
                    "cmd": "rsync -avz ~/data/all* g5:~/data/"
                },
                {
                    "match": ".*",
                    "isAsync": true,
                    "cmd": "rsync -avz ~/data/debug g5:~/data/"
                },
                {
                    "match": ".*",
                    "isAsync": true,
                    "cmd": "rsync -avz ~/keys g5:~/"
                },
                {
                    "match": ".*",
                    "cmd": "kinit"
                },
                {
                    "match": ".*",
                    "isAsync": true,
                    "cmd": "kubectl cp ~/repo/py_src/ podname:/data/me/repo"
                },
                {
                    "match": ".*",
                    "isAsync": true,
                    "cmd": "kubectl cp ~/repo/py_src/ podfname:/data/me/repo"
                },
                {
                    "match": ".*",
                    "isAsync": true,
                    "cmd": "kubectl cp ~/repo/ podname:/data/me/"
                },
                {
                    "match": ".*",
                    "isAsync": true,
                    "cmd": "kubectl cp ~/repo/ podfname:/data/me/"
                }
            ]
        }
}

g5 is

ssh -i ~/.ssh/me-ssh-key.pem [email protected]

Upvotes: 0

Solo.dmitry
Solo.dmitry

Reputation: 770

If You want to get just the code formatting feature, instead of installing RunOnSave, check that the native setting of IDE is activated. enter image description here

Upvotes: 6

Parth Developer
Parth Developer

Reputation: 1857

In order to above answer for https://marketplace.visualstudio.com/items?itemName=emeraldwalk.RunOnSave.

How to make the above extension work:

In order to see the console output, you have to be in the Output tab and select the Run On Save option in the dropdown. The extension was created before the integrated terminal existed and hasn't seen a major update in a while.

enter image description here

Upvotes: 7

adam.hendry
adam.hendry

Reputation: 5605

Just a heads up to the provided answer:

If you are using Python, the Run on Save extension (and any tasks.json for that matter) in VSCode do not see (automatically recognize) any active virtual environments in your workspace.

All commands are run as if from a shell in the current working directory before your environment is activated. (If you think about it, thinks makes sense because it doesn't know what language/program you are going to run)

To run a python command on save from within the context of a virtual environment, first manually activate it:

"cmd": ".venv\\Scripts\\activate.bat && py -m your_script.py"

Otherwise, the global python installation is used.

If you are using a command from a 3rd party package (e.g. pyupgrade) and you don't have that installed in your global python, nothing gets run. Even worse, if you have multiple python installations and both have the package installed, the package that gets run is the one from your global python, which may not be what you want.

Upvotes: 2

Mark
Mark

Reputation: 180659

As I noted in a comment, there are a number of "run on save" extensions. Here is one that will run external commands, like those from an extension. And it seems to be more recent and better maintained than some.

Run It On

Sample setting:

"runItOn": {
    "commands": [
        {
            "match": ".*",
            "isShellCommand" : false,
            "cmd": "myExtension.amazingCommand"
        },
        {
            "match": "\\.txt$",
            "cmd": "echo 'Executed in the terminal: I am a .txt file ${file}.'"
        }
    ],
    "watchers": [
        {
            "match": "**/*.js",
            "cmd": "echo 'Changes detected on js files.'"
        }
    ]
}

myExtension.amazingCommand is what you are looking for.

Upvotes: 5

Related Questions