简体   繁体   中英

Is there a way to copy a file on save vscode

Workflow to automate

  • code file file in folder B
  • copy file to folder A

Is there a way to have this file/multiple files copy on save in vscode?

Context

I have two folder A and B . Folder B has some code in it that has to be copy pasted into folder A for it to be executed. But version control is on folder B for this file so I have to code there.

I finnaly did it, so I share it: Using both Visual Studio Code extensions: multi command (from @ryuta46) and command runner (from @ed.net) I can add a 'multi-command' triggered on 'Ctrl+s' shortkey (when saving file) that copy the file to another directory:

Add into settings.json Create a new 'multi command' named copyFile: adjust the destination as needed. This command save the file, wait 2 seconds, and copy to another location.

"multiCommand.commands": [
{
    "command": "multiCommand.copyFile",
    "label": "Copy file to another location",
    "description": "copy the current $file to another root hard-coded destination, require 'command-runner' plugin.",
    "interval": 2,
    "sequence": [
        "workbench.action.files.save",
        {
            "command": "command-runner.run",
            "args": { "command": "cp \"${file}\" \"x:/${relativeFile}\"" }
        }
    ]
}

]

Add into keybindings.json Trigger the previously defined copyFile multicommand on 'Ctrl+s'

[
    {
        "key": "ctrl+s",
        "command": "extension.multiCommand.execute",
        "args": { 
            "command": "multiCommand.copyFile"
        },
        "when": "editorTextFocus"
    }
]

This can be done with a single macro extension, like Multi-Command . Make this keybinding in your keybindings.json :

{
  "key": "alt+s",                  // whatever keybinding you want
  "command": "extension.multiCommand.execute",
  "args": { 
    "sequence": [
      "workbench.action.files.save",
      {
        "command": "workbench.action.terminal.sendSequence",
        "args": {
          "text": "cp '${file}' '${relativeFileDirname}\\copyTo'\u000D"
        }
      }
    ]
  }
}

The sendSequence command sends the argument text to the terminal - the sample script assumes a bash-like shell.

As you can see, it saves and then copies the current file to the copyTo folder which is under the same parent directory as the current file.

Theis a return so the command runs immediately without manually having to hit return.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM