我正在尝试从头开始创建一个 InMemoryGitRepository。最终,我想尝试自定义 DFSRepository 作为 git 后端,但首先我正在尝试 InMemoryRepository 的默认实现。我知道如何将现有存储库克隆到 InMemoryRepository 中,如here所述,但我在如何从头开始创建存储库并添加文件方面遇到了困难。我正在尝试以下
private static void initInMemoryGit() throws IOException, GitAPIException {
DfsRepositoryDescription repoDesc = new DfsRepositoryDescription("test");
//InMemoryRepository repo = new InMemoryRepository(repoDesc);
InMemoryRepository repo = new InMemoryRepository.Builder().setRepositoryDescription(repoDesc)
.setInitialBranch("master")
.build();
repo.create();
Git git = new Git(repo);
File textFile = new File("/tmp/TestGitRepository", "test.txt");
Files.write(textFile.toPath(), "hi".getBytes());
git.add().addFilepattern(textFile.getName()).call();
git.commit().setMessage("hi").call();
}
但是我收到以下错误
Exception in thread "main" org.eclipse.jgit.errors.NoWorkTreeException: Bare Repository has neither a working tree, nor an index
at org.eclipse.jgit.lib.Repository.getIndexFile(Repository.java:1200)
at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:259)
at org.eclipse.jgit.lib.Repository.lockDirCache(Repository.java:1282)
at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:122)
at oracle.bi.versioncontrol.jgit.JGitVersionInMemory.initInMemoryGit(JGitVersionInMemory.java:114)
at oracle.bi.versioncontrol.jgit.JGitVersionInMemory.main(JGitVersionInMemory.java:51)
由于它是内存存储库,我不应该设置索引文件或工作树文件,但看起来这就是错误消息所说的内容。我错过了什么?
默认情况下,静态嵌套类
InMemoryRepository.Builder
构建一个裸存储库。这也让我很头疼,但是如果你调用 repo.isBare()
,你可以看到它实际上返回 true,即使在构建过程中没有调用 setBare()
。
Git.init()
创建一个新的非裸存储库。
public static void initInMemoryGit() throws IOException, GitAPIException {
File textFile = new File("./tmp/TestGitRepository/test.txt");
try (Git git = Git.init().setInitialBranch("master").setDirectory(new File("./tmp/TestGitRepository")).call()) {
git.add().addFilepattern(textFile.getName()).call();
git.commit().setMessage("hi").call();
}
}