PushProcess.java

  1. /*
  2.  * Copyright (C) 2008, 2022 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 java.util.stream.Collectors;

  20. import org.eclipse.jgit.api.errors.AbortedByHookException;
  21. import org.eclipse.jgit.errors.MissingObjectException;
  22. import org.eclipse.jgit.errors.NotSupportedException;
  23. import org.eclipse.jgit.errors.TransportException;
  24. import org.eclipse.jgit.hooks.PrePushHook;
  25. import org.eclipse.jgit.internal.JGitText;
  26. import org.eclipse.jgit.lib.Constants;
  27. import org.eclipse.jgit.lib.ObjectId;
  28. import org.eclipse.jgit.lib.ProgressMonitor;
  29. import org.eclipse.jgit.lib.Ref;
  30. import org.eclipse.jgit.revwalk.RevCommit;
  31. import org.eclipse.jgit.revwalk.RevObject;
  32. import org.eclipse.jgit.revwalk.RevWalk;
  33. import org.eclipse.jgit.transport.RemoteRefUpdate.Status;

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

  42.     /** Transport used to perform this operation. */
  43.     private final Transport transport;

  44.     /** Push operation connection created to perform this operation */
  45.     private PushConnection connection;

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

  48.     /** Revision walker for checking some updates properties. */
  49.     private final RevWalk walker;

  50.     /** an outputstream to write messages to */
  51.     private final OutputStream out;

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

  54.     private final PrePushHook prePush;

  55.     /**
  56.      * Create process for specified transport and refs updates specification.
  57.      *
  58.      * @param transport
  59.      *            transport between remote and local repository, used to create
  60.      *            connection.
  61.      * @param toPush
  62.      *            specification of refs updates (and local tracking branches).
  63.      * @param prePush
  64.      *            {@link PrePushHook} to run after the remote advertisement has
  65.      *            been gotten
  66.      * @throws TransportException
  67.      */
  68.     PushProcess(Transport transport, Collection<RemoteRefUpdate> toPush,
  69.             PrePushHook prePush) throws TransportException {
  70.         this(transport, toPush, prePush, null);
  71.     }

  72.     /**
  73.      * Create process for specified transport and refs updates specification.
  74.      *
  75.      * @param transport
  76.      *            transport between remote and local repository, used to create
  77.      *            connection.
  78.      * @param toPush
  79.      *            specification of refs updates (and local tracking branches).
  80.      * @param prePush
  81.      *            {@link PrePushHook} to run after the remote advertisement has
  82.      *            been gotten
  83.      * @param out
  84.      *            OutputStream to write messages to
  85.      * @throws TransportException
  86.      */
  87.     PushProcess(Transport transport, Collection<RemoteRefUpdate> toPush,
  88.             PrePushHook prePush, OutputStream out) throws TransportException {
  89.         this.walker = new RevWalk(transport.local);
  90.         this.transport = transport;
  91.         this.toPush = new LinkedHashMap<>();
  92.         this.prePush = prePush;
  93.         this.out = out;
  94.         this.pushOptions = transport.getPushOptions();
  95.         for (RemoteRefUpdate rru : toPush) {
  96.             if (this.toPush.put(rru.getRemoteName(), rru) != null)
  97.                 throw new TransportException(MessageFormat.format(
  98.                         JGitText.get().duplicateRemoteRefUpdateIsIllegal, rru.getRemoteName()));
  99.         }
  100.     }

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

  122.             final PushResult res = new PushResult();
  123.             connection = transport.openPush();
  124.             try {
  125.                 res.setAdvertisedRefs(transport.getURI(), connection
  126.                         .getRefsMap());
  127.                 res.peerUserAgent = connection.getPeerUserAgent();
  128.                 monitor.endTask();

  129.                 Map<String, RemoteRefUpdate> expanded = expandMatching();
  130.                 toPush.clear();
  131.                 toPush.putAll(expanded);

  132.                 res.setRemoteUpdates(toPush);
  133.                 final Map<String, RemoteRefUpdate> preprocessed = prepareRemoteUpdates();
  134.                 List<RemoteRefUpdate> willBeAttempted = preprocessed.values()
  135.                         .stream().filter(u -> {
  136.                             switch (u.getStatus()) {
  137.                             case NON_EXISTING:
  138.                             case REJECTED_NODELETE:
  139.                             case REJECTED_NONFASTFORWARD:
  140.                             case REJECTED_OTHER_REASON:
  141.                             case REJECTED_REMOTE_CHANGED:
  142.                             case UP_TO_DATE:
  143.                                 return false;
  144.                             default:
  145.                                 return true;
  146.                             }
  147.                         }).collect(Collectors.toList());
  148.                 if (!willBeAttempted.isEmpty()) {
  149.                     if (prePush != null) {
  150.                         try {
  151.                             prePush.setRefs(willBeAttempted);
  152.                             prePush.setDryRun(transport.isDryRun());
  153.                             prePush.call();
  154.                         } catch (AbortedByHookException | IOException e) {
  155.                             throw new TransportException(e.getMessage(), e);
  156.                         }
  157.                     }
  158.                 }
  159.                 if (transport.isDryRun())
  160.                     modifyUpdatesForDryRun();
  161.                 else if (!preprocessed.isEmpty())
  162.                     connection.push(monitor, preprocessed, out);
  163.             } finally {
  164.                 connection.close();
  165.                 res.addMessages(connection.getMessages());
  166.             }
  167.             if (!transport.isDryRun())
  168.                 updateTrackingRefs();
  169.             for (RemoteRefUpdate rru : toPush.values()) {
  170.                 final TrackingRefUpdate tru = rru.getTrackingRefUpdate();
  171.                 if (tru != null)
  172.                     res.add(tru);
  173.             }
  174.             return res;
  175.         } finally {
  176.             walker.close();
  177.         }
  178.     }

  179.     private Map<String, RemoteRefUpdate> prepareRemoteUpdates()
  180.             throws TransportException {
  181.         boolean atomic = transport.isPushAtomic();
  182.         final Map<String, RemoteRefUpdate> result = new LinkedHashMap<>();
  183.         for (RemoteRefUpdate rru : toPush.values()) {
  184.             final Ref advertisedRef = connection.getRef(rru.getRemoteName());
  185.             ObjectId advertisedOld = null;
  186.             if (advertisedRef != null) {
  187.                 advertisedOld = advertisedRef.getObjectId();
  188.             }
  189.             if (advertisedOld == null) {
  190.                 advertisedOld = ObjectId.zeroId();
  191.             }

  192.             if (rru.getNewObjectId().equals(advertisedOld)) {
  193.                 if (rru.isDelete()) {
  194.                     // ref does exist neither locally nor remotely
  195.                     rru.setStatus(Status.NON_EXISTING);
  196.                 } else {
  197.                     // same object - nothing to do
  198.                     rru.setStatus(Status.UP_TO_DATE);
  199.                 }
  200.                 continue;
  201.             }

  202.             // caller has explicitly specified expected old object id, while it
  203.             // has been changed in the mean time - reject
  204.             if (rru.isExpectingOldObjectId()
  205.                     && !rru.getExpectedOldObjectId().equals(advertisedOld)) {
  206.                 rru.setStatus(Status.REJECTED_REMOTE_CHANGED);
  207.                 if (atomic) {
  208.                     return rejectAll();
  209.                 }
  210.                 continue;
  211.             }
  212.             if (!rru.isExpectingOldObjectId()) {
  213.                 rru.setExpectedOldObjectId(advertisedOld);
  214.             }

  215.             // create ref (hasn't existed on remote side) and delete ref
  216.             // are always fast-forward commands, feasible at this level
  217.             if (advertisedOld.equals(ObjectId.zeroId()) || rru.isDelete()) {
  218.                 rru.setFastForward(true);
  219.                 result.put(rru.getRemoteName(), rru);
  220.                 continue;
  221.             }

  222.             boolean fastForward = isFastForward(advertisedOld,
  223.                     rru.getNewObjectId());
  224.             rru.setFastForward(fastForward);
  225.             if (!fastForward && !rru.isForceUpdate()) {
  226.                 rru.setStatus(Status.REJECTED_NONFASTFORWARD);
  227.                 if (atomic) {
  228.                     return rejectAll();
  229.                 }
  230.             } else {
  231.                 result.put(rru.getRemoteName(), rru);
  232.             }
  233.         }
  234.         return result;
  235.     }

  236.     /**
  237.      * Determines whether an update from {@code oldOid} to {@code newOid} is a
  238.      * fast-forward update:
  239.      * <ul>
  240.      * <li>both old and new must be commits, AND</li>
  241.      * <li>both of them must be known to us and exist in the repository,
  242.      * AND</li>
  243.      * <li>the old commit must be an ancestor of the new commit.</li>
  244.      * </ul>
  245.      *
  246.      * @param oldOid
  247.      *            {@link ObjectId} of the old commit
  248.      * @param newOid
  249.      *            {@link ObjectId} of the new commit
  250.      * @return {@code true} if the update fast-forwards, {@code false} otherwise
  251.      * @throws TransportException
  252.      */
  253.     private boolean isFastForward(ObjectId oldOid, ObjectId newOid)
  254.             throws TransportException {
  255.         try {
  256.             RevObject oldRev = walker.parseAny(oldOid);
  257.             RevObject newRev = walker.parseAny(newOid);
  258.             if (!(oldRev instanceof RevCommit) || !(newRev instanceof RevCommit)
  259.                     || !walker.isMergedInto((RevCommit) oldRev,
  260.                             (RevCommit) newRev)) {
  261.                 return false;
  262.             }
  263.         } catch (MissingObjectException x) {
  264.             return false;
  265.         } catch (Exception x) {
  266.             throw new TransportException(transport.getURI(),
  267.                     MessageFormat.format(JGitText
  268.                             .get().readingObjectsFromLocalRepositoryFailed,
  269.                             x.getMessage()),
  270.                     x);
  271.         }
  272.         return true;
  273.     }

  274.     /**
  275.      * Expands all placeholder {@link RemoteRefUpdate}s for "matching"
  276.      * {@link RefSpec}s ":" in {@link #toPush} and returns the resulting map in
  277.      * which the placeholders have been replaced by their expansion.
  278.      *
  279.      * @return a new map of {@link RemoteRefUpdate}s keyed by remote name
  280.      * @throws TransportException
  281.      *             if the expansion results in duplicate updates
  282.      */
  283.     private Map<String, RemoteRefUpdate> expandMatching()
  284.             throws TransportException {
  285.         Map<String, RemoteRefUpdate> result = new LinkedHashMap<>();
  286.         boolean hadMatch = false;
  287.         for (RemoteRefUpdate update : toPush.values()) {
  288.             if (update.isMatching()) {
  289.                 if (hadMatch) {
  290.                     throw new TransportException(MessageFormat.format(
  291.                             JGitText.get().duplicateRemoteRefUpdateIsIllegal,
  292.                             ":")); //$NON-NLS-1$
  293.                 }
  294.                 expandMatching(result, update);
  295.                 hadMatch = true;
  296.             } else if (result.put(update.getRemoteName(), update) != null) {
  297.                 throw new TransportException(MessageFormat.format(
  298.                         JGitText.get().duplicateRemoteRefUpdateIsIllegal,
  299.                         update.getRemoteName()));
  300.             }
  301.         }
  302.         return result;
  303.     }

  304.     /**
  305.      * Expands the placeholder {@link RemoteRefUpdate} {@code match} for a
  306.      * "matching" {@link RefSpec} ":" or "+:" and puts the expansion into the
  307.      * given map {@code updates}.
  308.      *
  309.      * @param updates
  310.      *            map to put the expansion in
  311.      * @param match
  312.      *            the placeholder {@link RemoteRefUpdate} to expand
  313.      *
  314.      * @throws TransportException
  315.      *             if the expansion results in duplicate updates, or the local
  316.      *             branches cannot be determined
  317.      */
  318.     private void expandMatching(Map<String, RemoteRefUpdate> updates,
  319.             RemoteRefUpdate match) throws TransportException {
  320.         try {
  321.             Map<String, Ref> advertisement = connection.getRefsMap();
  322.             Collection<RefSpec> fetchSpecs = match.getFetchSpecs();
  323.             boolean forceUpdate = match.isForceUpdate();
  324.             for (Ref local : transport.local.getRefDatabase()
  325.                     .getRefsByPrefix(Constants.R_HEADS)) {
  326.                 if (local.isSymbolic()) {
  327.                     continue;
  328.                 }
  329.                 String name = local.getName();
  330.                 Ref advertised = advertisement.get(name);
  331.                 if (advertised == null || advertised.isSymbolic()) {
  332.                     continue;
  333.                 }
  334.                 ObjectId oldOid = advertised.getObjectId();
  335.                 if (oldOid == null || ObjectId.zeroId().equals(oldOid)) {
  336.                     continue;
  337.                 }
  338.                 ObjectId newOid = local.getObjectId();
  339.                 if (newOid == null || ObjectId.zeroId().equals(newOid)) {
  340.                     continue;
  341.                 }

  342.                 RemoteRefUpdate rru = new RemoteRefUpdate(transport.local, name,
  343.                         newOid, name, forceUpdate,
  344.                         Transport.findTrackingRefName(name, fetchSpecs),
  345.                         oldOid);
  346.                 if (updates.put(rru.getRemoteName(), rru) != null) {
  347.                     throw new TransportException(MessageFormat.format(
  348.                             JGitText.get().duplicateRemoteRefUpdateIsIllegal,
  349.                             rru.getRemoteName()));
  350.                 }
  351.             }
  352.         } catch (IOException x) {
  353.             throw new TransportException(transport.getURI(),
  354.                     MessageFormat.format(JGitText
  355.                             .get().readingObjectsFromLocalRepositoryFailed,
  356.                             x.getMessage()),
  357.                     x);
  358.         }
  359.     }

  360.     private Map<String, RemoteRefUpdate> rejectAll() {
  361.         for (RemoteRefUpdate rru : toPush.values()) {
  362.             if (rru.getStatus() == Status.NOT_ATTEMPTED) {
  363.                 rru.setStatus(RemoteRefUpdate.Status.REJECTED_OTHER_REASON);
  364.                 rru.setMessage(JGitText.get().transactionAborted);
  365.             }
  366.         }
  367.         return Collections.emptyMap();
  368.     }

  369.     private void modifyUpdatesForDryRun() {
  370.         for (RemoteRefUpdate rru : toPush.values())
  371.             if (rru.getStatus() == Status.NOT_ATTEMPTED)
  372.                 rru.setStatus(Status.OK);
  373.     }

  374.     private void updateTrackingRefs() {
  375.         for (RemoteRefUpdate rru : toPush.values()) {
  376.             final Status status = rru.getStatus();
  377.             if (rru.hasTrackingRefUpdate()
  378.                     && (status == Status.UP_TO_DATE || status == Status.OK)) {
  379.                 // update local tracking branch only when there is a chance that
  380.                 // it has changed; this is possible for:
  381.                 // -updated (OK) status,
  382.                 // -up to date (UP_TO_DATE) status
  383.                 try {
  384.                     rru.updateTrackingRef(walker);
  385.                 } catch (IOException e) {
  386.                     // ignore as RefUpdate has stored I/O error status
  387.                 }
  388.             }
  389.         }
  390.     }

  391.     /**
  392.      * Gets the list of option strings associated with this push.
  393.      *
  394.      * @return pushOptions
  395.      * @since 4.5
  396.      */
  397.     public List<String> getPushOptions() {
  398.         return pushOptions;
  399.     }
  400. }