最近设计基于gitops新的CICD方案,需要通过java读写git仓库,这里简单记录下。
在jgit中,存在最核心的三个组件:Git类,Repository类。Git类中包含了push commit之类的常见git操作,而Repository则实现了仓库的初始化和基本的管理功能。
Git类的实例都会持有一个Repository实例。
Repository类的初始化
针对一个git仓库,我们一般会有三种方式获得
1.新建一个空仓库
Git git = Git.init().setDirectory(localPath).call()
2.加载一个已存在的仓库
Repository repository = builder.setGitDir(repoDir)
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build()
3.从远程仓库下载
Git result = Git.cloneRepository()
.setURI(REMOTE_URL)
.setDirectory(localPath)
.call()
JGit是一款pure java的软件包,可以读写git仓库,下面介绍基本使用。
引入jgit#

maven引入:
<!-- jgit -->
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>5.8.0.202006091008-r</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</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 GitAPIExce

最低0.47元/天 解锁文章
976

被折叠的 条评论
为什么被折叠?



