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). ...
随机推荐
- firefox浏览器中使用vux的x-input报错TypeError: _this3.$refs.input.scrollIntoViewIfNeeded is not a function
最近做公众号项目,想着统一风格,所以决定使用vux. 在调试时发现,只要鼠标点击x-input输入框,就会报错 TypeError: _this3.$refs.input.scrollIntoView ...
- [ch02-03] 梯度下降
系列博客,原文在笔者所维护的github上:https://aka.ms/beginnerAI, 点击star加星不要吝啬,星越多笔者越努力. 2.3 梯度下降 2.3.1 从自然现象中理解梯度下降 ...
- python3基础之 字符串切片
一.python3中,可迭代对象有:列表.元组.字典.字符串:常结合for循环使用:均可使用索引切片 实例: str = ' #str[start:stop:step] 遵循[左闭右开]规则 prin ...
- 为什么 Redis 是单线程的?
以前一直有个误区,以为:高性能服务器 一定是 多线程来实现的 原因很简单因为误区二导致的:多线程 一定比 单线程 效率高.其实不然. 在说这个事前希望大家都能对 CPU . 内存 . 硬盘的速度都有了 ...
- 【原创】(十二)Linux内存管理之vmap与vmalloc
背景 Read the fucking source code! --By 鲁迅 A picture is worth a thousand words. --By 高尔基 说明: Kernel版本: ...
- linuxLVM
一.概念性的东西 LVM2:Logical Volume Manager ,Cersion 2 LVM,依赖于内核的dm模块(将一个或多个底层的设备组织成一个逻辑设备的模块).可以将多个物理分区通过软 ...
- vue通过控制boolean值来决定是否添加class类名
vue通过控制boolean值来决定是否添加class类名
- python网络爬虫之入门[一]
目录 前言 一.探讨什么是python网络爬虫? 二.一个针对于网络传输的抓包工具fiddler 三.学习request模块来爬取第一个网页 * 扩展内容(爬取top250的网页) 后记 @(目录) ...
- day20191006假期作业收尾
国庆作业:(轻重缓急,重点代码看懂理解了.每天重心就是代码,理解代码,理解,understand the code.花时间花功夫.只要功夫深,铁杵磨成针.) 一.使用DAO设计模式操作数据库CRUD( ...
- JS的引用顺序真的灰常重要
JS的引用一定要记得顺序,不然常常会被小小的问题卡住很久.