Java Jgit:裸存储库既没有工作树,也没有索引
我在E中创建了一个名为gitrepo的目录,完整路径为(E:\gitrepo),然后我用以下代码在其中克隆了一个存储库Java Jgit:裸存储库既没有工作树,也没有索引,java,git,jgit,Java,Git,Jgit,我在E中创建了一个名为gitrepo的目录,完整路径为(E:\gitrepo),然后我用以下代码在其中克隆了一个存储库 Git git=Git.cloneRepository() .setURI("samplelink.git") .setDirectory(new File("/E:/gitrepo")) .call(); 然后我用这段代码打开了一个存储库 public Repository op
Git git=Git.cloneRepository()
.setURI("samplelink.git")
.setDirectory(new File("/E:/gitrepo"))
.call();
然后我用这段代码打开了一个存储库
public Repository openRepository() throws IOException {
FileRepositoryBuilder builder = new FileRepositoryBuilder();
Repository repository = builder.setGitDir(new File("/E:/gitrepo"))
.readEnvironment() // scan environment GIT_* variables
.findGitDir() // scan up the file system tree
.build();
log.info("Repository directory is {}", repository.getDirectory());
return repository;
}
在这里之前一切都很顺利
然后我尝试在本地存储库中添加一个文件
Repository repo = openRepository();
Git git = new Git(repo);
File myfile = new File(repo.getDirectory()/*.getParent()*/, "testfile");
if (!myfile.createNewFile()) {
throw new IOException("Could not create file " + myfile);
}
log.info("file created at{}", myfile.getPath());
git.add().addFilepattern("testfile").call();
然后我在这条线上遇到了一个例外
git.add().addFilepattern("testfile").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:1147)
at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:294)
at org.eclipse.jgit.lib.Repository.lockDirCache(Repository.java:1205)
at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:149)
at com.km.GitAddFile.addFile(GitAddFile.java:26)
虽然文件代码是在E:\gitrepo
我已通过此命令检查gitrepo是否为非裸存储库
/e/gitrepo (master)
$ git rev-parse --is-bare-repository
并返回false
请帮助我如何解决此异常使用
FileRepositoryBuilder
打开Git存储库很棘手。这是一个内部类。它的方法setGitDir(File)
定义了存储库元数据的位置(即.git
文件夹)。换句话说,它用于构建Git裸存储库。您可以通过调用存储库#isBare()
来证明这一点:
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:1147)
at org.eclipse.jgit.dircache.DirCache.lock(DirCache.java:294)
at org.eclipse.jgit.lib.Repository.lockDirCache(Repository.java:1205)
at org.eclipse.jgit.api.AddCommand.call(AddCommand.java:149)
at com.km.GitAddFile.addFile(GitAddFile.java:26)
您应该将此用法替换为Git#open(File)
:
您确定
repo
指向的存储库与git rev parse--is bare repository
指向的存储库相同吗?在/e/gitrepo
中执行时,ls
显示了什么?repo.getDirectory()
指向什么?是的,repo指向/e/gitrepo,我正在运行git rev parse——是裸存储库,ls在/e/gitrepolog.info(“存储库目录为{}”,repository.getDirectory())中显示三个e文件README.md sample.txt testfile;输出->信息:存储库目录为E:\gitrepo使用FileRepositoryBuilder
不正确,您将其指向gitrepo
,而存储库元目录为gitrepo/.git
。你应该用Git.open(新文件(“/E:/gitrepo”)来代替这个用法。它起作用了:)你可以把它作为答案发布,这样可能会帮助其他人。错误的想法是调用Git构造函数,你需要一个存储库,然后在构建存储库的文档中显示了OP方法。但是文档中没有提到Git.open。有点困惑。你的帖子帮我节省了很多时间,谢谢!
try (Git git = Git.open(new File("/E:/gitrepo"))) {
// Do sth ...
}