【JGit】分支管理实践

本文紧接【JGit】简述及学习资料整理

以下梳理了使用 JGit 进行 Git 操作的实践

JGit实践

主函数

public static void main(String[] args) throws Exception {
        String localDir = "D:\\tmp\\git-test\\";

        String gitUrl = "http://192.168.181.1:3000/root/git-test-by-code.git";

        String username = "root";
        String password = "123456";
        // 创建认证信息
        CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username, password);

        // 初始化 git 仓库
        Git git = Git.init().setDirectory(new File(localDir)).call();


        // Pull Test
        // pullTest(gitUrl, credentialsProvider, git);

        // ==== 分支管理
        // branchManage(git);

        // ==== 创建分支,并将其推送到远程仓库
		newBranchAndPush(credentialsProvider, git);
		// ==== 删除远程分支
		//deleteRemoteBranch(credentialsProvider, git);

        // 关闭 git 命令
        git.close();
    }

拉取代码

private static void pullTest(String gitUrl, CredentialsProvider credentialsProvider, Git git)
            throws GitAPIException, URISyntaxException, WrongRepositoryStateException, InvalidConfigurationException,
            InvalidRemoteException, CanceledException, RefNotFoundException, RefNotAdvertisedException, NoHeadException,
            TransportException {
        // 添加远程仓库信息
        git.remoteAdd()
                .setName("origin")
                .setUri(new URIish(gitUrl))
                .call();

        // 代码拉取
        PullResult pullResult = git.pull()
                .setCredentialsProvider(credentialsProvider)
                .call();

        log.info(">>> " + pullResult);
        if (pullResult.isSuccessful()) {
            log.info(">>> pull Result is Success");
        } else {
            log.error(">>> pull Result is Failes ");
        }
    }

分支管理

private static void branchManage(Git git) throws Exception {
        // 列出所有分支
        branchList(git);

        // 添加分支 dev
        System.err.println("<<< 添加分支");
        git.branchCreate().setName("dev").call();
        branchList(git);

        // 修改分支名
        System.err.println("<<< 修改分支");
        git.branchRename().setOldName("dev").setNewName("dev-new").call();
        branchList(git);

        // 删除分支
        System.err.println("<<< 删除分支");
        git.branchDelete().setBranchNames("dev-new").call();
        branchList(git);
    }

private static void branchList(Git git) throws Exception {
    // 获取默认分支
        String currentBranch = git.getRepository().getBranch();
        List<Ref> call = git.branchList().call();
        for (Ref ref : call) {
            boolean symbolic = ref.isSymbolic();
            boolean peeled = ref.isPeeled();
            String name = ref.getName();
            if(currentBranch.equals(name.substring(name.lastIndexOf('/') + 1))){
                name = "* \t"+ name;
            }else{
                name = "\t" + name;
            }
            System.out.println(">>> \t"+ name + "  " + ref.getObjectId().getName() + "  ,symbolic:" + symbolic + ", peeled: " + peeled);
        }
    }

创建新分支并推送到远程服务器

 private static void newBranchAndPush(CredentialsProvider credentialsProvider, Git git) throws Exception{
     // 创建 dev 分支
        Ref branchRef = git.branchCreate().setName("dev").call();

        // 推送分支到远程仓库
        Iterable<PushResult> results = git.push()
                .setCredentialsProvider(credentialsProvider)
                .setRemote("origin")
                .add(branchRef)
                .call();

        // 处理推送结果
        for (PushResult result : results) {
            for (RemoteRefUpdate update : result.getRemoteUpdates()) {
                System.out.println("Status: " + update.getStatus());
            }
        }
}

推送结果展示

在这里插入图片描述

删除远程分支

private static void deleteRemoteBranch(CredentialsProvider credentialsProvider, Git git) throws GitAPIException {
        String deleteBranch = "dev";
        RefSpec refSpec = new RefSpec()
                .setSource(null)
                .setDestination("refs/heads/" + deleteBranch);
         
        Iterable<PushResult> results = git.push()
                .setCredentialsProvider(credentialsProvider)
                .setRemote("origin")
                .setRefSpecs(refSpec)
                .call();

        // 处理推送结果
        for (PushResult result : results) {
            for (RemoteRefUpdate update : result.getRemoteUpdates()) {
                System.out.println("Status: " + update.getStatus());
            }
        }
    }

以上代码相当关于执行了 git push origin --delete dev 命令。

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值