JAVA 使用jgit管理git仓库
最近设计基于gitops新的CICD方案,需要通过java读写git仓库,这里简单记录下。
JGit是一款pure java的软件包,可以读写git仓库,下面介绍基本使用。
引入jgit
maven引入:
<!-- https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit -->
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>5.6.0.201912101111-r</version>
</dependency>
jgit 有一个Git类,可以用来执行常规的git操作
凭证管理
通过CredentialsProvider管理凭证,常用的是UsernamePasswordCredentialsProvider
通过下面代码初始化:
public static CredentialsProvider createCredential(String userName, String password) {
return new UsernamePasswordCredentialsProvider(userName, password);
}
clone远程仓库
git 命令:
git clone {repoUrl}
通过Git.cloneRepository 来clone远程仓库,如果需要凭证,则需要指定credentialsProvider
public static Git fromCloneRepository(String repoUrl, String cloneDir, CredentialsProvider provider) throws GitAPIException {
Git git = Git.cloneRepository()
.setCredentialsProvider(provider)
.setURI(repoUrl)
.setDirectory(new File(cloneDir)).call();
return git;
}
commit
git 命令:
git commit -a -m '{msg}'
commit比较简单,对应commit方法, 注意需要先add
public static void commit(Git git, String message, CredentialsProvider provider) throws GitAPIException {
git.add().addFilepattern(".").call();
git.commit()
.setMessage(message)
.call();
}
push
git 命令:
git push origin branchName
push直接调用push即可, 需要指定credentialsProvider
public static void push(Git git, CredentialsProvider provider) throws GitAPIException, IOException {
push(git,null,provider);
}
public static void push(Git git, String branch, CredentialsProvider provider) throws GitAPIException, IOException {
if (branch == null) {
branch = git.getRepository().getBranch();
}
git.push()
.setCredentialsProvider(provider)
.setRemote("origin").setRefSpecs(new RefSpec(branch)).call();
}
读取已有仓库
如果git已经clone了,想直接读取,怎么办?
public static Repository getRepositoryFromDir(String dir) throws IOException {
return new FileRepositoryBuilder()
.setGitDir(Paths.get(dir, ".git").toFile())
.build();
}
读取仓库日志
可以通过RevWalk读取仓库日志。
- revWalk.parseCommit 可读取一条commit
- 遍历revWalk,可读取所有日志
public static List<String> getLogs(Repository repository) throws IOException {
return getLogsSinceCommit(repository, null, null);
}
public static List<String> getLogsSinceCommit(Repository repository, String commit) throws IOException {
return getLogsSinceCommit(repository, null, commit);
}
public static List<String> getLogsSinceCommit(Repository repository, String branch, String commit) throws IOException {
if (branch == null) {
branch = repository.getBranch();
}
Ref head = repository.findRef("refs/heads/" + branch);
List<String> commits = new ArrayList<>();
if (head != null) {
try (RevWalk revWalk = new RevWalk(repository)) {
revWalk.markStart(revWalk.parseCommit(head.getObjectId()));
for (RevCommit revCommit : revWalk) {
if (revCommit.getId().getName().equals(commit)) {
break;
}
commits.add(revCommit.getFullMessage());
System.out.println("\nCommit-Message: " + revCommit.getFullMessage());
}
revWalk.dispose();
}
}
return commits;
}
测试
我们来先clone仓库,然后修改,最后push
String yaml = "dependencies:\n" +
"- name: springboot-rest-demo\n" +
" version: 0.0.5\n" +
" repository: http://hub.hubHOST.com/chartrepo/ainote\n" +
" alias: demo\n" +
"- name: exposecontroller\n" +
" version: 2.3.82\n" +
" repository: http://chartmuseum.jenkins-x.io\n" +
" alias: cleanup\n";
CredentialsProvider provider = createCredential("USR_NAME", "PASSWORD");
String cloneDir = "/tmp/test";
Git git = fromCloneRepository("http://gitlab.GITHOST.cn/datahub/env-test.git", cloneDir, provider);
// 修改文件
FileUtils.writeStringToFile(Paths.get(cloneDir, "env", "requirements.yaml").toFile(), yaml, "utf-8");
// 提交
commit(git, "deploy(app): deploy springboot-rest-demo:0.0.5 to env test", provider);
// push 到远程仓库
push(git, "master", provider);
git.clean().call();
git.close();
FileUtils.deleteDirectory(new File(cloneDir));
读取已有仓库的日志:
Repository repository = getRepositoryFromDir("GIT_DIR");
List<String> logs = getLogs(repository);
System.out.println(logs);
RevCommit head = getLastCommit(repository);
System.out.println(head.getFullMessage());
小结
本文讲述了如何通过jgit完成常规的git操作。
作者:Jadepeng
出处:jqpeng的技术记事本--http://www.cnblogs.com/xiaoqi
您的支持是对博主最大的鼓励,感谢您的认真阅读。
本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
JAVA 使用jgit管理git仓库的更多相关文章
- 多人合作项目如何去管理git仓库
前记:在git之前依稀记得有SVN去管理代码仓库,现在多用git去管理我们的代码:现在一般的项目大多数是多人同时开发,这样就会存在一个问题就是如何去协调开发:这也是lz当前使用git开发管理的些许经验 ...
- 使用linux安装gitolite管理git
系统:centos7 服务器:阿里云 一.前期准备 1.安装git yum install git 2.安装perl yum install perl 3.安装openssh yum install ...
- 流程自动化RPA,Power Automate Desktop系列 - 批量备份Git仓库做好灾备
一.背景 打个比如,你在Github上的代码库需要批量的定时备案到本地的Gitlab上,以便Github不能访问时,可以继续编写,这时候我们可以基于Power Automate Desktop来实现一 ...
- github仓库主页介绍、用git管理本地仓库和github仓库、搭建网站
github仓库主页介绍 名词解释: 工作区: 添加.编辑.修改文件等动作 暂存区: 暂存已经修改的文件,最后统一提交到git中 git(仓库): 最终确定的文件保存到仓库,成为一个新的版本,并且对他 ...
- Git仓库分支管理
#前提条件:#一.使用命令“cd /d/BranchMgr”进入到需要进行分支管理的仓库的目录,“/d/BranchMgr”是仓库路径.如下图: ”Administrator@DESKTOP-VL6G ...
- 【前端开发环境】前端使用GIT管理代码仓库需要掌握的几个必备技巧和知识点总结
1. Git的三种状态 已提交 committed 已暂存 staged 已修改 modified 2. Git的三个区域 Git仓库 是 Git 用来保存项目的元数据和对象数据库的地方. 这是 Gi ...
- git注册到git管理远程仓库
注册: ① 注册github网站:地址:https://github.com/,其中sign up 是注册,sign in是登录 (如果是用QQ邮箱的话,如果觉得收不到邮箱,可能是在垃圾箱哦) ② 之 ...
- 6. Git管理远程仓库
6. Git管理远程仓库 使用远程仓库的目的 作用:备份,实现代码共享集中化管理 Git克隆操作 目的 将远程仓库(github对应的项目)复制到本地 代码 git clone 仓库地址 多学一招:仓 ...
- Git初始化本地仓库及管理远程仓库github
1.首先在本地安装git,地址:https://git-scm.com/downloads.下载安装好git工具. 2.将自己在github上的注册的用户名和邮箱写入本地git的配置文件中: (1). ...
随机推荐
- 安卓手机运行fedora
安卓手机使用容器运行其他linux,一般两种: 1. termux + rootfs.img + proot,依赖api>=21,不必root但受限. 2. linuxdeploy + proo ...
- 函数式接口的使用 (Function、Predicate、Supplier、Consumer)
参考:https://blog.csdn.net/jmj18756235518/article/details/81490966 函数式接口 定义:有且只有一个抽象方法的接口 Function< ...
- [ch02-03] 梯度下降
系列博客,原文在笔者所维护的github上:https://aka.ms/beginnerAI, 点击star加星不要吝啬,星越多笔者越努力. 2.3 梯度下降 2.3.1 从自然现象中理解梯度下降 ...
- 【故障公告】数据库服务器 CPU 近 100% 引发的故障
抱歉,今天上午 10:48 ~ 10:33 期间,我们所使用的数据库服务(阿里云 RDS 实例 SQL Server 2016 标准版)又出现了 CPU 近 100% 问题,由此给您带来麻烦,请您谅解 ...
- nginx支持https配置
nginx证书 nginx.conf配置.
- linux字符集修改
首先介绍一下变量. 1.变量类型:本地变量.环境变量.局部变量.特殊变量(内置).参数变量.只读变量. 2.bash的配置文件:profile类和bashrc类 profile类:为交互式登录的she ...
- 了解HTTP协议,这一篇就够了
HTTP(Hyper Text Transfer Protocol:超文本传输协议)是一个基于请求与响应模式的.无状态的.应用层的协议,常基于TCP的连接方式,HTTP1.1版本中给出一种持续连接的 ...
- tensorflow:模型的保存和训练过程可视化
在使用tf来训练模型的时候,难免会出现中断的情况.这时候自然就希望能够将辛辛苦苦得到的中间参数保留下来,不然下次又要重新开始. 保存模型的方法: #之前是各种构建模型graph的操作(矩阵相乘,sig ...
- Rust入坑指南:鳞次栉比
很久没有挖Rust的坑啦,今天来挖一些排列整齐的坑.没错,就是要介绍一些集合类型的数据类型."鳞次栉比"这个标题是不是显得很有文化? 在Rust入坑指南:常规套路一文中我们已经介绍 ...
- CNCF官方大使张磊:什么是云原生?
作者|张磊 阿里云容器平台高级技术专家,CNCF 官方大使 编者说: 从 2015 年 Google 牵头成立 CNCF 以来,云原生技术开始进入公众的视线并取得快速的发展,到 2018 年包括 Go ...