function getCurrentGitBranch(docUri: vscode.Uri): string | undefined {
const extension = vscode.extensions.getExtension<GitExtension>("vscode.git");
if (!extension) {
console.warn("Git extension not available");
return undefined;
}
if (!extension.isActive) {
console.warn("Git extension not active");
return undefined;
}
// "1" == "Get version 1 of the API". Version one seems to be the latest when I
// type this.
const git = extension.exports.getAPI(1);
const repository = git.getRepository(docUri);
if (!repository) {
console.warn("No Git repository for current document", docUri);
return undefined;
}
const currentBranch = repository.state.HEAD;
if (!currentBranch) {
console.warn("No HEAD branch for current document", docUri);
return undefined;
}
const branchName = currentBranch.name;
if (!branchName) {
console.warn("Current branch has no name", docUri, currentBranch);
return undefined;
}
return branchName;
}
2条答案
按热度按时间xesrikrc1#
原生git扩展现在提供了几个方法/属性来获取当前分支以及所有分支
点击这里查看git扩展API参考:
获取分支https:github.com/microsoft/vscode/blob/master/extensions/git/src/api/api1.ts#L160
获取分支https:github.com/microsoft/vscode/blob/master/extensions/git/src/api/api1.ts#L164
2nc8po8w2#
首先,请确保按照设置说明操作。
然后,这是我想到的。