Home > Net >  VS Code Extension. How to get the directory of the current open file?
VS Code Extension. How to get the directory of the current open file?

Time:01-11

I ran into a problem while writing an extension for Visual Studio Code! I keep getting messages like this "Cannot read properties of undefined (reading 'uri')", etc.

 const defaultCompiler = 'g  ';

 // define the command for compiling C   code with each compiler
 const compilerCommands = {
   'g  ': 'g   -S -o "{oFile}" "{cFile}"',
   'clang  ': 'clang   -S -o "{oFile}" "{cFile}"'
 };

 let currentlyOpenFilePath = vscode.window.activeTextEditor;
 // let curDir = vscode.workspace.workspaceFolders[0].uri.path
 let cFile = currentlyOpenFilePath.document.uri.path;
 let dirPath = path.dirname(cFile);
 let oFile = path.join(dirPath, 'output.s');

 let command = compilerCommands[this.currentCompiler].replace('{cFile}', currentlyOpenFilePath).replace('{oFile}', oFile);

I surfed all over Google in search of a solution to the problem, but everything I found did not help me. I tried various combinations in variables currentlyOpenFilePath, curDir, cFile (currently open file), dirPath, oFile.

My system is MacOS and also needs to work on Windows. And also the extension is local (the previous version of the code took the path not of the current open file, but the path to the extension)

I need this plugin, when called, to successfully process the command "g -S -o {oFile} {cFile}" or "clang -S -o {oFile} {cFile}" by changing {cFile} to the current path to the open .cpp file in editor a in {oFile}, same path as {cFile} but saved as output.s

CodePudding user response:

let workspacePath = '';
if (vscode.workspace.workspaceFolders?.length) {
    workspacePath = workspace.workspaceFolders[0].uri.fsPath;
    workspacePath = path.normalize(workspacePath);
}

Try to see if it's what you want

  • Related