Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JGit push won't fail when push is impossible

Tags:

jgit

I'm trying to push a local repository to a github repository using JGit:

String remote = "https://[email protected]/me/foo";
Repository repository = buildLocalRepository();
try (Git git = new Git(repository)) {
  git.push()
      .setCredentialsProvider(new UsernamePasswordCredentialsProvider("token", ""))
      .setRemote(remote)
      .call();
}

But when the repository history on the remote is different (and consequently push is impossible) it neither fails nor touches the remote repository (fortunately). Any help? Thanks.

like image 206
Rad Avatar asked Oct 24 '25 14:10

Rad


2 Answers

It looks like you're expecting an exception to be thrown; according to the Javadoc, rejected refs do not constitute an exception. Instead, PushCommand.call() returns a list of PushResult objects, which you can inspect to see the status of each requested ref update.

like image 119
Mark Adelsberger Avatar answered Oct 27 '25 03:10

Mark Adelsberger


I found a code snippet that check the push results. It looks like this:

/*
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.PushResult;
import org.eclipse.jgit.transport.RemoteRefUpdate;
*/

String remote = "https://[email protected]/me/foo";
Repository repository = buildLocalRepository();
try (Git git = new Git(repository)) {
    Iterable<PushResult> results = git.push().call();
    for (PushResult result : results) {
        for(RemoteRefUpdate update : result.getRemoteUpdates()) {
            if(update.getStatus() != RemoteRefUpdate.Status.OK && update.getStatus() != RemoteRefUpdate.Status.UP_TO_DATE) {
                String error = "Push failed: "+ update.getStatus();
                throw new RuntimeException(error);
            }
        }
    }
}

My jbang script to test it.

like image 23
Jmini Avatar answered Oct 27 '25 03:10

Jmini