我正在使用Java中的jGit,我已经设法克隆了整个存储库。但我找不到在存储库中下载单个文件的方法。我试过了:
他们都没有工作。
我的代码(克隆整个存储库)如下:
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();
}
}
}
如何更改下载单个文件?
答案 0 :(得分:2)
您只需要遍历文件树即可找到所需的文件 这是一个代码示例
// 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;