当前位置: 首页 > news >正文

【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 命令。

  • [【JGit】简述及学习资料整理]([JGit ]简述及学习资料整理-CSDN博客)
  • 【Gitea】Java 使用 JGit 创建 Git 代码仓库
  • Win 下 Docker 安装 Gitea 实践:windows docker desktop部署gitea

相关文章:

  • 我为什么不喜欢关电脑?
  • 【C++】类与对象—— 初始化列表 、static 静态成员、
  • Zookeeper特性与节点数据类型详解
  • 枚举类(enum)
  • Jenkins使用遇到的一些问题
  • MYSQL--存储过程操作
  • FastGPT配置文件及OneAPI程序:
  • 浅拷贝导致的bug
  • 【算法与数据结构】1971、LeetCode寻找图中是否存在路径
  • Ubuntu20.04 查看系统版本号
  • go - 学习笔记 - 1
  • 使用logicflow流程图实例
  • ClickHouse快速上手
  • Hyperf 使用配置中心 - nacos配置中心
  • 力扣hot100题解(python版10-12题)
  • Windows如何新建一个需要管理员权限才能删除的文件夹
  • Vue | (四)使用Vue脚手架(上) | 尚硅谷Vue2.0+Vue3.0全套教程
  • IDEA自定义类注释及方法注释模板
  • 智慧城市的新宠儿:会“思考”的井盖
  • 分布式锁的应用场景及实现