PushCommand.java

  1. /*
  2.  * Copyright (C) 2010, Chris Aniszczyk <caniszczyk@gmail.com>
  3.  * and other copyright owners as documented in the project's IP log.
  4.  *
  5.  * This program and the accompanying materials are made available
  6.  * under the terms of the Eclipse Distribution License v1.0 which
  7.  * accompanies this distribution, is reproduced below, and is
  8.  * available at http://www.eclipse.org/org/documents/edl-v10.php
  9.  *
  10.  * All rights reserved.
  11.  *
  12.  * Redistribution and use in source and binary forms, with or
  13.  * without modification, are permitted provided that the following
  14.  * conditions are met:
  15.  *
  16.  * - Redistributions of source code must retain the above copyright
  17.  *   notice, this list of conditions and the following disclaimer.
  18.  *
  19.  * - Redistributions in binary form must reproduce the above
  20.  *   copyright notice, this list of conditions and the following
  21.  *   disclaimer in the documentation and/or other materials provided
  22.  *   with the distribution.
  23.  *
  24.  * - Neither the name of the Eclipse Foundation, Inc. nor the
  25.  *   names of its contributors may be used to endorse or promote
  26.  *   products derived from this software without specific prior
  27.  *   written permission.
  28.  *
  29.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30.  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31.  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33.  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34.  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35.  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37.  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38.  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39.  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41.  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42.  */
  43. package org.eclipse.jgit.api;

  44. import java.io.IOException;
  45. import java.io.OutputStream;
  46. import java.net.URISyntaxException;
  47. import java.text.MessageFormat;
  48. import java.util.ArrayList;
  49. import java.util.Arrays;
  50. import java.util.Collection;
  51. import java.util.Collections;
  52. import java.util.HashMap;
  53. import java.util.List;
  54. import java.util.Map;

  55. import org.eclipse.jgit.api.errors.GitAPIException;
  56. import org.eclipse.jgit.api.errors.InvalidRemoteException;
  57. import org.eclipse.jgit.api.errors.JGitInternalException;
  58. import org.eclipse.jgit.errors.NotSupportedException;
  59. import org.eclipse.jgit.errors.TooLargeObjectInPackException;
  60. import org.eclipse.jgit.errors.TooLargePackException;
  61. import org.eclipse.jgit.errors.TransportException;
  62. import org.eclipse.jgit.internal.JGitText;
  63. import org.eclipse.jgit.lib.Constants;
  64. import org.eclipse.jgit.lib.NullProgressMonitor;
  65. import org.eclipse.jgit.lib.ProgressMonitor;
  66. import org.eclipse.jgit.lib.Ref;
  67. import org.eclipse.jgit.lib.Repository;
  68. import org.eclipse.jgit.transport.PushResult;
  69. import org.eclipse.jgit.transport.RefLeaseSpec;
  70. import org.eclipse.jgit.transport.RefSpec;
  71. import org.eclipse.jgit.transport.RemoteConfig;
  72. import org.eclipse.jgit.transport.RemoteRefUpdate;
  73. import org.eclipse.jgit.transport.Transport;

  74. /**
  75.  * A class used to execute a {@code Push} command. It has setters for all
  76.  * supported options and arguments of this command and a {@link #call()} method
  77.  * to finally execute the command.
  78.  *
  79.  * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-push.html"
  80.  *      >Git documentation about Push</a>
  81.  */
  82. public class PushCommand extends
  83.         TransportCommand<PushCommand, Iterable<PushResult>> {

  84.     private String remote = Constants.DEFAULT_REMOTE_NAME;

  85.     private final List<RefSpec> refSpecs;

  86.     private final Map<String, RefLeaseSpec> refLeaseSpecs;

  87.     private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;

  88.     private String receivePack = RemoteConfig.DEFAULT_RECEIVE_PACK;

  89.     private boolean dryRun;
  90.     private boolean atomic;
  91.     private boolean force;
  92.     private boolean thin = Transport.DEFAULT_PUSH_THIN;

  93.     private OutputStream out;

  94.     private List<String> pushOptions;

  95.     /**
  96.      * <p>
  97.      * Constructor for PushCommand.
  98.      * </p>
  99.      *
  100.      * @param repo
  101.      *            the {@link org.eclipse.jgit.lib.Repository}
  102.      */
  103.     protected PushCommand(Repository repo) {
  104.         super(repo);
  105.         refSpecs = new ArrayList<>(3);
  106.         refLeaseSpecs = new HashMap<>();
  107.     }

  108.     /**
  109.      * {@inheritDoc}
  110.      * <p>
  111.      * Execute the {@code push} command with all the options and parameters
  112.      * collected by the setter methods of this class. Each instance of this
  113.      * class should only be used for one invocation of the command (means: one
  114.      * call to {@link #call()})
  115.      */
  116.     @Override
  117.     public Iterable<PushResult> call() throws GitAPIException,
  118.             InvalidRemoteException,
  119.             org.eclipse.jgit.api.errors.TransportException {
  120.         checkCallable();

  121.         ArrayList<PushResult> pushResults = new ArrayList<>(3);

  122.         try {
  123.             if (refSpecs.isEmpty()) {
  124.                 RemoteConfig config = new RemoteConfig(repo.getConfig(),
  125.                         getRemote());
  126.                 refSpecs.addAll(config.getPushRefSpecs());
  127.             }
  128.             if (refSpecs.isEmpty()) {
  129.                 Ref head = repo.exactRef(Constants.HEAD);
  130.                 if (head != null && head.isSymbolic())
  131.                     refSpecs.add(new RefSpec(head.getLeaf().getName()));
  132.             }

  133.             if (force) {
  134.                 for (int i = 0; i < refSpecs.size(); i++)
  135.                     refSpecs.set(i, refSpecs.get(i).setForceUpdate(true));
  136.             }

  137.             final List<Transport> transports;
  138.             transports = Transport.openAll(repo, remote, Transport.Operation.PUSH);
  139.             for (@SuppressWarnings("resource") // Explicitly closed in finally
  140.                     final Transport transport : transports) {
  141.                 transport.setPushThin(thin);
  142.                 transport.setPushAtomic(atomic);
  143.                 if (receivePack != null)
  144.                     transport.setOptionReceivePack(receivePack);
  145.                 transport.setDryRun(dryRun);
  146.                 transport.setPushOptions(pushOptions);
  147.                 configure(transport);

  148.                 final Collection<RemoteRefUpdate> toPush = transport
  149.                         .findRemoteRefUpdatesFor(refSpecs, refLeaseSpecs);

  150.                 try {
  151.                     PushResult result = transport.push(monitor, toPush, out);
  152.                     pushResults.add(result);

  153.                 } catch (TooLargePackException e) {
  154.                     throw new org.eclipse.jgit.api.errors.TooLargePackException(
  155.                             e.getMessage(), e);
  156.                 } catch (TooLargeObjectInPackException e) {
  157.                     throw new org.eclipse.jgit.api.errors.TooLargeObjectInPackException(
  158.                             e.getMessage(), e);
  159.                 } catch (TransportException e) {
  160.                     throw new org.eclipse.jgit.api.errors.TransportException(
  161.                             e.getMessage(), e);
  162.                 } finally {
  163.                     transport.close();
  164.                 }
  165.             }

  166.         } catch (URISyntaxException e) {
  167.             throw new InvalidRemoteException(MessageFormat.format(
  168.                     JGitText.get().invalidRemote, remote));
  169.         } catch (TransportException e) {
  170.             throw new org.eclipse.jgit.api.errors.TransportException(
  171.                     e.getMessage(), e);
  172.         } catch (NotSupportedException e) {
  173.             throw new JGitInternalException(
  174.                     JGitText.get().exceptionCaughtDuringExecutionOfPushCommand,
  175.                     e);
  176.         } catch (IOException e) {
  177.             throw new JGitInternalException(
  178.                     JGitText.get().exceptionCaughtDuringExecutionOfPushCommand,
  179.                     e);
  180.         }

  181.         return pushResults;
  182.     }

  183.     /**
  184.      * The remote (uri or name) used for the push operation. If no remote is
  185.      * set, the default value of <code>Constants.DEFAULT_REMOTE_NAME</code> will
  186.      * be used.
  187.      *
  188.      * @see Constants#DEFAULT_REMOTE_NAME
  189.      * @param remote
  190.      *            the remote name
  191.      * @return {@code this}
  192.      */
  193.     public PushCommand setRemote(String remote) {
  194.         checkCallable();
  195.         this.remote = remote;
  196.         return this;
  197.     }

  198.     /**
  199.      * Get remote name
  200.      *
  201.      * @return the remote used for the remote operation
  202.      */
  203.     public String getRemote() {
  204.         return remote;
  205.     }

  206.     /**
  207.      * The remote executable providing receive-pack service for pack transports.
  208.      * If no receive-pack is set, the default value of
  209.      * <code>RemoteConfig.DEFAULT_RECEIVE_PACK</code> will be used.
  210.      *
  211.      * @see RemoteConfig#DEFAULT_RECEIVE_PACK
  212.      * @param receivePack
  213.      *            name of the remote executable providing the receive-pack
  214.      *            service
  215.      * @return {@code this}
  216.      */
  217.     public PushCommand setReceivePack(String receivePack) {
  218.         checkCallable();
  219.         this.receivePack = receivePack;
  220.         return this;
  221.     }

  222.     /**
  223.      * Get the name of the remote executable providing the receive-pack service
  224.      *
  225.      * @return the receive-pack used for the remote operation
  226.      */
  227.     public String getReceivePack() {
  228.         return receivePack;
  229.     }

  230.     /**
  231.      * Get timeout used for push operation
  232.      *
  233.      * @return the timeout used for the push operation
  234.      */
  235.     public int getTimeout() {
  236.         return timeout;
  237.     }

  238.     /**
  239.      * Get the progress monitor
  240.      *
  241.      * @return the progress monitor for the push operation
  242.      */
  243.     public ProgressMonitor getProgressMonitor() {
  244.         return monitor;
  245.     }

  246.     /**
  247.      * The progress monitor associated with the push operation. By default, this
  248.      * is set to <code>NullProgressMonitor</code>
  249.      *
  250.      * @see NullProgressMonitor
  251.      * @param monitor
  252.      *            a {@link org.eclipse.jgit.lib.ProgressMonitor}
  253.      * @return {@code this}
  254.      */
  255.     public PushCommand setProgressMonitor(ProgressMonitor monitor) {
  256.         checkCallable();
  257.         if (monitor == null) {
  258.             monitor = NullProgressMonitor.INSTANCE;
  259.         }
  260.         this.monitor = monitor;
  261.         return this;
  262.     }

  263.     /**
  264.      * Get the <code>RefLeaseSpec</code>s.
  265.      *
  266.      * @return the <code>RefLeaseSpec</code>s
  267.      * @since 4.7
  268.      */
  269.     public List<RefLeaseSpec> getRefLeaseSpecs() {
  270.         return new ArrayList<>(refLeaseSpecs.values());
  271.     }

  272.     /**
  273.      * The ref lease specs to be used in the push operation, for a
  274.      * force-with-lease push operation.
  275.      *
  276.      * @param specs
  277.      *            a {@link org.eclipse.jgit.transport.RefLeaseSpec} object.
  278.      * @return {@code this}
  279.      * @since 4.7
  280.      */
  281.     public PushCommand setRefLeaseSpecs(RefLeaseSpec... specs) {
  282.         return setRefLeaseSpecs(Arrays.asList(specs));
  283.     }

  284.     /**
  285.      * The ref lease specs to be used in the push operation, for a
  286.      * force-with-lease push operation.
  287.      *
  288.      * @param specs
  289.      *            list of {@code RefLeaseSpec}s
  290.      * @return {@code this}
  291.      * @since 4.7
  292.      */
  293.     public PushCommand setRefLeaseSpecs(List<RefLeaseSpec> specs) {
  294.         checkCallable();
  295.         this.refLeaseSpecs.clear();
  296.         for (RefLeaseSpec spec : specs) {
  297.             refLeaseSpecs.put(spec.getRef(), spec);
  298.         }
  299.         return this;
  300.     }

  301.     /**
  302.      * Get {@code RefSpec}s.
  303.      *
  304.      * @return the ref specs
  305.      */
  306.     public List<RefSpec> getRefSpecs() {
  307.         return refSpecs;
  308.     }

  309.     /**
  310.      * The ref specs to be used in the push operation
  311.      *
  312.      * @param specs a {@link org.eclipse.jgit.transport.RefSpec} object.
  313.      * @return {@code this}
  314.      */
  315.     public PushCommand setRefSpecs(RefSpec... specs) {
  316.         checkCallable();
  317.         this.refSpecs.clear();
  318.         Collections.addAll(refSpecs, specs);
  319.         return this;
  320.     }

  321.     /**
  322.      * The ref specs to be used in the push operation
  323.      *
  324.      * @param specs
  325.      *            list of {@link org.eclipse.jgit.transport.RefSpec}s
  326.      * @return {@code this}
  327.      */
  328.     public PushCommand setRefSpecs(List<RefSpec> specs) {
  329.         checkCallable();
  330.         this.refSpecs.clear();
  331.         this.refSpecs.addAll(specs);
  332.         return this;
  333.     }

  334.     /**
  335.      * Push all branches under refs/heads/*.
  336.      *
  337.      * @return {code this}
  338.      */
  339.     public PushCommand setPushAll() {
  340.         refSpecs.add(Transport.REFSPEC_PUSH_ALL);
  341.         return this;
  342.     }

  343.     /**
  344.      * Push all tags under refs/tags/*.
  345.      *
  346.      * @return {code this}
  347.      */
  348.     public PushCommand setPushTags() {
  349.         refSpecs.add(Transport.REFSPEC_TAGS);
  350.         return this;
  351.     }

  352.     /**
  353.      * Add a reference to push.
  354.      *
  355.      * @param ref
  356.      *            the source reference. The remote name will match.
  357.      * @return {@code this}.
  358.      */
  359.     public PushCommand add(Ref ref) {
  360.         refSpecs.add(new RefSpec(ref.getLeaf().getName()));
  361.         return this;
  362.     }

  363.     /**
  364.      * Add a reference to push.
  365.      *
  366.      * @param nameOrSpec
  367.      *            any reference name, or a reference specification.
  368.      * @return {@code this}.
  369.      * @throws JGitInternalException
  370.      *             the reference name cannot be resolved.
  371.      */
  372.     public PushCommand add(String nameOrSpec) {
  373.         if (0 <= nameOrSpec.indexOf(':')) {
  374.             refSpecs.add(new RefSpec(nameOrSpec));
  375.         } else {
  376.             Ref src;
  377.             try {
  378.                 src = repo.findRef(nameOrSpec);
  379.             } catch (IOException e) {
  380.                 throw new JGitInternalException(
  381.                         JGitText.get().exceptionCaughtDuringExecutionOfPushCommand,
  382.                         e);
  383.             }
  384.             if (src != null)
  385.                 add(src);
  386.         }
  387.         return this;
  388.     }

  389.     /**
  390.      * Whether to run the push operation as a dry run
  391.      *
  392.      * @return the dry run preference for the push operation
  393.      */
  394.     public boolean isDryRun() {
  395.         return dryRun;
  396.     }

  397.     /**
  398.      * Sets whether the push operation should be a dry run
  399.      *
  400.      * @param dryRun a boolean.
  401.      * @return {@code this}
  402.      */
  403.     public PushCommand setDryRun(boolean dryRun) {
  404.         checkCallable();
  405.         this.dryRun = dryRun;
  406.         return this;
  407.     }

  408.     /**
  409.      * Get the thin-pack preference
  410.      *
  411.      * @return the thin-pack preference for push operation
  412.      */
  413.     public boolean isThin() {
  414.         return thin;
  415.     }

  416.     /**
  417.      * Set the thin-pack preference for push operation.
  418.      *
  419.      * Default setting is Transport.DEFAULT_PUSH_THIN
  420.      *
  421.      * @param thin
  422.      *            the thin-pack preference value
  423.      * @return {@code this}
  424.      */
  425.     public PushCommand setThin(boolean thin) {
  426.         checkCallable();
  427.         this.thin = thin;
  428.         return this;
  429.     }

  430.     /**
  431.      * Whether this push should be executed atomically (all references updated,
  432.      * or none)
  433.      *
  434.      * @return true if all-or-nothing behavior is requested.
  435.      * @since 4.2
  436.      */
  437.     public boolean isAtomic() {
  438.         return atomic;
  439.     }

  440.     /**
  441.      * Requests atomic push (all references updated, or no updates).
  442.      *
  443.      * Default setting is false.
  444.      *
  445.      * @param atomic
  446.      *            whether to run the push atomically
  447.      * @return {@code this}
  448.      * @since 4.2
  449.      */
  450.     public PushCommand setAtomic(boolean atomic) {
  451.         checkCallable();
  452.         this.atomic = atomic;
  453.         return this;
  454.     }

  455.     /**
  456.      * Whether to push forcefully
  457.      *
  458.      * @return the force preference for push operation
  459.      */
  460.     public boolean isForce() {
  461.         return force;
  462.     }

  463.     /**
  464.      * Sets the force preference for push operation.
  465.      *
  466.      * @param force
  467.      *            whether to push forcefully
  468.      * @return {@code this}
  469.      */
  470.     public PushCommand setForce(boolean force) {
  471.         checkCallable();
  472.         this.force = force;
  473.         return this;
  474.     }

  475.     /**
  476.      * Sets the output stream to write sideband messages to
  477.      *
  478.      * @param out
  479.      *            an {@link java.io.OutputStream}
  480.      * @return {@code this}
  481.      * @since 3.0
  482.      */
  483.     public PushCommand setOutputStream(OutputStream out) {
  484.         this.out = out;
  485.         return this;
  486.     }

  487.     /**
  488.      * Get push options
  489.      *
  490.      * @return the option strings associated with the push operation
  491.      * @since 4.5
  492.      */
  493.     public List<String> getPushOptions() {
  494.         return pushOptions;
  495.     }

  496.     /**
  497.      * Set the option strings associated with the push operation.
  498.      *
  499.      * @param pushOptions
  500.      *            a {@link java.util.List} of push option strings
  501.      * @return {@code this}
  502.      * @since 4.5
  503.      */
  504.     public PushCommand setPushOptions(List<String> pushOptions) {
  505.         this.pushOptions = pushOptions;
  506.         return this;
  507.     }
  508. }