View Javadoc
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  
45  import java.io.IOException;
46  import java.io.OutputStream;
47  import java.net.URISyntaxException;
48  import java.text.MessageFormat;
49  import java.util.ArrayList;
50  import java.util.Arrays;
51  import java.util.Collection;
52  import java.util.Collections;
53  import java.util.HashMap;
54  import java.util.List;
55  import java.util.Map;
56  
57  import org.eclipse.jgit.api.errors.GitAPIException;
58  import org.eclipse.jgit.api.errors.InvalidRemoteException;
59  import org.eclipse.jgit.api.errors.JGitInternalException;
60  import org.eclipse.jgit.errors.NotSupportedException;
61  import org.eclipse.jgit.errors.TooLargeObjectInPackException;
62  import org.eclipse.jgit.errors.TooLargePackException;
63  import org.eclipse.jgit.errors.TransportException;
64  import org.eclipse.jgit.internal.JGitText;
65  import org.eclipse.jgit.lib.Constants;
66  import org.eclipse.jgit.lib.NullProgressMonitor;
67  import org.eclipse.jgit.lib.ProgressMonitor;
68  import org.eclipse.jgit.lib.Ref;
69  import org.eclipse.jgit.lib.Repository;
70  import org.eclipse.jgit.transport.PushResult;
71  import org.eclipse.jgit.transport.RefLeaseSpec;
72  import org.eclipse.jgit.transport.RefSpec;
73  import org.eclipse.jgit.transport.RemoteConfig;
74  import org.eclipse.jgit.transport.RemoteRefUpdate;
75  import org.eclipse.jgit.transport.Transport;
76  
77  /**
78   * A class used to execute a {@code Push} command. It has setters for all
79   * supported options and arguments of this command and a {@link #call()} method
80   * to finally execute the command.
81   *
82   * @see <a href="http://www.kernel.org/pub/software/scm/git/docs/git-push.html"
83   *      >Git documentation about Push</a>
84   */
85  public class PushCommand extends
86  		TransportCommand<PushCommand, Iterable<PushResult>> {
87  
88  	private String remote = Constants.DEFAULT_REMOTE_NAME;
89  
90  	private final List<RefSpec> refSpecs;
91  
92  	private final Map<String, RefLeaseSpec> refLeaseSpecs;
93  
94  	private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
95  
96  	private String receivePack = RemoteConfig.DEFAULT_RECEIVE_PACK;
97  
98  	private boolean dryRun;
99  	private boolean atomic;
100 	private boolean force;
101 	private boolean thin = Transport.DEFAULT_PUSH_THIN;
102 
103 	private OutputStream out;
104 
105 	private List<String> pushOptions;
106 
107 	/**
108 	 * <p>
109 	 * Constructor for PushCommand.
110 	 * </p>
111 	 *
112 	 * @param repo
113 	 *            the {@link org.eclipse.jgit.lib.Repository}
114 	 */
115 	protected PushCommand(Repository repo) {
116 		super(repo);
117 		refSpecs = new ArrayList<>(3);
118 		refLeaseSpecs = new HashMap<>();
119 	}
120 
121 	/**
122 	 * {@inheritDoc}
123 	 * <p>
124 	 * Execute the {@code push} command with all the options and parameters
125 	 * collected by the setter methods of this class. Each instance of this
126 	 * class should only be used for one invocation of the command (means: one
127 	 * call to {@link #call()})
128 	 */
129 	@Override
130 	public Iterable<PushResult> call() throws GitAPIException,
131 			InvalidRemoteException,
132 			org.eclipse.jgit.api.errors.TransportException {
133 		checkCallable();
134 
135 		ArrayList<PushResult> pushResults = new ArrayList<>(3);
136 
137 		try {
138 			if (refSpecs.isEmpty()) {
139 				RemoteConfig config = new RemoteConfig(repo.getConfig(),
140 						getRemote());
141 				refSpecs.addAll(config.getPushRefSpecs());
142 			}
143 			if (refSpecs.isEmpty()) {
144 				Ref head = repo.exactRef(Constants.HEAD);
145 				if (head != null && head.isSymbolic())
146 					refSpecs.add(new RefSpec(head.getLeaf().getName()));
147 			}
148 
149 			if (force) {
150 				for (int i = 0; i < refSpecs.size(); i++)
151 					refSpecs.set(i, refSpecs.get(i).setForceUpdate(true));
152 			}
153 
154 			final List<Transport> transports;
155 			transports = Transport.openAll(repo, remote, Transport.Operation.PUSH);
156 			for (@SuppressWarnings("resource") // Explicitly closed in finally
157 					final Transport transport : transports) {
158 				transport.setPushThin(thin);
159 				transport.setPushAtomic(atomic);
160 				if (receivePack != null)
161 					transport.setOptionReceivePack(receivePack);
162 				transport.setDryRun(dryRun);
163 				transport.setPushOptions(pushOptions);
164 				configure(transport);
165 
166 				final Collection<RemoteRefUpdate> toPush = transport
167 						.findRemoteRefUpdatesFor(refSpecs, refLeaseSpecs);
168 
169 				try {
170 					PushResult result = transport.push(monitor, toPush, out);
171 					pushResults.add(result);
172 
173 				} catch (TooLargePackException e) {
174 					throw new org.eclipse.jgit.api.errors.TooLargePackException(
175 							e.getMessage(), e);
176 				} catch (TooLargeObjectInPackException e) {
177 					throw new org.eclipse.jgit.api.errors.TooLargeObjectInPackException(
178 							e.getMessage(), e);
179 				} catch (TransportException e) {
180 					throw new org.eclipse.jgit.api.errors.TransportException(
181 							e.getMessage(), e);
182 				} finally {
183 					transport.close();
184 				}
185 			}
186 
187 		} catch (URISyntaxException e) {
188 			throw new InvalidRemoteException(MessageFormat.format(
189 					JGitText.get().invalidRemote, remote));
190 		} catch (TransportException e) {
191 			throw new org.eclipse.jgit.api.errors.TransportException(
192 					e.getMessage(), e);
193 		} catch (NotSupportedException e) {
194 			throw new JGitInternalException(
195 					JGitText.get().exceptionCaughtDuringExecutionOfPushCommand,
196 					e);
197 		} catch (IOException e) {
198 			throw new JGitInternalException(
199 					JGitText.get().exceptionCaughtDuringExecutionOfPushCommand,
200 					e);
201 		}
202 
203 		return pushResults;
204 	}
205 
206 	/**
207 	 * The remote (uri or name) used for the push operation. If no remote is
208 	 * set, the default value of <code>Constants.DEFAULT_REMOTE_NAME</code> will
209 	 * be used.
210 	 *
211 	 * @see Constants#DEFAULT_REMOTE_NAME
212 	 * @param remote
213 	 *            the remote name
214 	 * @return {@code this}
215 	 */
216 	public PushCommand setRemote(String remote) {
217 		checkCallable();
218 		this.remote = remote;
219 		return this;
220 	}
221 
222 	/**
223 	 * Get remote name
224 	 *
225 	 * @return the remote used for the remote operation
226 	 */
227 	public String getRemote() {
228 		return remote;
229 	}
230 
231 	/**
232 	 * The remote executable providing receive-pack service for pack transports.
233 	 * If no receive-pack is set, the default value of
234 	 * <code>RemoteConfig.DEFAULT_RECEIVE_PACK</code> will be used.
235 	 *
236 	 * @see RemoteConfig#DEFAULT_RECEIVE_PACK
237 	 * @param receivePack
238 	 *            name of the remote executable providing the receive-pack
239 	 *            service
240 	 * @return {@code this}
241 	 */
242 	public PushCommand setReceivePack(String receivePack) {
243 		checkCallable();
244 		this.receivePack = receivePack;
245 		return this;
246 	}
247 
248 	/**
249 	 * Get the name of the remote executable providing the receive-pack service
250 	 *
251 	 * @return the receive-pack used for the remote operation
252 	 */
253 	public String getReceivePack() {
254 		return receivePack;
255 	}
256 
257 	/**
258 	 * Get timeout used for push operation
259 	 *
260 	 * @return the timeout used for the push operation
261 	 */
262 	public int getTimeout() {
263 		return timeout;
264 	}
265 
266 	/**
267 	 * Get the progress monitor
268 	 *
269 	 * @return the progress monitor for the push operation
270 	 */
271 	public ProgressMonitor getProgressMonitor() {
272 		return monitor;
273 	}
274 
275 	/**
276 	 * The progress monitor associated with the push operation. By default, this
277 	 * is set to <code>NullProgressMonitor</code>
278 	 *
279 	 * @see NullProgressMonitor
280 	 * @param monitor
281 	 *            a {@link org.eclipse.jgit.lib.ProgressMonitor}
282 	 * @return {@code this}
283 	 */
284 	public PushCommand setProgressMonitor(ProgressMonitor monitor) {
285 		checkCallable();
286 		if (monitor == null) {
287 			monitor = NullProgressMonitor.INSTANCE;
288 		}
289 		this.monitor = monitor;
290 		return this;
291 	}
292 
293 	/**
294 	 * Get the <code>RefLeaseSpec</code>s.
295 	 *
296 	 * @return the <code>RefLeaseSpec</code>s
297 	 * @since 4.7
298 	 */
299 	public List<RefLeaseSpec> getRefLeaseSpecs() {
300 		return new ArrayList<>(refLeaseSpecs.values());
301 	}
302 
303 	/**
304 	 * The ref lease specs to be used in the push operation, for a
305 	 * force-with-lease push operation.
306 	 *
307 	 * @param specs
308 	 *            a {@link org.eclipse.jgit.transport.RefLeaseSpec} object.
309 	 * @return {@code this}
310 	 * @since 4.7
311 	 */
312 	public PushCommand setRefLeaseSpecs(RefLeaseSpec... specs) {
313 		return setRefLeaseSpecs(Arrays.asList(specs));
314 	}
315 
316 	/**
317 	 * The ref lease specs to be used in the push operation, for a
318 	 * force-with-lease push operation.
319 	 *
320 	 * @param specs
321 	 *            list of {@code RefLeaseSpec}s
322 	 * @return {@code this}
323 	 * @since 4.7
324 	 */
325 	public PushCommand setRefLeaseSpecs(List<RefLeaseSpec> specs) {
326 		checkCallable();
327 		this.refLeaseSpecs.clear();
328 		for (RefLeaseSpec spec : specs) {
329 			refLeaseSpecs.put(spec.getRef(), spec);
330 		}
331 		return this;
332 	}
333 
334 	/**
335 	 * Get {@code RefSpec}s.
336 	 *
337 	 * @return the ref specs
338 	 */
339 	public List<RefSpec> getRefSpecs() {
340 		return refSpecs;
341 	}
342 
343 	/**
344 	 * The ref specs to be used in the push operation
345 	 *
346 	 * @param specs a {@link org.eclipse.jgit.transport.RefSpec} object.
347 	 * @return {@code this}
348 	 */
349 	public PushCommand setRefSpecs(RefSpec... specs) {
350 		checkCallable();
351 		this.refSpecs.clear();
352 		Collections.addAll(refSpecs, specs);
353 		return this;
354 	}
355 
356 	/**
357 	 * The ref specs to be used in the push operation
358 	 *
359 	 * @param specs
360 	 *            list of {@link org.eclipse.jgit.transport.RefSpec}s
361 	 * @return {@code this}
362 	 */
363 	public PushCommand setRefSpecs(List<RefSpec> specs) {
364 		checkCallable();
365 		this.refSpecs.clear();
366 		this.refSpecs.addAll(specs);
367 		return this;
368 	}
369 
370 	/**
371 	 * Push all branches under refs/heads/*.
372 	 *
373 	 * @return {code this}
374 	 */
375 	public PushCommand setPushAll() {
376 		refSpecs.add(Transport.REFSPEC_PUSH_ALL);
377 		return this;
378 	}
379 
380 	/**
381 	 * Push all tags under refs/tags/*.
382 	 *
383 	 * @return {code this}
384 	 */
385 	public PushCommand setPushTags() {
386 		refSpecs.add(Transport.REFSPEC_TAGS);
387 		return this;
388 	}
389 
390 	/**
391 	 * Add a reference to push.
392 	 *
393 	 * @param ref
394 	 *            the source reference. The remote name will match.
395 	 * @return {@code this}.
396 	 */
397 	public PushCommand add(Ref ref) {
398 		refSpecs.add(new RefSpec(ref.getLeaf().getName()));
399 		return this;
400 	}
401 
402 	/**
403 	 * Add a reference to push.
404 	 *
405 	 * @param nameOrSpec
406 	 *            any reference name, or a reference specification.
407 	 * @return {@code this}.
408 	 * @throws JGitInternalException
409 	 *             the reference name cannot be resolved.
410 	 */
411 	public PushCommand add(String nameOrSpec) {
412 		if (0 <= nameOrSpec.indexOf(':')) {
413 			refSpecs.add(new RefSpec(nameOrSpec));
414 		} else {
415 			Ref src;
416 			try {
417 				src = repo.findRef(nameOrSpec);
418 			} catch (IOException e) {
419 				throw new JGitInternalException(
420 						JGitText.get().exceptionCaughtDuringExecutionOfPushCommand,
421 						e);
422 			}
423 			if (src != null)
424 				add(src);
425 		}
426 		return this;
427 	}
428 
429 	/**
430 	 * Whether to run the push operation as a dry run
431 	 *
432 	 * @return the dry run preference for the push operation
433 	 */
434 	public boolean isDryRun() {
435 		return dryRun;
436 	}
437 
438 	/**
439 	 * Sets whether the push operation should be a dry run
440 	 *
441 	 * @param dryRun a boolean.
442 	 * @return {@code this}
443 	 */
444 	public PushCommand setDryRun(boolean dryRun) {
445 		checkCallable();
446 		this.dryRun = dryRun;
447 		return this;
448 	}
449 
450 	/**
451 	 * Get the thin-pack preference
452 	 *
453 	 * @return the thin-pack preference for push operation
454 	 */
455 	public boolean isThin() {
456 		return thin;
457 	}
458 
459 	/**
460 	 * Set the thin-pack preference for push operation.
461 	 *
462 	 * Default setting is Transport.DEFAULT_PUSH_THIN
463 	 *
464 	 * @param thin
465 	 *            the thin-pack preference value
466 	 * @return {@code this}
467 	 */
468 	public PushCommand setThin(boolean thin) {
469 		checkCallable();
470 		this.thin = thin;
471 		return this;
472 	}
473 
474 	/**
475 	 * Whether this push should be executed atomically (all references updated,
476 	 * or none)
477 	 *
478 	 * @return true if all-or-nothing behavior is requested.
479 	 * @since 4.2
480 	 */
481 	public boolean isAtomic() {
482 		return atomic;
483 	}
484 
485 	/**
486 	 * Requests atomic push (all references updated, or no updates).
487 	 *
488 	 * Default setting is false.
489 	 *
490 	 * @param atomic
491 	 *            whether to run the push atomically
492 	 * @return {@code this}
493 	 * @since 4.2
494 	 */
495 	public PushCommand setAtomic(boolean atomic) {
496 		checkCallable();
497 		this.atomic = atomic;
498 		return this;
499 	}
500 
501 	/**
502 	 * Whether to push forcefully
503 	 *
504 	 * @return the force preference for push operation
505 	 */
506 	public boolean isForce() {
507 		return force;
508 	}
509 
510 	/**
511 	 * Sets the force preference for push operation.
512 	 *
513 	 * @param force
514 	 *            whether to push forcefully
515 	 * @return {@code this}
516 	 */
517 	public PushCommand setForce(boolean force) {
518 		checkCallable();
519 		this.force = force;
520 		return this;
521 	}
522 
523 	/**
524 	 * Sets the output stream to write sideband messages to
525 	 *
526 	 * @param out
527 	 *            an {@link java.io.OutputStream}
528 	 * @return {@code this}
529 	 * @since 3.0
530 	 */
531 	public PushCommand setOutputStream(OutputStream out) {
532 		this.out = out;
533 		return this;
534 	}
535 
536 	/**
537 	 * Get push options
538 	 *
539 	 * @return the option strings associated with the push operation
540 	 * @since 4.5
541 	 */
542 	public List<String> getPushOptions() {
543 		return pushOptions;
544 	}
545 
546 	/**
547 	 * Set the option strings associated with the push operation.
548 	 *
549 	 * @param pushOptions
550 	 *            a {@link java.util.List} of push option strings
551 	 * @return {@code this}
552 	 * @since 4.5
553 	 */
554 	public PushCommand setPushOptions(List<String> pushOptions) {
555 		this.pushOptions = pushOptions;
556 		return this;
557 	}
558 }