想出了:
/**
* Create a repo at the specified directory or open one if it already
* exists. Return a {@link Git} object...
*
* @param p
* Path to the repo root (the dir that contains the .git folder)
* @return a "Git" object to run porcelain commands on...
* @throws GitterException
* if the specified path cannot be resolved to a directory, or
* the repository failed to be build (...) or created
*/
public static Git open(Path p) throws GitterException {
if (!Files.isDirectory(p)) // default LinkOption is follow links
throw new GitterException(p + " can't be resolved to a directory");
Repository localRepo = null;
try {
localRepo = new FileRepository(Paths.get(p.toString(), ".git")
.toFile()); // do I have to specify the .git folder ?
} catch (IOException e) {
throw new GitterException("Failed to build Repository instance", e);
}
try {
localRepo.create();
} catch (IllegalStateException e) {
// ISE when the repo exists !
} catch (IOException e) {
throw new GitterException("Failed to create Repository instance", e);
}
return new Git(localRepo);
}
Run Code Online (Sandbox Code Playgroud)
我错过了一些明显的东西吗 这样复杂吗?
跨setMustExist(布尔)在运行BaseRepositoryBuilder可以应用它呢?
我能找到的最短解决方案是始终调用create()并忽略已存在的异常.
static Git openOrCreate( File gitDirectory ) throws IOException {
Repository repository = new FileRepository( gitDirectory );
try {
repository.create();
} catch( IllegalStateException repositoryExists ) {
}
return new Git( repository );
}
Run Code Online (Sandbox Code Playgroud)
该代码有其警告.这IllegalStateException似乎是一个可能会改变并破坏上述代码的实现细节.此外,它FileRepository驻留在内部包中,不属于公共JGit API.
以下是避免这些问题的解决方案:
static Git openOrCreate( File gitDirectory ) throws IOException, GitAPIException {
Git git;
FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder();
repositoryBuilder.addCeilingDirectory( gitDirectory );
repositoryBuilder.findGitDir( gitDirectory );
if( repositoryBuilder.getGitDir() == null ) {
git = Git.init().setDirectory( gitDirectory.getParentFile() ).call();
} else {
git = new Git( repositoryBuilder.build() );
}
return git;
}
Run Code Online (Sandbox Code Playgroud)
请注意,省略了异常处理,以便专注于片段的实际用途.
setMustExist无法按需创建存储库.如果在指定位置找不到存储库,则只会导致build()提升RepositoryNotFoundException.
Repository表示存储库本身,而Git充当工厂来创建在其包装的存储库上运行的命令.旁边的工厂方法有close(),它只是委托给Repository.close().
存储库维护一个递减的使用计数器close().您可以在关闭后通过Git或Repository自己的方法继续使用存储库,但如有必要,它将重新打开.为避免泄漏文件句柄,您不应在关闭后使用存储库.
可以找到有关如何使用JGit访问和初始化存储库的深入讨论
这里:http://www.codeaffine.com/2014/09/22/access-git-repository-with-jgit/和
这里:http://www.codeaffine.com/2015/05/06/jgit-initialize-repository/