欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Jgit 操作 Git 切换分支 chekout

最编程 2024-03-09 20:44:25
...
【开源中国 APP 全新上线】“动弹” 回归、集成大模型对话、畅读技术报告

Jgit 操作Git 切换分支

//列出所有的分支名称,判断分支是否存在
Git git = Git.open(new File(BASE_GIT_PATH));
boolean existBranch = false;
List<Ref> branchList = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
String branchName = featureInfo.getBranchVersion();
for (Ref ref : branchList) {
    if (("refs/remotes/origin/" + branchName).equals(ref.getName())) {
        existBranch = true;
    }
}
if (!existBranch) {
    log.error("分支{}不存在,请确认", branchName);
    throw new BusinessException(ExceptionEnum.BRANCH_NOT_EXIST.getCode(),
            "分支" + branchName + "不存在,请确认");
}
boolean existLocalBranch = false;
List<Ref> branchList = git.branchList().call();
for (Ref ref : branchList) {
    if (ref.getName().equals("refs/heads/" + branchName)) {
        existLocalBranch = true;
    }
}
if (existLocalBranch) {
    // 存在则切换本地分支
    git.checkout().setName(branchName).call();
} else {
    // 不存在则切换为远程分支
    git.checkout().setCreateBranch(true).setName(branchName)
            .setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
            .setStartPoint("origin/" + branchName).call();
}