I’ve recently worked on a project that used jgit to access configuration
files in repositories hosted on a GitHub. For various reasons we’re using
jgit
’s in-memory support with code that looks a little bit like
CloneRemoteRepositoryIntoMemoryAndReadFile.java
from jgit-cookbook:
= new DfsRepositoryDescription();
DfsRepositoryDescription repoDesc = new InMemoryRepository(repoDesc);
InMemoryRepository repo = new Git(repo);
Git git .fetch()
git.setRemote(REMOTE_URL)
.setRefSpecs(new RefSpec("+refs/heads/*:refs/heads/*"))
.call();
.getObjectDatabase();
repo= repo.resolve("refs/heads/" + BRANCH);
ObjectId lastCommitId = new RevWalk(repo);
RevWalk revWalk = revWalk.parseCommit(lastCommitId);
RevCommit commit = commit.getTree();
RevTree tree = new TreeWalk(repo);
TreeWalk treeWalk .addTree(tree);
treeWalk.setRecursive(true);
treeWalk.setFilter(PathFilter.create(FILE_TO_READ));
treeWalkif (!treeWalk.next()) {
return;
}
= treeWalk.getObjectId(0);
ObjectId objectId = repo.open(objectId);
ObjectLoader loader .copyTo(System.out); loader
This works more or less how you would expect when REMOTE_URL
is genuinely
remote (e.g. https://
or user@host:path
or similar) but results in
NullPointerExceptions
with a local repository (e.g. file://
, /path
,
etc.) We are using local repositories in our integration tests (so that we
don’t need to add yet more fragile, uninteresting network service mocking).
The problem is that Repository
subclasses use an instance of FS
to access
the local file system when required but InMemoryRepository
, for superficially
understandable reasons, leaves that field null
. If you want your
InMemoryRepository
to be able to operate with on-disk remotes, you need to
supply that FS
instance during construction:
= new DfsRepositoryDescription();
DfsRepositoryDescription repoDesc = new InMemoryRepository.Builder()
InMemoryRepository repo .setRepositoryDescription(repoDesc)
.setFS(FS.detect())
.build();
= new Git(repo); Git git
Then any subsequent operations on those Repository
or Git
objects that
that need to access the local file system will be able to do so (even though
the repository itself is in-memory).