How to access the api for git in visual studio code

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"
  ]

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];