Jgit:Bare Repository既没有工作树,也没有索引

时间:2018-03-14 16:07:37

标签: java git jgit

我在E中创建了一个目录,命名为gitrepo full path is(E:\ gitrepo)之后我用以下代码克隆了一个存储库

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

请帮助我如何解决此异常

1 个答案:

答案 0 :(得分:6)

使用FileRepositoryBuilder打开Git存储库非常棘手。这是一个内部课程。其方法setGitDir(File)定义了存储库元数据的位置(.git文件夹)。换句话说,它用于构建Git裸存储库。您可以致电Repository#isBare()

来证明这一点
Repository repository = builder.setGitDir(new File("/E:/gitrepo"))
        .readEnvironment() // scan environment GIT_* variables
        .findGitDir() // scan up the file system tree
        .build();
repository.isBare(); // returns true

您应该Git#open(File)替换此用法:

try (Git git = Git.open(new File("/E:/gitrepo"))) {
    // Do sth ...
}