/** * Inspect the push returns to know if the push command has succeeded. * * @param call The push results object. * @return Returns <code>true</code> pushed, <code>false</code> otherwise. */ private static boolean isPushed(Iterable<PushResult> call) { for (PushResult pr : call) { Optional<RemoteRefUpdate> any = pr.getRemoteUpdates().stream() .filter(ru -> !(RemoteRefUpdate.Status.OK.equals(ru.getStatus()) || RemoteRefUpdate.Status.UP_TO_DATE.equals(ru.getStatus()))).findAny(); if (any.isPresent()) { return false; } } return true; }
/** * @inheritDoc */ @Override public Iterable<PushResult> push(Git git, String username, String password, String reference, String remote, boolean force) { UsernamePasswordCredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(username, password); try { Iterable<PushResult> results = git .push() .setCredentialsProvider(credentialsProvider) .add(reference) .setRemote(remote) .setForce(force) .call(); for(PushResult result : results){ RemoteRefUpdate update = result.getRemoteUpdate(reference); RemoteRefUpdate.Status status = update.getStatus(); if(!(status.equals(RemoteRefUpdate.Status.OK)||status.equals(RemoteRefUpdate.Status.UP_TO_DATE))){ throw new RuntimeException("Failed to push changes to origin"); } } return results; } catch (GitAPIException e) { throw new RuntimeException("Failed to push to origin", e); } }
@Override public void execute() throws GitException, InterruptedException { try (Repository repo = getRepository()) { RefSpec ref = (refspec != null) ? new RefSpec(fixRefSpec(repo)) : Transport.REFSPEC_PUSH_ALL; listener.getLogger().println("RefSpec is \""+ref+"\"."); Git g = git(repo); Config config = g.getRepository().getConfig(); config.setString("remote", "org_jenkinsci_plugins_gitclient_JGitAPIImpl", "url", remote.toPrivateASCIIString()); org.eclipse.jgit.api.PushCommand pc = g.push().setRemote("org_jenkinsci_plugins_gitclient_JGitAPIImpl").setRefSpecs(ref) .setProgressMonitor(new JGitProgressMonitor(listener)) .setCredentialsProvider(getProvider()) .setForce(force); if(tags) { pc.setPushTags(); } Iterable<PushResult> results = pc.call(); for(PushResult result:results) for(RemoteRefUpdate update:result.getRemoteUpdates()) { RemoteRefUpdate.Status status = update.getStatus(); if(!OK.equals(status)&&!UP_TO_DATE.equals(status)) { throw new GitException(update.getMessage() + " " + status + " for '" + ref + "' refspec '" + refspec + "' to " + remote.toPrivateASCIIString()); } } config.unset("remote", "org_jenkinsci_plugins_gitclient_JGitAPIImpl", "url"); } catch (IOException | JGitInternalException | GitAPIException e) { throw new GitException(e); } }