Search in sources :

Example 1 with RemoteRefUpdate

use of org.eclipse.jgit.transport.RemoteRefUpdate in project che by eclipse.

the class JGitConnection method push.

@Override
public PushResponse push(PushParams params) throws GitException, UnauthorizedException {
    List<Map<String, String>> updates = new ArrayList<>();
    String currentBranch = getCurrentBranch();
    String remoteName = params.getRemote();
    String remoteUri = getRepository().getConfig().getString(ConfigConstants.CONFIG_REMOTE_SECTION, remoteName, ConfigConstants.CONFIG_KEY_URL);
    PushCommand pushCommand = getGit().push();
    if (params.getRemote() != null) {
        pushCommand.setRemote(remoteName);
    }
    List<String> refSpec = params.getRefSpec();
    if (!refSpec.isEmpty()) {
        pushCommand.setRefSpecs(refSpec.stream().map(RefSpec::new).collect(Collectors.toList()));
    }
    pushCommand.setForce(params.isForce());
    int timeout = params.getTimeout();
    if (timeout > 0) {
        pushCommand.setTimeout(timeout);
    }
    try {
        @SuppressWarnings("unchecked") Iterable<PushResult> pushResults = (Iterable<PushResult>) executeRemoteCommand(remoteUri, pushCommand, params.getUsername(), params.getPassword());
        PushResult pushResult = pushResults.iterator().next();
        String commandOutput = pushResult.getMessages().isEmpty() ? "Successfully pushed to " + remoteUri : pushResult.getMessages();
        Collection<RemoteRefUpdate> refUpdates = pushResult.getRemoteUpdates();
        for (RemoteRefUpdate remoteRefUpdate : refUpdates) {
            final String remoteRefName = remoteRefUpdate.getRemoteName();
            // check status only for branch given in the URL or tags - (handle special "refs/for" case)
            String shortenRefFor = remoteRefName.startsWith("refs/for/") ? remoteRefName.substring("refs/for/".length()) : remoteRefName;
            if (!currentBranch.equals(Repository.shortenRefName(remoteRefName)) && !currentBranch.equals(shortenRefFor) && !remoteRefName.startsWith(Constants.R_TAGS)) {
                continue;
            }
            Map<String, String> update = new HashMap<>();
            RemoteRefUpdate.Status status = remoteRefUpdate.getStatus();
            if (status != RemoteRefUpdate.Status.OK) {
                List<String> refSpecs = params.getRefSpec();
                if (remoteRefUpdate.getStatus() == RemoteRefUpdate.Status.UP_TO_DATE) {
                    commandOutput = INFO_PUSH_IGNORED_UP_TO_DATE;
                } else {
                    String remoteBranch = !refSpecs.isEmpty() ? refSpecs.get(0).split(REFSPEC_COLON)[1] : "master";
                    String errorMessage = format(ERROR_PUSH_CONFLICTS_PRESENT, currentBranch + BRANCH_REFSPEC_SEPERATOR + remoteBranch, remoteUri);
                    if (remoteRefUpdate.getMessage() != null) {
                        errorMessage += "\nError errorMessage: " + remoteRefUpdate.getMessage() + ".";
                    }
                    throw new GitException(errorMessage);
                }
            }
            if (status != RemoteRefUpdate.Status.UP_TO_DATE || !remoteRefName.startsWith(Constants.R_TAGS)) {
                update.put(KEY_COMMIT_MESSAGE, remoteRefUpdate.getMessage());
                update.put(KEY_RESULT, status.name());
                TrackingRefUpdate refUpdate = remoteRefUpdate.getTrackingRefUpdate();
                if (refUpdate != null) {
                    update.put(KEY_REMOTENAME, Repository.shortenRefName(refUpdate.getLocalName()));
                    update.put(KEY_LOCALNAME, Repository.shortenRefName(refUpdate.getRemoteName()));
                } else {
                    update.put(KEY_REMOTENAME, Repository.shortenRefName(remoteRefUpdate.getSrcRef()));
                    update.put(KEY_LOCALNAME, Repository.shortenRefName(remoteRefUpdate.getRemoteName()));
                }
                updates.add(update);
            }
        }
        return newDto(PushResponse.class).withCommandOutput(commandOutput).withUpdates(updates);
    } catch (GitAPIException exception) {
        if ("origin: not found.".equals(exception.getMessage())) {
            throw new GitException(ERROR_NO_REMOTE_REPOSITORY, exception);
        } else {
            String message = generateExceptionMessage(exception);
            throw new GitException(message, exception);
        }
    }
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) HashMap(java.util.HashMap) GitException(org.eclipse.che.api.git.exception.GitException) ArrayList(java.util.ArrayList) PushResult(org.eclipse.jgit.transport.PushResult) TrackingRefUpdate(org.eclipse.jgit.transport.TrackingRefUpdate) PushCommand(org.eclipse.jgit.api.PushCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RefSpec(org.eclipse.jgit.transport.RefSpec) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 2 with RemoteRefUpdate

use of org.eclipse.jgit.transport.RemoteRefUpdate in project gerrit by GerritCodeReview.

the class PushTagIT method pushTagDeletion.

private void pushTagDeletion(TagType tagType, String tagName, Status expectedStatus) throws Exception {
    String tagRef = tagRef(tagName);
    PushResult r = deleteRef(testRepo, tagRef);
    RemoteRefUpdate refUpdate = r.getRemoteUpdate(tagRef);
    assertThat(refUpdate.getStatus()).named(tagType.name()).isEqualTo(expectedStatus);
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) PushResult(org.eclipse.jgit.transport.PushResult)

Example 3 with RemoteRefUpdate

use of org.eclipse.jgit.transport.RemoteRefUpdate in project fabric8 by jboss-fuse.

the class DefaultPullPushPolicy method doPush.

@Override
public synchronized PushPolicyResult doPush(GitContext context, CredentialsProvider credentialsProvider) {
    StoredConfig config = git.getRepository().getConfig();
    String remoteUrl = config.getString("remote", remoteRef, "url");
    if (remoteUrl == null) {
        LOGGER.debug("No remote repository defined, so not doing a push");
        return new AbstractPushPolicyResult();
    }
    LOGGER.info("Pushing last change to: {}", remoteUrl);
    Iterator<PushResult> resit = null;
    Exception lastException = null;
    try {
        // clean working copy before the push
        // to remove not-tracked files
        git.clean().setCleanDirectories(true).call();
        // for file permissions
        git.reset().setMode(ResetCommand.ResetType.MIXED).call();
        // for other changes
        git.reset().setMode(ResetCommand.ResetType.HARD).call();
        resit = git.push().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setPushTags().setPushAll().call().iterator();
    } catch (Exception ex) {
        lastException = ex;
    }
    // Allow the commit to stay in the repository in case of push failure
    if (lastException != null) {
        LOGGER.warn("Cannot push because of: " + lastException.toString(), lastException);
        return new AbstractPushPolicyResult(lastException);
    }
    List<PushResult> pushResults = new ArrayList<>();
    Map<String, RemoteBranchChange> acceptedUpdates = new TreeMap<>();
    Map<String, RemoteBranchChange> rejectedUpdates = new TreeMap<>();
    // Collect the updates that are not ok
    while (resit.hasNext()) {
        PushResult pushResult = resit.next();
        pushResults.add(pushResult);
        for (RemoteRefUpdate refUpdate : pushResult.getRemoteUpdates()) {
            Status status = refUpdate.getStatus();
            ObjectId from = refUpdate.getTrackingRefUpdate() == null || refUpdate.getTrackingRefUpdate().getOldObjectId() == null ? refUpdate.getExpectedOldObjectId() : refUpdate.getTrackingRefUpdate().getOldObjectId();
            ObjectId to = refUpdate.getTrackingRefUpdate() == null || refUpdate.getTrackingRefUpdate().getNewObjectId() == null ? refUpdate.getNewObjectId() : refUpdate.getTrackingRefUpdate().getNewObjectId();
            if (status == Status.OK) {
                acceptedUpdates.put(refUpdate.getSrcRef(), new RemoteBranchChange(refUpdate.getSrcRef(), refUpdate).updated(from, to, "fast-forward"));
            } else if (status == Status.UP_TO_DATE) {
                acceptedUpdates.put(refUpdate.getSrcRef(), new RemoteBranchChange(refUpdate.getSrcRef(), refUpdate));
            } else {
                switch(status) {
                    case REJECTED_NONFASTFORWARD:
                        // typical problem when repos are not synced
                        rejectedUpdates.put(refUpdate.getSrcRef(), new RemoteBranchChange(refUpdate.getSrcRef(), refUpdate).rejected(from, to, "non fast-forward update"));
                        break;
                    case NOT_ATTEMPTED:
                    case REJECTED_NODELETE:
                    case REJECTED_REMOTE_CHANGED:
                    case REJECTED_OTHER_REASON:
                    case NON_EXISTING:
                    case AWAITING_REPORT:
                    default:
                        // ?
                        rejectedUpdates.put(refUpdate.getSrcRef(), new RemoteBranchChange(refUpdate.getSrcRef(), refUpdate).rejected(from, to, status.toString()));
                        break;
                }
            }
        }
    }
    // Reset to the last known good rev and make the commit/push fail
    for (String rejectedRefName : rejectedUpdates.keySet()) {
        RemoteRefUpdate rejectedRef = rejectedUpdates.get(rejectedRefName).getRemoteRefUpdate();
        LOGGER.warn("Rejected push: {}. Attempting to recreate local branch.", rejectedRef);
        String refName = rejectedRef.getRemoteName();
        String branch = refName.substring(refName.lastIndexOf('/') + 1);
        try {
            GitHelpers.checkoutBranch(git, branch);
            FetchResult fetchResult = git.fetch().setTimeout(gitTimeout).setCredentialsProvider(credentialsProvider).setRemote(remoteRef).setRefSpecs(new RefSpec("refs/heads/" + branch)).call();
            Ref fetchRef = fetchResult.getAdvertisedRef("refs/heads/" + branch);
            git.branchRename().setOldName(branch).setNewName(branch + "-tmp").call();
            git.checkout().setCreateBranch(true).setName(branch).setStartPoint(fetchRef.getObjectId().getName()).call();
            git.branchDelete().setBranchNames(branch + "-tmp").setForce(true).call();
            LOGGER.info("Local branch {} recreated from {}", branch, fetchRef.toString());
        } catch (Exception ex) {
            LOGGER.warn("Cannot recreate branch " + branch + " because of: " + ex.toString(), ex);
        }
    }
    PushPolicyResult result = new AbstractPushPolicyResult(pushResults, acceptedUpdates, rejectedUpdates, null);
    LOGGER.info("Push result: {}", result);
    return result;
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) Status(org.eclipse.jgit.transport.RemoteRefUpdate.Status) MergeStatus(org.eclipse.jgit.api.MergeResult.MergeStatus) FetchResult(org.eclipse.jgit.transport.FetchResult) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) PushResult(org.eclipse.jgit.transport.PushResult) TreeMap(java.util.TreeMap) SocketTimeoutException(java.net.SocketTimeoutException) NoRemoteRepositoryException(org.eclipse.jgit.errors.NoRemoteRepositoryException) ConnectException(java.net.ConnectException) InvalidRemoteException(org.eclipse.jgit.api.errors.InvalidRemoteException) StoredConfig(org.eclipse.jgit.lib.StoredConfig) Ref(org.eclipse.jgit.lib.Ref) RefSpec(org.eclipse.jgit.transport.RefSpec)

Example 4 with RemoteRefUpdate

use of org.eclipse.jgit.transport.RemoteRefUpdate in project MGit by maks.

the class PushTask method pushRepo.

public boolean pushRepo() {
    Git git;
    try {
        git = mRepo.getGit();
    } catch (StopTaskException e1) {
        return false;
    }
    PushCommand pushCommand = git.push().setPushTags().setProgressMonitor(new BasicProgressMonitor()).setTransportConfigCallback(new SgitTransportCallback()).setRemote(mRemote);
    if (mPushAll) {
        pushCommand.setPushAll();
    } else {
        RefSpec spec = new RefSpec(mRepo.getBranchName());
        pushCommand.setRefSpecs(spec);
    }
    if (mForcePush) {
        pushCommand.setForce(true);
    }
    setCredentials(pushCommand);
    try {
        Iterable<PushResult> result = pushCommand.call();
        for (PushResult r : result) {
            Collection<RemoteRefUpdate> updates = r.getRemoteUpdates();
            for (RemoteRefUpdate update : updates) {
                parseRemoteRefUpdate(update);
            }
        }
    } catch (TransportException e) {
        setException(e);
        handleAuthError(this);
        return false;
    } catch (Exception e) {
        setException(e);
        return false;
    } catch (OutOfMemoryError e) {
        setException(e, R.string.error_out_of_memory);
        return false;
    } catch (Throwable e) {
        setException(e);
        return false;
    }
    return true;
}
Also used : RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) PushResult(org.eclipse.jgit.transport.PushResult) TransportException(org.eclipse.jgit.api.errors.TransportException) PushCommand(org.eclipse.jgit.api.PushCommand) TransportException(org.eclipse.jgit.api.errors.TransportException) StopTaskException(me.sheimi.sgit.exception.StopTaskException) SgitTransportCallback(me.sheimi.sgit.ssh.SgitTransportCallback) Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) StopTaskException(me.sheimi.sgit.exception.StopTaskException)

Example 5 with RemoteRefUpdate

use of org.eclipse.jgit.transport.RemoteRefUpdate in project egit by eclipse.

the class PushOperation method run.

/**
 * @param actMonitor
 *            may be <code>null</code> if progress monitoring is not desired
 * @throws InvocationTargetException
 *             not really used: failure is communicated via the result (see
 *             {@link #getOperationResult()})
 */
public void run(IProgressMonitor actMonitor) throws InvocationTargetException {
    if (operationResult != null)
        throw new IllegalStateException(CoreText.OperationAlreadyExecuted);
    if (this.specification != null)
        for (URIish uri : this.specification.getURIs()) {
            for (RemoteRefUpdate update : this.specification.getRefUpdates(uri)) if (update.getStatus() != Status.NOT_ATTEMPTED)
                throw new IllegalStateException(CoreText.RemoteRefUpdateCantBeReused);
        }
    final int totalWork;
    if (specification != null) {
        totalWork = specification.getURIsNumber();
    } else {
        totalWork = 1;
    }
    String taskName = dryRun ? CoreText.PushOperation_taskNameDryRun : CoreText.PushOperation_taskNameNormalRun;
    SubMonitor progress = SubMonitor.convert(actMonitor, totalWork);
    progress.setTaskName(taskName);
    operationResult = new PushOperationResult();
    try (Git git = new Git(localDb)) {
        if (specification != null)
            for (final URIish uri : specification.getURIs()) {
                if (progress.isCanceled()) {
                    operationResult.addOperationResult(uri, CoreText.PushOperation_resultCancelled);
                    progress.worked(1);
                    continue;
                }
                Collection<RemoteRefUpdate> refUpdates = specification.getRefUpdates(uri);
                final EclipseGitProgressTransformer gitSubMonitor = new EclipseGitProgressTransformer(progress.newChild(1));
                try (Transport transport = Transport.open(localDb, uri)) {
                    transport.setDryRun(dryRun);
                    transport.setTimeout(timeout);
                    if (credentialsProvider != null) {
                        transport.setCredentialsProvider(credentialsProvider);
                    }
                    PushResult result = transport.push(gitSubMonitor, refUpdates, out);
                    operationResult.addOperationResult(result.getURI(), result);
                    specification.addURIRefUpdates(result.getURI(), result.getRemoteUpdates());
                } catch (JGitInternalException e) {
                    String errorMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
                    String userMessage = NLS.bind(CoreText.PushOperation_InternalExceptionOccurredMessage, errorMessage);
                    handleException(uri, e, userMessage);
                } catch (Exception e) {
                    handleException(uri, e, e.getMessage());
                }
            }
        else {
            final EclipseGitProgressTransformer gitMonitor = new EclipseGitProgressTransformer(progress.newChild(totalWork));
            try {
                Iterable<PushResult> results = git.push().setRemote(remoteName).setDryRun(dryRun).setTimeout(timeout).setProgressMonitor(gitMonitor).setCredentialsProvider(credentialsProvider).setOutputStream(out).call();
                for (PushResult result : results) {
                    operationResult.addOperationResult(result.getURI(), result);
                }
            } catch (JGitInternalException e) {
                String errorMessage = e.getCause() != null ? e.getCause().getMessage() : e.getMessage();
                String userMessage = NLS.bind(CoreText.PushOperation_InternalExceptionOccurredMessage, errorMessage);
                URIish uri = getPushURIForErrorHandling();
                handleException(uri, e, userMessage);
            } catch (Exception e) {
                URIish uri = getPushURIForErrorHandling();
                handleException(uri, e, e.getMessage());
            }
        }
    }
}
Also used : URIish(org.eclipse.jgit.transport.URIish) RemoteRefUpdate(org.eclipse.jgit.transport.RemoteRefUpdate) SubMonitor(org.eclipse.core.runtime.SubMonitor) EclipseGitProgressTransformer(org.eclipse.egit.core.EclipseGitProgressTransformer) PushResult(org.eclipse.jgit.transport.PushResult) URISyntaxException(java.net.URISyntaxException) InvocationTargetException(java.lang.reflect.InvocationTargetException) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) Git(org.eclipse.jgit.api.Git) Collection(java.util.Collection) JGitInternalException(org.eclipse.jgit.api.errors.JGitInternalException) Transport(org.eclipse.jgit.transport.Transport)

Aggregations

RemoteRefUpdate (org.eclipse.jgit.transport.RemoteRefUpdate)58 PushResult (org.eclipse.jgit.transport.PushResult)43 Test (org.junit.Test)19 File (java.io.File)15 Git (org.eclipse.jgit.api.Git)15 CloneCommand (org.eclipse.jgit.api.CloneCommand)14 URIish (org.eclipse.jgit.transport.URIish)13 BufferedWriter (java.io.BufferedWriter)11 FileOutputStream (java.io.FileOutputStream)11 OutputStreamWriter (java.io.OutputStreamWriter)11 Date (java.util.Date)11 RefSpec (org.eclipse.jgit.transport.RefSpec)11 RepositoryModel (com.gitblit.models.RepositoryModel)10 RevCommit (org.eclipse.jgit.revwalk.RevCommit)10 UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)10 PushOperationSpecification (org.eclipse.egit.core.op.PushOperationSpecification)9 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)8 ArrayList (java.util.ArrayList)8 PushOperation (org.eclipse.egit.core.op.PushOperation)7 IOException (java.io.IOException)6