Java uses jgit to manage git warehouse
Recently designed a new cicd scheme based on gitops. You need to read and write git warehouse through Java. Here is a simple record.
Jgit is a pure java software package that can read and write git warehouse. The basic use is described below.
Introducing jgit
Maven introduction:
<!-- 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 has a git class that can be used to perform regular git operations
Voucher management
Credentials are managed through the credentialsprovider. The commonly used is usernamepasswordcredentialsprovider
Initialize with the following code:
public static CredentialsProvider createCredential(String userName,String password) {
return new UsernamePasswordCredentialsProvider(userName,password);
}
Clone remote warehouse
Git command:
git clone {repoUrl}
Through GIT Clonerepository is a remote warehouse. If credentials are required, you need to specify the 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 command:
git commit -a -m '{msg}'
Commit is relatively simple. It corresponds to the commit method. Note that you need to add first
public static void commit(Git git,String message,CredentialsProvider provider) throws GitAPIException {
git.add().addFilepattern(".").call();
git.commit()
.setMessage(message)
.call();
}
push
Git command:
git push origin branchName
Push simply calls push, and credentialsprovider needs to be specified
public static void push(Git git,CredentialsProvider provider) throws GitAPIException,IOException {
push(git,null,provider);
}
public static void push(Git git,String branch,IOException {
if (branch == null) {
branch = git.getRepository().getBranch();
}
git.push()
.setCredentialsProvider(provider)
.setRemote("origin").setRefSpecs(new RefSpec(branch)).call();
}
Read existing warehouse
What if git has clone and wants to read directly?
public static Repository getRepositoryFromDir(String dir) throws IOException {
return new FileRepositoryBuilder()
.setGitDir(Paths.get(dir,".git").toFile())
.build();
}
Read warehouse log
You can read the warehouse log through revwalk.
public static List<String> getLogs(Repository repository) throws IOException {
return getLogsSinceCommit(repository,null);
}
public static List<String> getLogsSinceCommit(Repository repository,String commit) throws IOException {
return getLogsSinceCommit(repository,commit);
}
public static List<String> getLogsSinceCommit(Repository repository,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;
}
test
Let's first clone the warehouse, then modify it, and finally push it
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));
Read logs of existing warehouses:
Repository repository = getRepositoryFromDir("GIT_DIR");
List<String> logs = getLogs(repository);
System.out.println(logs);
RevCommit head = getLastCommit(repository);
System.out.println(head.getFullMessage());
Summary
This article describes how to complete conventional git operations through jgit.