Java Code Examples for org.eclipse.jgit.transport.PushResult#getRemoteUpdates()

The following examples show how to use org.eclipse.jgit.transport.PushResult#getRemoteUpdates() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitMergeUtil.java    From MergeProcessor with Apache License 2.0 6 votes vote down vote up
/**
 * {@code git push}
 */
private void push() {
	try {
		final Iterable<PushResult> resultIterable = repo.push().call();
		for (final PushResult pushResult : resultIterable) {
			for (RemoteRefUpdate refUpdate : pushResult.getRemoteUpdates()) {
				if (refUpdate.getStatus() != RemoteRefUpdate.Status.OK) {
					// Push was rejected
					exception = new MergeUnitException(String
							.format("Could not push the local repository: '%s'", pushResult.getMessages()));
					return;
				}
			}
		}
	} catch (GitAPIException e) {
		exception = new MergeUnitException(String.format("Could not push the local repository '%s'.", repo), e); //$NON-NLS-1$
	}
}
 
Example 2
Source File: GitConfigurationPersister.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public String publish(String name) throws ConfigurationPersistenceException {
    StringBuilder message = new StringBuilder();
    String remoteName = gitRepository.getRemoteName(name);
    if (remoteName != null && gitRepository.isValidRemoteName(remoteName)) {
        try (Git git = gitRepository.getGit()) {
            Iterable<PushResult> result = git.push().setRemote(remoteName)
                    .setRefSpecs(new RefSpec(gitRepository.getBranch() + ':' + gitRepository.getBranch()))
                    .setPushTags().call();
            for (PushResult pushResult : result) {
                for (RemoteRefUpdate refUpdate : pushResult.getRemoteUpdates()) {
                    message.append(refUpdate.getMessage()).append(" ").append(refUpdate.getNewObjectId().name()).append('\n');
                }
            }
        } catch (GitAPIException ex) {
            throw MGMT_OP_LOGGER.failedToPublishConfiguration(ex, name, ex.getMessage());
        }
    }
    return message.toString();
}
 
Example 3
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 *  Attempts to push to a non-existent branch to validate the user actually has push access
 *
 * @param repo local repository
 * @param remoteUrl git repo url
 * @param credential credential to use when accessing git
 */
public static void validatePushAccess(@Nonnull Repository repo, @Nonnull String remoteUrl, @Nullable StandardCredentials credential) throws GitException {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        // we need to perform an actual push, so we try a deletion of a very-unlikely-to-exist branch
        // which needs to have push permissions in order to get a 'branch not found' message
        String pushSpec = ":this-branch-is-only-to-test-if-jenkins-has-push-access";
        PushCommand pushCommand = git.push();

        addCredential(repo, pushCommand, credential);

        Iterable<PushResult> resultIterable = pushCommand
            .setRefSpecs(new RefSpec(pushSpec))
            .setRemote(remoteUrl)
            .setDryRun(true) // we only want to test
            .call();
        PushResult result = resultIterable.iterator().next();
        if (result.getRemoteUpdates().isEmpty()) {
            System.out.println("No remote updates occurred");
        } else {
            for (RemoteRefUpdate update : result.getRemoteUpdates()) {
                if (!RemoteRefUpdate.Status.NON_EXISTING.equals(update.getStatus()) && !RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
                    throw new ServiceException.UnexpectedErrorException("Expected non-existent ref but got: " + update.getStatus().name() + ": " + update.getMessage());
                }
            }
        }
    } catch (GitAPIException e) {
        if (e.getMessage().toLowerCase().contains("auth")) {
            throw new ServiceException.UnauthorizedException(e.getMessage(), e);
        }
        throw new ServiceException.UnexpectedErrorException("Unable to access and push to: " + remoteUrl + " - " + e.getMessage(), e);
    }
}
 
Example 4
Source File: GitUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public static void push(String remoteUrl, Repository repo, StandardCredentials credential, String localBranchRef, String remoteBranchRef) {
    try (org.eclipse.jgit.api.Git git = new org.eclipse.jgit.api.Git(repo)) {
        String pushSpec = "+" + localBranchRef + ":" + remoteBranchRef;
        PushCommand pushCommand = git.push();

        addCredential(repo, pushCommand, credential);

        Iterable<PushResult> resultIterable = pushCommand
            .setRefSpecs(new RefSpec(pushSpec))
            .setRemote(remoteUrl)
            .call();
        PushResult result = resultIterable.iterator().next();
        if (result.getRemoteUpdates().isEmpty()) {
            throw new RuntimeException("No remote updates occurred");
        } else {
            for (RemoteRefUpdate update : result.getRemoteUpdates()) {
                if (!RemoteRefUpdate.Status.OK.equals(update.getStatus())) {
                    throw new ServiceException.UnexpectedErrorException("Remote update failed: " + update.getStatus().name() + ": " + update.getMessage());
                }
            }
        }
    } catch (GitAPIException e) {
        if (e.getMessage().toLowerCase().contains("auth")) {
            throw new ServiceException.UnauthorizedException(e.getMessage(), e);
        }
        throw new ServiceException.UnexpectedErrorException("Unable to save and push to: " + remoteUrl + " - " + e.getMessage(), e);
    }
}
 
Example 5
Source File: PushJob.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
private IStatus doPush(IProgressMonitor monitor) throws IOException, CoreException, URISyntaxException, GitAPIException {
	ProgressMonitor gitMonitor = new EclipseGitProgressTransformer(monitor);
	// /git/remote/{remote}/{branch}/file/{path}
	File gitDir = GitUtils.getGitDir(path.removeFirstSegments(2));
	Repository db = null;
	JSONObject result = new JSONObject();
	try {
		db = FileRepositoryBuilder.create(gitDir);
		Git git = Git.wrap(db);

		PushCommand pushCommand = git.push();
		pushCommand.setProgressMonitor(gitMonitor);
		pushCommand.setTransportConfigCallback(new TransportConfigCallback() {
			@Override
			public void configure(Transport t) {
				credentials.setUri(t.getURI());
				if (t instanceof TransportHttp && cookie != null) {
					HashMap<String, String> map = new HashMap<String, String>();
					map.put(GitConstants.KEY_COOKIE, cookie.getName() + "=" + cookie.getValue());
					((TransportHttp) t).setAdditionalHeaders(map);
				}
			}
		});
		RemoteConfig remoteConfig = new RemoteConfig(git.getRepository().getConfig(), remote);
		credentials.setUri(remoteConfig.getURIs().get(0));
		pushCommand.setCredentialsProvider(credentials);

		boolean pushToGerrit = branch.startsWith("for/");
		RefSpec spec = new RefSpec(srcRef + ':' + (pushToGerrit ? "refs/" : Constants.R_HEADS) + branch);
		pushCommand.setRemote(remote).setRefSpecs(spec);
		if (tags)
			pushCommand.setPushTags();
		pushCommand.setForce(force);
		Iterable<PushResult> resultIterable = pushCommand.call();
		if (monitor.isCanceled()) {
			return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
		}
		PushResult pushResult = resultIterable.iterator().next();
		boolean error = false;
		JSONArray updates = new JSONArray();
		result.put(GitConstants.KEY_COMMIT_MESSAGE, pushResult.getMessages());
		result.put(GitConstants.KEY_UPDATES, updates);
		for (final RemoteRefUpdate rru : pushResult.getRemoteUpdates()) {
			if (monitor.isCanceled()) {
				return new Status(IStatus.CANCEL, GitActivator.PI_GIT, "Cancelled");
			}
			final String rm = rru.getRemoteName();
			// check status only for branch given in the URL or tags
			if (branch.equals(Repository.shortenRefName(rm)) || rm.startsWith(Constants.R_TAGS) || rm.startsWith(Constants.R_REFS + "for/")) {
				JSONObject object = new JSONObject();
				RemoteRefUpdate.Status status = rru.getStatus();
				if (status != RemoteRefUpdate.Status.UP_TO_DATE || !rm.startsWith(Constants.R_TAGS)) {
					object.put(GitConstants.KEY_COMMIT_MESSAGE, rru.getMessage());
					object.put(GitConstants.KEY_RESULT, status.name());
					TrackingRefUpdate refUpdate = rru.getTrackingRefUpdate();
					if (refUpdate != null) {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
					} else {
						object.put(GitConstants.KEY_REMOTENAME, Repository.shortenRefName(rru.getSrcRef()));
						object.put(GitConstants.KEY_LOCALNAME, Repository.shortenRefName(rru.getRemoteName()));
					}
					updates.put(object);
				}
				if (status != RemoteRefUpdate.Status.OK && status != RemoteRefUpdate.Status.UP_TO_DATE)
					error = true;
			}
			// TODO: return results for all updated branches once push is available for remote, see bug 352202
		}
		// needs to handle multiple
		result.put("Severity", error ? "Error" : "Ok");
	} catch (JSONException e) {
	} finally {
		if (db != null) {
			db.close();
		}
	}
	return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}
 
Example 6
Source File: JGitOperator.java    From verigreen with Apache License 2.0 4 votes vote down vote up
@Override
public boolean push(String sourceBranch, String destinationBranch) {
       
       PushCommand command = _git.push();
       boolean ret = true;
       RefSpec refSpec = new RefSpec().setSourceDestination(sourceBranch, destinationBranch);
       command.setRefSpecs(refSpec);
       try {
       	List<Ref> remoteBranches = _git.branchList().setListMode(ListMode.REMOTE).call();
           if(_cp != null)
               command.setCredentialsProvider(_cp);
           Iterable<PushResult> results = command.call();
           for (PushResult pushResult : results) {
           	Collection<RemoteRefUpdate> resultsCollection = pushResult.getRemoteUpdates();
           	Map<PushResult,RemoteRefUpdate> resultsMap = new HashMap<>();
           	for(RemoteRefUpdate remoteRefUpdate : resultsCollection)
           	{
           		resultsMap.put(pushResult, remoteRefUpdate);
           	}
           	
               RemoteRefUpdate remoteUpdate = pushResult.getRemoteUpdate(destinationBranch);
               if (remoteUpdate != null) {
                   org.eclipse.jgit.transport.RemoteRefUpdate.Status status =
                           remoteUpdate.getStatus();
                   ret =
                           status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.OK)
                                   || status.equals(org.eclipse.jgit.transport.RemoteRefUpdate.Status.UP_TO_DATE);
               }
               
               if(remoteUpdate == null && !remoteBranches.toString().contains(destinationBranch))
               {	
            
               	
               	for(RemoteRefUpdate resultValue : resultsMap.values())
               	{
               		if(resultValue.toString().contains("REJECTED_OTHER_REASON"))
               		{
               			ret = false;
               		}
               	}
               }	
           }
       } catch (Throwable e) {
           throw new RuntimeException(String.format(
                   "Failed to push [%s] into [%s]",
                   sourceBranch,
                   destinationBranch), e);
       }
       
       return ret;
   }