Java 使用 JGit 执行 Git 命令
某些时候需要使用Java代码执行Git操作,可以使用JGit来实现。
<dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>4.9.3.201807311005-r</version> </dependency>
clone project
public static void main(String[] args) throws GitAPIException { Git git = Git.cloneRepository().setURI("xxx.git") .setCredentialsProvider(provide()) .call(); git.checkout() .setCreateBranch(true) .setName("your-branch") .call(); File file = git.getRepository().getDirectory(); String projectPath = file.getParent(); } private static UsernamePasswordCredentialsProvider provide() { return new UsernamePasswordCredentialsProvider(username, password); }
push project
private void pushFiles(GitlabProject project, File file) throws GitAPIException, URISyntaxException { Git git = Git.init().setDirectory(file).call(); RemoteAddCommand remoteAddCommand = git.remoteAdd(); remoteAddCommand.setName("origin"); remoteAddCommand.setUri(new URIish(project.getHttpUrl())); remoteAddCommand.call(); git.add().addFilepattern(".").call(); git.commit().setMessage("init").call(); git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)).call(); }