使用jgit clone远程代码
GitClone.java
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.api.CloneCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ListBranchCommand.ListMode;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.api.errors.InvalidRemoteException;
import org.eclipse.jgit.api.errors.TransportException;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider;
public class GitClone {
private static final String REMOTE_URL = "https://github.com/***/GitTest.git";
private static String login = "****@gmail.com";
private static String password = "123456";
public static Repository cloneRepository() throws IOException, InvalidRemoteException, TransportException, GitAPIException {
// prepare a new folder for the cloned repository
File localPath = new File("E:/temp/TestGitRepositorygithub");
System.out.println(localPath);
if (!localPath.exists() && !localPath.isDirectory()) {
localPath.mkdir();
}
localPath.delete();
// then clone .setBranchesToClone(Arrays.asList("refs/heads/master"))
System.out.println("Cloning from " + REMOTE_URL + " to " + localPath);
CloneCommand clone = Git.cloneRepository().setURI(REMOTE_URL).setDirectory(localPath);
if (REMOTE_URL.contains("ssh")) {
MySShSessionFactory myFactory = new MySShSessionFactory();
myFactory.setSshKeyFilePath("C:/id_rsa");
SshSessionFactory.setInstance(myFactory);
}
if (REMOTE_URL.toString().contains("http") || REMOTE_URL.toString().contains("https")) {
UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(login, password);
clone.setCredentialsProvider(user);
}
Git repo1 = clone.call();
for (Ref b : repo1.branchList().setListMode(ListMode.ALL).call())
System.out.println("(standard): cloned branch " + b.getName());
repo1.close();
// now open the created repository
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repository = builder.setGitDir(new File(localPath + "/.git")).readEnvironment()
// scan environment GIT_DIR
// GIT_WORK_TREE
// variables
.findGitDir() // scan up the file system tree
.build();
return repository;
}
}
Martin 于 4月24日
jgitclone 1 0