我已经在计算机上克隆了一个存储库。我希望创建一个Java程序,该程序在打开时拉入,在关闭时推入。
这是我启动JGit的方式:
auth = new UsernamePasswordCredentialsProvider("[username]", "[pass]");
git = Git.open(new File(path_to_git + "\\.git"));
git.checkout().setName("master").call();
git.pull().setCredentialsProvider(auth).call();
这在我第一次启动时有效,但是如果我关闭并重新打开程序,则会收到错误消息
Exception in thread "JavaFX Application Thread" Exception in thread "main" java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplicationWithArgs$2(LauncherImpl.java:352)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsupportedOperationException: Cannot check out from unborn branch
at org.eclipse.jgit.api.CheckoutCommand.call(CheckoutCommand.java:235)
at com.company.app.Main.<clinit>(Main.java:59)
... 11 more
程序关闭时,我调用函数pushToGit()定义为:
public static void pushToGit() {
try {
git.remoteAdd()
.setName("origin")
.setUri(new URIish("https://github.com/[username]/[repo]"))
.call();
git.commit().setMessage("from database application").setAuthor(new PersonIdent("[name]","[email]")).call();
git.push().setCredentialsProvider(auth).call();
} catch (GitAPIException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
[每当我运行程序时,我都需要删除本地存储库并重新克隆它。
您可以尝试使用以下示例代码段。
Git git = Git.cloneRepository()
.setURI( "https://github.com/someRepoName" )
.setDirectory( "/path/to/repo" )
.setBranch( "refs/heads/master" )
.call();
您可以在下面的链接中获取更多详细信息。https://www.codeaffine.com/2015/11/30/jgit-clone-repository/
在更高版本的Jgit api中,您可以使用CloneCommand
,可以在链接下面进行检查。
https://www.programcreek.com/java-api-examples/?api=org.eclipse.jgit.api.CloneCommand
尝试使用Git.open:
public static Git openOrInit(Path repoPath) throws IOException, GitAPIException {
Git git;
try {
git = Git.open(repoPath.toFile());
} catch (RepositoryNotFoundException e) {
log.warn("Git repository may not exist, we will try to initialize an empty repository", e);
git = Git.init().setDirectory(repoPath.toFile()).call();
}
return git;
}
您可以在这里找到其他不错的示例:http://apisonar.com/java-examples/org.eclipse.jgit.api.Git.open.html