起因
对于一个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
呢,太丑了,而且还会影响到程序的argv。
对比其他的命令,发现如果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 ."
即可。