vscode-code-runner去除末尾自動新增的檔名
阿新 • • 發佈:2022-12-11
起因
對於一個go專案,如果main package包含多個檔案,則需要執行go run .
這樣的命令。在vscode中,code-runner預設的go檔案執行命令在defaultSettings.json中如下:
"code-runner.executorMap": {
"go": "go run",
}
實際執行時,會變成`go run "$fullFileName",此時main package無法識別多個.go檔案的內容。
操作
好,那就在settings.json裡,把他改成:"go": "go run ."
,執行!
確實可以正常運行了,但是末尾怎麼會自動帶上$fullFileName
對比其他的命令,發現如果command中不自己寫上
$fileName
,$dir
之類的變數,code-runner就會自動給末尾加上$fullFileName
。再看了一遍defaultSettings,似乎沒有什麼配置可以指定不加上這段檔名。那就看外掛原始碼。
發現在
src\codeManager.ts::getFinalCommandToRunCodeFile
中,確實有這種邏輯。如果沒有變數需要替換,就自動加上檔名了。
// code from https://github.com/formulahendry/vscode-code-runner private async getFinalCommandToRunCodeFile(executor: string, appendFile: boolean = true): Promise<string> { let cmd = executor; if (this._codeFile) { const codeFileDir = this.getCodeFileDir(); const pythonPath = cmd.includes("$pythonPath") ? await Utility.getPythonPath(this._document) : Constants.python; const placeholders: Array<{ regex: RegExp, replaceValue: string }> = [ // A placeholder that has to be replaced by the path of the folder opened in VS Code // If no folder is opened, replace with the directory of the code file { regex: /\$workspaceRoot/g, replaceValue: this.getWorkspaceRoot(codeFileDir) }, // A placeholder that has to be replaced by the code file name without its extension { regex: /\$fileNameWithoutExt/g, replaceValue: this.getCodeFileWithoutDirAndExt() }, // A placeholder that has to be replaced by the full code file name { regex: /\$fullFileName/g, replaceValue: this.quoteFileName(this._codeFile) }, // A placeholder that has to be replaced by the code file name without the directory { regex: /\$fileName/g, replaceValue: this.getCodeBaseFile() }, // A placeholder that has to be replaced by the drive letter of the code file (Windows only) { regex: /\$driveLetter/g, replaceValue: this.getDriveLetter() }, // A placeholder that has to be replaced by the directory of the code file without a trailing slash { regex: /\$dirWithoutTrailingSlash/g, replaceValue: this.quoteFileName(this.getCodeFileDirWithoutTrailingSlash()) }, // A placeholder that has to be replaced by the directory of the code file { regex: /\$dir/g, replaceValue: this.quoteFileName(codeFileDir) }, // A placeholder that has to be replaced by the path of Python interpreter { regex: /\$pythonPath/g, replaceValue: pythonPath }, ]; placeholders.forEach((placeholder) => { cmd = cmd.replace(placeholder.regex, placeholder.replaceValue); }); } return (cmd !== executor ? cmd : executor + (appendFile ? " " + this.quoteFileName(this._codeFile) : "")); }
對於go專案,執行go run .需要在根目錄執行,有時候編輯完其他go檔案,需要先切換回根目錄的檔案再用code-runner,不太方便。所以把executorMap修改為:"go": "cd $workspaceRoot && go run ."
即可。