2012-11-19 590 views
14

我正在尝试构建一个允许用户使用基于Git的存储库的Java应用程序。我可以通过命令行执行此操作,使用下面的命令:如何用JGit做git push?

git init 
<create some files> 
git add . 
git commit 
git remote add <remote repository name> <remote repository URI> 
git push -u <remote repository name> master 

这让我创建,添加并提交内容我的本地库和内容推到远程存储库。 我现在正在尝试使用JGit在我的Java代码中执行相同的操作。我能够轻松完成git init,使用JGit API添加和提交。

Repository localRepo = new FileRepository(localPath); 
this.git = new Git(localRepo);   
localRepo.create(); 
git.add().addFilePattern(".").call(); 
git.commit().setMessage("test message").call(); 

再次,所有这些工作正常。我找不到git remote addgit push的任何示例或等效代码。我确实看过这个SO question

testPush()失败并显示错误消息TransportException: origin not found。在我见过的其他例子中https://gist.github.com/2487157git clone之前git push我不明白为什么这是必要的。

任何指向我如何做到这一点将不胜感激。

回答

13

您将在org.eclipse.jgit.test找到你需要的所有例子:

  • RemoteconfigTest.java使用Config

    config.setString("remote", "origin", "pushurl", "short:project.git"); 
    config.setString("url", "https://server/repos/", "name", "short:"); 
    RemoteConfig rc = new RemoteConfig(config, "origin"); 
    assertFalse(rc.getPushURIs().isEmpty()); 
    assertEquals("short:project.git", rc.getPushURIs().get(0).toASCIIString()); 
    
  • PushCommandTest.java说明了各种推的情况下,using RemoteConfig
    查看testTrackingUpdate()的完整示例推送跟踪远程分支。
    提取物:

    String trackingBranch = "refs/remotes/" + remote + "/master"; 
    RefUpdate trackingBranchRefUpdate = db.updateRef(trackingBranch); 
    trackingBranchRefUpdate.setNewObjectId(commit1.getId()); 
    trackingBranchRefUpdate.update(); 
    
    URIish uri = new URIish(db2.getDirectory().toURI().toURL()); 
    remoteConfig.addURI(uri); 
    remoteConfig.addFetchRefSpec(new RefSpec("+refs/heads/*:refs/remotes/" 
        + remote + "/*")); 
    remoteConfig.update(config); 
    config.save(); 
    
    
    RevCommit commit2 = git.commit().setMessage("Commit to push").call(); 
    
    RefSpec spec = new RefSpec(branch + ":" + branch); 
    Iterable<PushResult> resultIterable = git.push().setRemote(remote) 
        .setRefSpecs(spec).call(); 
    
+0

感谢您的投入。我确实看过PushCommandTest.java,但没有足够的理解使用它。我会尝试一下并给出更新。再次感谢。 –

+0

试过了,它效果很好!非常感谢你的帮助! –

4

最简单的方法是使用JGit瓷API:

Repository localRepo = new FileRepository(localPath); 
    Git git = new Git(localRepo); 

    // add remote repo: 
    RemoteAddCommand remoteAddCommand = git.remoteAdd(); 
    remoteAddCommand.setName("origin"); 
    remoteAddCommand.setUri(new URIish(httpUrl)); 
    // you can add more settings here if needed 
    remoteAddCommand.call(); 

    // push to remote: 
    PushCommand pushCommand = git.push(); 
    pushCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider("username", "password")); 
    // you can add more settings here if needed 
    pushCommand.call(); 
+0

我的(5岁)答案不错的选择。 +1 – VonC