如何在Visual Studio Code中访问Git的API

16

我希望在我的扩展中使用 vscode git api 来进行 git clone 和其他任务。这个 api 可以从 vscode api 中访问吗? 代码位于这里..api


我也在想同样的问题... 在文档中,关于 Git API 只有两个(2!)项目。当我查看了我经常使用的两个 Git 扩展(gitHistoryVSCodevscode-gitlens)的代码时,我注意到作者编写了基本的 Git 功能(如 checkoutbranch 等),而不是使用 VSCode 中已经内置的 Git 功能。 - Daniel
1
同样的问题,在这方面好像没有任何消息。该存储库上的这个开放问题似乎试图使扩展的API可用:https://github.com/Microsoft/vscode/issues/31103 - batjko
3个回答

11

Twitter 来拯救! 我在那里询问并被指向了这里的 API 定义:https://github.com/Microsoft/vscode/blob/master/extensions/git/src/api/git.d.ts

...以及这里的示例:https://github.com/microsoft/vscode-pull-request-github/blob/0068c135d1c3e5ce601c1d5c7f7007904e59901e/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];

1
导入 GitExtension 的导入行是什么? - David Lechner
2
你能否请澄清一下这段代码?它非常令人困惑,我已经尝试过了,但是一无所获... - TOPKAT

10

在 VS Code 扩展中使用 Git API 的示例代码:

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 });

你还需要在 package.json 中更新 extensionDependencies:

"extensionDependencies": [
    "vscode.git"
  ]

2
我决定使用 simple-git npm 模块,而不是依赖于 git 扩展。 - Nishant

0
根据扩展API,要访问由另一个扩展提供的API:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接