How to clone a single file with jGit?

不想你离开。 提交于 2019-12-23 01:37:10

问题


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:

  • Change the URL specifying the path of the file.
  • Change the URL by specifying a subdirectory.

Neither of them worked.

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?


回答1:


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;


来源:https://stackoverflow.com/questions/48619755/how-to-clone-a-single-file-with-jgit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!