How to access the api for git in visual studio code

Viewed 3407

I want to use the vscode git api in one my extension to do git clone and other tasks. Is it accessible from the vscode api ? The code is present here.. api

3 Answers

Twitter to the rescue! I asked there and was pointed to the API definitions here: https://github.com/Microsoft/vscode/blob/master/extensions/git/src/api/git.d.ts

...and an example here: https://github.com/Microsoft/vscode-pull-request-github/blob/master/src/extension.ts#L53

// Import the git.d.ts file
import { API as GitAPI, GitExtension, APIState } from './typings/git'; 

const gitExtension = vscode.extensions.getExtension<GitExtension>('vscode.git').exports;
const api = gitExtension.getAPI(1);

const rootPath = vscode.workspace.rootPath;
const repository = api.repositories.filter(r => isDescendant(r.rootUri.fsPath, rootPath))[0];

Sample code for using git api in vscode extension :

const gitExtension = vscode.extensions.getExtension('vscode.git').exports;
const api = gitExtension.getAPI(1);

const repo = api.repositories[0];
const head = repo.state.HEAD;

// Get the branch and commit 
const {commit,name: branch} = head;

// Get head of any other branch
const mainBranch = 'master'
const branchDetails = await repo.getBranch(mainBranch);

// Get last merge commit
const lastMergeCommit = await repo.getMergeBase(branch, mainBranch);

const status = await repo.status();

console.log({ branch, commit, lastMergeCommit, needsSync: lastMergeCommit !== commit });

You also have to update extensionDependencies in you package.json:

"extensionDependencies": [
    "vscode.git"
  ]

According to the extension API, to access APIs that provided by another extension:

When depending on the API of another extension add an extensionDependencies-entry to package.json, and use the getExtension-function and the exports-property, like below:

let mathExt = extensions.getExtension('genius.math');
let importedApi = mathExt.exports;

console.log(importedApi.mul(42, 1));
Related