如何使用jGit克隆单个文件? [英] How to clone a single file with jGit?

查看:472
本文介绍了如何使用jGit克隆单个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working with jGit in Java and I have managed to clone an entire repository. But I can not find a way to download a single file inside a repository. I have tried:

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

他们都不起作用.

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

My code (clone whole repository) is as follows:

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();
        }
    }
}

如何更改下载单个文件?

How could it be changed to download a single file?

推荐答案

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

you just need to walk the file tree to find file you need Here is a code sample

// 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;

这篇关于如何使用jGit克隆单个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆