i have created a directory in E named it gitrepo full path is (E:\gitrepo) after then i have cloned a repository in it with the following code
Git git=Git.cloneRepository()
.setURI("samplelink.git")
.setDirectory(new File("/E:/gitrepo"))
.call();
then i opened a repository using this code
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;
}
everything worked fine till here then i tried to add a file in this local 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();
Then i got exception on this line
git.add().addFilepattern("testfile").call();
here is the exception
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)
although the file code created in E:\gitrepo
i have checked gitrepo is non-bare-repository by this command
/e/gitrepo (master)
$ git rev-parse --is-bare-repository
and its returning false
please help how can i resolve this exception
Opening a Git repository using FileRepositoryBuilder
is tricky. This is an internal class. Its method setGitDir(File)
defines the location of the repository metadata (the .git
folder). In other words, it is used to construct a Git bare repository. You can prove it by calling the 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
You should replace this usage by Git#open(File)
:
try (Git git = Git.open(new File("/E:/gitrepo"))) {
// Do sth ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With