How do I do git push with JGit?

后端 未结 2 1466
闹比i
闹比i 2020-12-14 07:50

I\'m trying to build a Java application that allows users to use Git based repositories. I was able to do this from the command-line, using the following commands:



        
相关标签:
2条回答
  • 2020-12-14 08:32

    You will find in org.eclipse.jgit.test all the example you need:

    • RemoteconfigTest.java uses 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 illustrates various push scenario, using RemoteConfig.
      See testTrackingUpdate() for a complete example pushing an tracking a remote branch.
      Extracts:

      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 讨论(0)
  • 2020-12-14 08:41

    The easiest way is to use the JGit Porcelain API:

        Git git = Git.open(localPath); 
    
        // 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 讨论(0)
提交回复
热议问题