使用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;
    }
}

登录发表评论 注册

blue_cliff

感谢大佬,解决了我的问题

请叫我不土

楼主你好 我把您的代码粘过去运行后为啥报org.eclipse.jgit.errors.NotSupportedException 呢

新建主题 记录代码

学员动态

  • l**2添加了笔记:1、Integer是...
  • s**a完成了课程的作业
  • j**h评论了:您好 源码点击进去显...
反馈意见