【问题标题】:How to clone a single file with jGit?如何使用 jGit 克隆单个文件?
【发布时间】:2018-07-15 03:25:58
【问题描述】:

我正在使用 Java 中的 jGit,并且我设法克隆了整个存储库。但是我找不到在存储库中下载单个文件的方法。我试过了:

  • 更改指定文件路径的 URL。
  • 通过指定子目录更改 URL。

他们都没有工作。

我的代码(克隆整个仓库)如下:

public File cloneRepository(String url, String path) throws GitAPIException {

    File download = new File (path);
    if (download.exists()){
        System.out.println("Error");
        return null;
    }
    else{
        CloneCommand clone = Git.cloneRepository()      
                .setURI(url)
                .setDirectory(download);
        try (Git repositorio = clone.call()) {
            return repositorio.getRepository().getWorkTree();
        }
    }
}

如何更改为下载单个文件?

【问题讨论】:

  • 您用“github”标记了您的问题,这是否意味着您想知道 github 上的存储库?因为您不需要 jgit,所以 URL/URLConnection 可以为您处理它。否则,如果存储库上没有 Web 界面,那就很难了。查看stackoverflow.com/questions/1125476/…
  • 我知道存储库。但我想用 jGit 来做
  • @user5872256 Erwin 在问你为什么你放了 github 标签。仅使用对您的问题真正重要的标签。记录一下:您了解克隆存储库基本上意味着下载完整内容吗? git not 像 SVN 一样,您可以(轻松地)进行稀疏检出并最终只得到 一个 单个文件(总是有一个 .git 目录,其中包含您的 完整存储库)。
  • 您接受了一个看起来像(在我的手机上,因此无法验证)的答案,它克隆并下载了整个存储库,然后为您提供了其中单个文件的内容 - 让我知道是否我错了。如果这是真的,那并不能回答您关于仅下载单个文件的问题。

标签: java api github clone


【解决方案1】:

您只需要遍历文件树即可找到您需要的文件 这是一个代码示例

// Clone remote repository
CloneCommand cloneCommand = Git.cloneRepository();
cloneCommand.setDirectory(localRepository.toFile());
cloneCommand.setBare(false);
cloneCommand.setURI(remoteRepository.toString());
cloneCommand.setTransportConfigCallback(transportConfigCallback);
Repository repository = cloneCommand.call().getRepository();
ObjectId ref = repository.resolve("your commit or branch");
// Resolve commit hash
RevWalk revWalk = new RevWalk(repository);
RevCommit revCommit = revWalk.parseCommit(ref);
Commit commit = new Commit(revCommit);
TreeWalk tree = new TreeWalk(repository);
tree.addTree(revCommit.getTree());
tree.setRecursive(true);
// Set path filter, to show files on matching path
tree.setFilter(PathFilter.create("path to file"));

try (ObjectReader objectReader = repository.newObjectReader()) {
    while (tree.next()) {
        String fileName = tree.getPathString();
        byte[] fileBytes = objectReader.open(tree.getObjectId(0)).getBytes();        
    }
}
return paths;

【讨论】:

  • 这不是第一步下载整个仓库吗?
  • 是的,它将所有存储库克隆到本地,然后使用本地 git 实体进行操作。
  • 我正在测试您的代码,但出现错误“构造函数 DepthWalk.Commit(AnyObjectId) 不可见”
  • 如果这实际上克隆了整个 repo,为什么会被接受?
  • 这几乎和实际结帐并从 FS 获取文件一样糟糕 :)
猜你喜欢
  • 2012-07-13
  • 2023-03-06
  • 2015-10-24
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-24
  • 2010-09-21
相关资源
最近更新 更多