基于Jgit 实现java 自动化操作 git 相关功能
2019-10-18
阅读 {{counts.readCount}}
评论 {{counts.commentCount}}
## 需求
通过java代码实现git的常用的操作
如`clone`、`add`、`commit`、`pull`、`push` 等
最终可以用于例如服务器生产环境中的部分静态文件一件同步
## 代码
```java
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.eclipse.jgit.api.AddCommand;
import org.eclipse.jgit.api.CommitCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullResult;
import org.eclipse.jgit.api.PushCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.transport.CredentialsProvider;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
/**
* java 操作 git
* 实现java自动化操作git 简单功能实现
* <p>
* 基于Jgit
* <dependency>
* <groupId>org.eclipse.jgit</groupId>
* <artifactId>org.eclipse.jgit</artifactId>
* <version>${jgit.version}</version>
* </dependency>
* <p>
* 代码参考
* https://www.jqhtml.com/26305.html
*/
public class GitUtils {
public static UsernamePasswordCredentialsProvider getCredentialsProvider(String gituser, String gitpasswd) {
UsernamePasswordCredentialsProvider credentialsProvider = null;
if (StringUtils.isNotEmpty(gituser) && StringUtils.isNotEmpty(gitpasswd)) {
credentialsProvider = new UsernamePasswordCredentialsProvider(gituser, gitpasswd);
}
return credentialsProvider;
}
public static void doInit(File gitDir) throws GitAPIException {
if (!gitDir.exists()) {
gitDir.mkdirs();
}
Git git = Git.init().setDirectory(gitDir).setBare(false).call();
}
public static void doClone(File gitDir, String gituri, CredentialsProvider credentialsProvider, String branch)
throws GitAPIException {
Git.cloneRepository().setURI(gituri)
.setCredentialsProvider(credentialsProvider)
.setDirectory(gitDir).setCloneAllBranches(false)
.setBranch(branch).call().close();
}
public static PullResult doPull(File gitDir, String url, CredentialsProvider credentialsProvider) throws IOException,
GitAPIException {
Git git = Git.open(gitDir);
return git.pull().setCredentialsProvider(credentialsProvider).call();
}
public static void doAdd(File gitDir, String... files)
throws GitAPIException, IOException {
try (Git git = Git.open(gitDir)) {
AddCommand add = git.add();
if (ArrayUtils.isEmpty(files)) {
add.addFilepattern(".");
} else {
for (String file : files) {
add.addFilepattern(file);
}
}
add.call();
}
}
public static void doCommit(File gitDir, String message) throws GitAPIException, IOException {
Git git = Git.open(gitDir);
CommitCommand commit = git.commit().setAll(false).setMessage(message);
commit.call();
}
public static Iterable<PushResult> doPush(File gitDir, CredentialsProvider credentialsProvider) throws IOException, GitAPIException {
Git git = Git.open(gitDir);
PushCommand push = git.push().setCredentialsProvider(credentialsProvider);
return push.call();
}
}
```