获取远程地址的存储库对象

时间:2019-01-05 14:54:09

标签: java git jgit

我尝试使用以下代码通过JGit从URL地址获取Repository对象:

Repository repository = Git.lsRemoteRepository()
    .setHeads(true)
    .setTags(true)
    .setRemote(url)
    .setCredentialsProvider(credentials)
    .getRepository();

但是,使用该代码,repositorynull。另一方面,使用此代码

Collection<Ref> refs = Git.lsRemoteRepository()
    .setHeads(true)
    .setTags(true)
    .setRemote(urlString)
    .setCredentialsProvider(credentials)
    .call();

可以获得Ref对象的集合,该方法似乎适用于远程URL。

我可以从Ref对象获得Repository对象吗?如何从Ref对象开始查找文件?

2 个答案:

答案 0 :(得分:1)

尝试一下:

String repoUrl = "https://github.com/GovindParashar136/SpringBootWithRestOpenIdClientAuthentication.git";
String cloneDirectoryPath = "/path/to/directory/"; // Ex.in windows c:\\gitProjects\SpringBootWithRestOpenIdClientAuthentication\
try {
    System.out.println("Cloning "+repoUrl+" into "+repoUrl);
    Git.cloneRepository()
        .setURI(repoUrl)
        .setDirectory(Paths.get(cloneDirectoryPath).toFile())
        .setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", "password"))
        .call();
    System.out.println("Completed Cloning");
} catch (GitAPIException e) {
    System.out.println("Exception occurred while cloning repo");
    e.printStackTrace();
}

答案 1 :(得分:1)

JGit的Repository类表示本地存储库,通常是远程存储库的克隆。

LsRemoteCommand返回的Git::lsRemoteRepository在本地存储库的上下文之外运行,因此为null返回getRepository

JGit中的Ref也没有对存储库的引用,因为它们可能源自无本地表示形式的存储库。请记住,例如,LsRemoteCommand返回的引用没有本地存储库。

要对存储库执行任何有用的操作,需要先将其克隆。例如,使用:

Git git = Git.cloneRepository().setURI(url).call();
// do something with repository, access to repository through git.getRepostory()
git.close();

该代码等效于git clone <url>。如果url为https://host.org/repo.git,则该命令将在当前工作目录的repo子目录中创建一个克隆。

有关使用JGit克隆存储库的更多详细信息,请参见:https://www.codeaffine.com/2015/11/30/jgit-clone-repository/