skip to Main Content

Given a path of a file or folder that is in a VS Code workspace, is there an API I can use to determine if it’s Git-controlled and look up the associated remote repository URL? This would be for a custom extension.

2

Answers


  1. I am not sure if this answers your question, but if it is something you are working on, there is a hidden git folder in the root folder. ".git" which has a config file with the remote url listed.

    Login or Signup to reply.
  2. Try this code. It gets the workspace folder of the file you are interested in. And then checks if that is one of the git repositories that you have opened – it works for single root or multiroot workspaces where a file may be in a root folder that may or may not be in a git repo.

        const gitExtension = vscode.extensions.getExtension('vscode.git').exports;
        const api = gitExtension.getAPI(1);
    
        // some file you are interested in, get a uri from it
        // note forward slashes
        const myUri = vscode.Uri.file('C:/Users/Mark/OneDrive/TestMultiRoot/Test.js');
    
        // note double backslashes also work
        // const myUri = vscode.Uri.file('C:\Users\Mark\OneDrive\TestMultiRoot\Test.js');
    
        // below single backslashes - DO NOT WORK
        // const myUri = vscode.Uri.file('C:UsersMarkOneDrivecommand-aliasscratchpad.txt');
    
        const repo = api.repositories.find(repo => {
            // to test current editor, below returns the workspaceFolder
            // const inThisFolder = vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri);
            
            const inThisFolder = vscode.workspace.getWorkspaceFolder(myUri);
            return inThisFolder?.uri?.fsPath === repo?.rootUri?.fsPath;
        });
    
        if (!repo) return;  // no git repo for this file
        const repoPath = repo.repository.remotes[0].fetchUrl;
        // repoPath is like "https://github.com/ArturoDent/command-alias.git"
    
        // note that 'remotes' is an array, it will contain CLONES of the original repository
        // but it appears that remotes[0] is the current working repository you are interested in, check
    

    See also https://stackoverflow.com/a/59442538 and Git integration for Visual Studio Code especially the part about extensionDependencies.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search