PushProcess.java

  1. /*
  2.  * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com> and others
  3.  *
  4.  * This program and the accompanying materials are made available under the
  5.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  6.  * https://www.eclipse.org/org/documents/edl-v10.php.
  7.  *
  8.  * SPDX-License-Identifier: BSD-3-Clause
  9.  */

  10. package org.eclipse.jgit.transport;

  11. import java.io.IOException;
  12. import java.io.OutputStream;
  13. import java.text.MessageFormat;
  14. import java.util.Collection;
  15. import java.util.Collections;
  16. import java.util.LinkedHashMap;
  17. import java.util.List;
  18. import java.util.Map;

  19. import org.eclipse.jgit.errors.MissingObjectException;
  20. import org.eclipse.jgit.errors.NotSupportedException;
  21. import org.eclipse.jgit.errors.TransportException;
  22. import org.eclipse.jgit.internal.JGitText;
  23. import org.eclipse.jgit.lib.ObjectId;
  24. import org.eclipse.jgit.lib.ProgressMonitor;
  25. import org.eclipse.jgit.lib.Ref;
  26. import org.eclipse.jgit.revwalk.RevCommit;
  27. import org.eclipse.jgit.revwalk.RevObject;
  28. import org.eclipse.jgit.revwalk.RevWalk;
  29. import org.eclipse.jgit.transport.RemoteRefUpdate.Status;

  30. /**
  31.  * Class performing push operation on remote repository.
  32.  *
  33.  * @see Transport#push(ProgressMonitor, Collection, OutputStream)
  34.  */
  35. class PushProcess {
  36.     /** Task name for {@link ProgressMonitor} used during opening connection. */
  37.     static final String PROGRESS_OPENING_CONNECTION = JGitText.get().openingConnection;

  38.     /** Transport used to perform this operation. */
  39.     private final Transport transport;

  40.     /** Push operation connection created to perform this operation */
  41.     private PushConnection connection;

  42.     /** Refs to update on remote side. */
  43.     private final Map<String, RemoteRefUpdate> toPush;

  44.     /** Revision walker for checking some updates properties. */
  45.     private final RevWalk walker;

  46.     /** an outputstream to write messages to */
  47.     private final OutputStream out;

  48.     /** A list of option strings associated with this push */
  49.     private List<String> pushOptions;

  50.     /**
  51.      * Create process for specified transport and refs updates specification.
  52.      *
  53.      * @param transport
  54.      *            transport between remote and local repository, used to create
  55.      *            connection.
  56.      * @param toPush
  57.      *            specification of refs updates (and local tracking branches).
  58.      *
  59.      * @throws TransportException
  60.      */
  61.     PushProcess(final Transport transport,
  62.             final Collection<RemoteRefUpdate> toPush) throws TransportException {
  63.         this(transport, toPush, null);
  64.     }

  65.     /**
  66.      * Create process for specified transport and refs updates specification.
  67.      *
  68.      * @param transport
  69.      *            transport between remote and local repository, used to create
  70.      *            connection.
  71.      * @param toPush
  72.      *            specification of refs updates (and local tracking branches).
  73.      * @param out
  74.      *            OutputStream to write messages to
  75.      * @throws TransportException
  76.      */
  77.     PushProcess(final Transport transport,
  78.             final Collection<RemoteRefUpdate> toPush, OutputStream out)
  79.             throws TransportException {
  80.         this.walker = new RevWalk(transport.local);
  81.         this.transport = transport;
  82.         this.toPush = new LinkedHashMap<>();
  83.         this.out = out;
  84.         this.pushOptions = transport.getPushOptions();
  85.         for (RemoteRefUpdate rru : toPush) {
  86.             if (this.toPush.put(rru.getRemoteName(), rru) != null)
  87.                 throw new TransportException(MessageFormat.format(
  88.                         JGitText.get().duplicateRemoteRefUpdateIsIllegal, rru.getRemoteName()));
  89.         }
  90.     }

  91.     /**
  92.      * Perform push operation between local and remote repository - set remote
  93.      * refs appropriately, send needed objects and update local tracking refs.
  94.      * <p>
  95.      * When {@link Transport#isDryRun()} is true, result of this operation is
  96.      * just estimation of real operation result, no real action is performed.
  97.      *
  98.      * @param monitor
  99.      *            progress monitor used for feedback about operation.
  100.      * @return result of push operation with complete status description.
  101.      * @throws NotSupportedException
  102.      *             when push operation is not supported by provided transport.
  103.      * @throws TransportException
  104.      *             when some error occurred during operation, like I/O, protocol
  105.      *             error, or local database consistency error.
  106.      */
  107.     PushResult execute(ProgressMonitor monitor)
  108.             throws NotSupportedException, TransportException {
  109.         try {
  110.             monitor.beginTask(PROGRESS_OPENING_CONNECTION,
  111.                     ProgressMonitor.UNKNOWN);

  112.             final PushResult res = new PushResult();
  113.             connection = transport.openPush();
  114.             try {
  115.                 res.setAdvertisedRefs(transport.getURI(), connection
  116.                         .getRefsMap());
  117.                 res.peerUserAgent = connection.getPeerUserAgent();
  118.                 res.setRemoteUpdates(toPush);
  119.                 monitor.endTask();

  120.                 final Map<String, RemoteRefUpdate> preprocessed = prepareRemoteUpdates();
  121.                 if (transport.isDryRun())
  122.                     modifyUpdatesForDryRun();
  123.                 else if (!preprocessed.isEmpty())
  124.                     connection.push(monitor, preprocessed, out);
  125.             } finally {
  126.                 connection.close();
  127.                 res.addMessages(connection.getMessages());
  128.             }
  129.             if (!transport.isDryRun())
  130.                 updateTrackingRefs();
  131.             for (RemoteRefUpdate rru : toPush.values()) {
  132.                 final TrackingRefUpdate tru = rru.getTrackingRefUpdate();
  133.                 if (tru != null)
  134.                     res.add(tru);
  135.             }
  136.             return res;
  137.         } finally {
  138.             walker.close();
  139.         }
  140.     }

  141.     private Map<String, RemoteRefUpdate> prepareRemoteUpdates()
  142.             throws TransportException {
  143.         boolean atomic = transport.isPushAtomic();
  144.         final Map<String, RemoteRefUpdate> result = new LinkedHashMap<>();
  145.         for (RemoteRefUpdate rru : toPush.values()) {
  146.             final Ref advertisedRef = connection.getRef(rru.getRemoteName());
  147.             ObjectId advertisedOld = null;
  148.             if (advertisedRef != null) {
  149.                 advertisedOld = advertisedRef.getObjectId();
  150.             }
  151.             if (advertisedOld == null) {
  152.                 advertisedOld = ObjectId.zeroId();
  153.             }

  154.             if (rru.getNewObjectId().equals(advertisedOld)) {
  155.                 if (rru.isDelete()) {
  156.                     // ref does exist neither locally nor remotely
  157.                     rru.setStatus(Status.NON_EXISTING);
  158.                 } else {
  159.                     // same object - nothing to do
  160.                     rru.setStatus(Status.UP_TO_DATE);
  161.                 }
  162.                 continue;
  163.             }

  164.             // caller has explicitly specified expected old object id, while it
  165.             // has been changed in the mean time - reject
  166.             if (rru.isExpectingOldObjectId()
  167.                     && !rru.getExpectedOldObjectId().equals(advertisedOld)) {
  168.                 rru.setStatus(Status.REJECTED_REMOTE_CHANGED);
  169.                 if (atomic) {
  170.                     return rejectAll();
  171.                 }
  172.                 continue;
  173.             }
  174.             if (!rru.isExpectingOldObjectId()) {
  175.                 rru.setExpectedOldObjectId(advertisedOld);
  176.             }

  177.             // create ref (hasn't existed on remote side) and delete ref
  178.             // are always fast-forward commands, feasible at this level
  179.             if (advertisedOld.equals(ObjectId.zeroId()) || rru.isDelete()) {
  180.                 rru.setFastForward(true);
  181.                 result.put(rru.getRemoteName(), rru);
  182.                 continue;
  183.             }

  184.             // check for fast-forward:
  185.             // - both old and new ref must point to commits, AND
  186.             // - both of them must be known for us, exist in repository, AND
  187.             // - old commit must be ancestor of new commit
  188.             boolean fastForward = true;
  189.             try {
  190.                 RevObject oldRev = walker.parseAny(advertisedOld);
  191.                 final RevObject newRev = walker.parseAny(rru.getNewObjectId());
  192.                 if (!(oldRev instanceof RevCommit)
  193.                         || !(newRev instanceof RevCommit)
  194.                         || !walker.isMergedInto((RevCommit) oldRev,
  195.                                 (RevCommit) newRev))
  196.                     fastForward = false;
  197.             } catch (MissingObjectException x) {
  198.                 fastForward = false;
  199.             } catch (Exception x) {
  200.                 throw new TransportException(transport.getURI(), MessageFormat.format(
  201.                         JGitText.get().readingObjectsFromLocalRepositoryFailed, x.getMessage()), x);
  202.             }
  203.             rru.setFastForward(fastForward);
  204.             if (!fastForward && !rru.isForceUpdate()) {
  205.                 rru.setStatus(Status.REJECTED_NONFASTFORWARD);
  206.                 if (atomic) {
  207.                     return rejectAll();
  208.                 }
  209.             } else {
  210.                 result.put(rru.getRemoteName(), rru);
  211.             }
  212.         }
  213.         return result;
  214.     }

  215.     private Map<String, RemoteRefUpdate> rejectAll() {
  216.         for (RemoteRefUpdate rru : toPush.values()) {
  217.             if (rru.getStatus() == Status.NOT_ATTEMPTED) {
  218.                 rru.setStatus(RemoteRefUpdate.Status.REJECTED_OTHER_REASON);
  219.                 rru.setMessage(JGitText.get().transactionAborted);
  220.             }
  221.         }
  222.         return Collections.emptyMap();
  223.     }

  224.     private void modifyUpdatesForDryRun() {
  225.         for (RemoteRefUpdate rru : toPush.values())
  226.             if (rru.getStatus() == Status.NOT_ATTEMPTED)
  227.                 rru.setStatus(Status.OK);
  228.     }

  229.     private void updateTrackingRefs() {
  230.         for (RemoteRefUpdate rru : toPush.values()) {
  231.             final Status status = rru.getStatus();
  232.             if (rru.hasTrackingRefUpdate()
  233.                     && (status == Status.UP_TO_DATE || status == Status.OK)) {
  234.                 // update local tracking branch only when there is a chance that
  235.                 // it has changed; this is possible for:
  236.                 // -updated (OK) status,
  237.                 // -up to date (UP_TO_DATE) status
  238.                 try {
  239.                     rru.updateTrackingRef(walker);
  240.                 } catch (IOException e) {
  241.                     // ignore as RefUpdate has stored I/O error status
  242.                 }
  243.             }
  244.         }
  245.     }

  246.     /**
  247.      * Gets the list of option strings associated with this push.
  248.      *
  249.      * @return pushOptions
  250.      * @since 4.5
  251.      */
  252.     public List<String> getPushOptions() {
  253.         return pushOptions;
  254.     }
  255. }