View Javadoc
1   /*
2    * Copyright (C) 2008-2009, Google Inc.
3    * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
4    * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
5    * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
6    * and other copyright owners as documented in the project's IP log.
7    *
8    * This program and the accompanying materials are made available
9    * under the terms of the Eclipse Distribution License v1.0 which
10   * accompanies this distribution, is reproduced below, and is
11   * available at http://www.eclipse.org/org/documents/edl-v10.php
12   *
13   * All rights reserved.
14   *
15   * Redistribution and use in source and binary forms, with or
16   * without modification, are permitted provided that the following
17   * conditions are met:
18   *
19   * - Redistributions of source code must retain the above copyright
20   *   notice, this list of conditions and the following disclaimer.
21   *
22   * - Redistributions in binary form must reproduce the above
23   *   copyright notice, this list of conditions and the following
24   *   disclaimer in the documentation and/or other materials provided
25   *   with the distribution.
26   *
27   * - Neither the name of the Eclipse Foundation, Inc. nor the
28   *   names of its contributors may be used to endorse or promote
29   *   products derived from this software without specific prior
30   *   written permission.
31   *
32   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
33   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
34   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
36   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
38   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
39   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
40   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
41   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
42   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
43   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
44   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
45   */
46  
47  package org.eclipse.jgit.transport;
48  
49  import static org.eclipse.jgit.lib.RefDatabase.ALL;
50  
51  import java.io.BufferedReader;
52  import java.io.IOException;
53  import java.io.InputStream;
54  import java.io.InputStreamReader;
55  import java.io.OutputStream;
56  import java.io.PrintStream;
57  import java.lang.ref.WeakReference;
58  import java.lang.reflect.Field;
59  import java.lang.reflect.Modifier;
60  import java.net.URISyntaxException;
61  import java.net.URL;
62  import java.text.MessageFormat;
63  import java.util.ArrayList;
64  import java.util.Collection;
65  import java.util.Collections;
66  import java.util.Enumeration;
67  import java.util.HashSet;
68  import java.util.LinkedList;
69  import java.util.List;
70  import java.util.Map;
71  import java.util.Vector;
72  import java.util.concurrent.CopyOnWriteArrayList;
73  
74  import org.eclipse.jgit.api.errors.AbortedByHookException;
75  import org.eclipse.jgit.errors.NotSupportedException;
76  import org.eclipse.jgit.errors.TransportException;
77  import org.eclipse.jgit.hooks.Hooks;
78  import org.eclipse.jgit.hooks.PrePushHook;
79  import org.eclipse.jgit.internal.JGitText;
80  import org.eclipse.jgit.lib.Constants;
81  import org.eclipse.jgit.lib.ObjectChecker;
82  import org.eclipse.jgit.lib.ObjectId;
83  import org.eclipse.jgit.lib.ProgressMonitor;
84  import org.eclipse.jgit.lib.Ref;
85  import org.eclipse.jgit.lib.Repository;
86  import org.eclipse.jgit.storage.pack.PackConfig;
87  
88  /**
89   * Connects two Git repositories together and copies objects between them.
90   * <p>
91   * A transport can be used for either fetching (copying objects into the
92   * caller's repository from the remote repository) or pushing (copying objects
93   * into the remote repository from the caller's repository). Each transport
94   * implementation is responsible for the details associated with establishing
95   * the network connection(s) necessary for the copy, as well as actually
96   * shuffling data back and forth.
97   * <p>
98   * Transport instances and the connections they create are not thread-safe.
99   * Callers must ensure a transport is accessed by only one thread at a time.
100  */
101 public abstract class Transport implements AutoCloseable {
102 	/** Type of operation a Transport is being opened for. */
103 	public enum Operation {
104 		/** Transport is to fetch objects locally. */
105 		FETCH,
106 		/** Transport is to push objects remotely. */
107 		PUSH;
108 	}
109 
110 	private static final List<WeakReference<TransportProtocol>> protocols =
111 		new CopyOnWriteArrayList<>();
112 
113 	static {
114 		// Registration goes backwards in order of priority.
115 		register(TransportLocal.PROTO_LOCAL);
116 		register(TransportBundleFile.PROTO_BUNDLE);
117 		register(TransportAmazonS3.PROTO_S3);
118 		register(TransportGitAnon.PROTO_GIT);
119 		register(TransportSftp.PROTO_SFTP);
120 		register(TransportHttp.PROTO_FTP);
121 		register(TransportHttp.PROTO_HTTP);
122 		register(TransportGitSsh.PROTO_SSH);
123 
124 		registerByService();
125 	}
126 
127 	private static void registerByService() {
128 		ClassLoader ldr = Thread.currentThread().getContextClassLoader();
129 		if (ldr == null)
130 			ldr = Transport.class.getClassLoader();
131 		Enumeration<URL> catalogs = catalogs(ldr);
132 		while (catalogs.hasMoreElements())
133 			scan(ldr, catalogs.nextElement());
134 	}
135 
136 	private static Enumeration<URL> catalogs(ClassLoader ldr) {
137 		try {
138 			String prefix = "META-INF/services/"; //$NON-NLS-1$
139 			String name = prefix + Transport.class.getName();
140 			return ldr.getResources(name);
141 		} catch (IOException err) {
142 			return new Vector<URL>().elements();
143 		}
144 	}
145 
146 	private static void scan(ClassLoader ldr, URL url) {
147 		BufferedReader br;
148 		try {
149 			InputStream urlIn = url.openStream();
150 			br = new BufferedReader(new InputStreamReader(urlIn, "UTF-8")); //$NON-NLS-1$
151 		} catch (IOException err) {
152 			// If we cannot read from the service list, go to the next.
153 			//
154 			return;
155 		}
156 
157 		try {
158 			String line;
159 			while ((line = br.readLine()) != null) {
160 				line = line.trim();
161 				if (line.length() == 0)
162 					continue;
163 				int comment = line.indexOf('#');
164 				if (comment == 0)
165 					continue;
166 				if (comment != -1)
167 					line = line.substring(0, comment).trim();
168 				load(ldr, line);
169 			}
170 		} catch (IOException err) {
171 			// If we failed during a read, ignore the error.
172 			//
173 		} finally {
174 			try {
175 				br.close();
176 			} catch (IOException e) {
177 				// Ignore the close error; we are only reading.
178 			}
179 		}
180 	}
181 
182 	private static void load(ClassLoader ldr, String cn) {
183 		Class<?> clazz;
184 		try {
185 			clazz = Class.forName(cn, false, ldr);
186 		} catch (ClassNotFoundException notBuiltin) {
187 			// Doesn't exist, even though the service entry is present.
188 			//
189 			return;
190 		}
191 
192 		for (Field f : clazz.getDeclaredFields()) {
193 			if ((f.getModifiers() & Modifier.STATIC) == Modifier.STATIC
194 					&& TransportProtocol.class.isAssignableFrom(f.getType())) {
195 				TransportProtocol proto;
196 				try {
197 					proto = (TransportProtocol) f.get(null);
198 				} catch (IllegalArgumentException e) {
199 					// If we cannot access the field, don't.
200 					continue;
201 				} catch (IllegalAccessException e) {
202 					// If we cannot access the field, don't.
203 					continue;
204 				}
205 				if (proto != null)
206 					register(proto);
207 			}
208 		}
209 	}
210 
211 	/**
212 	 * Register a TransportProtocol instance for use during open.
213 	 * <p>
214 	 * Protocol definitions are held by WeakReference, allowing them to be
215 	 * garbage collected when the calling application drops all strongly held
216 	 * references to the TransportProtocol. Therefore applications should use a
217 	 * singleton pattern as described in
218 	 * {@link org.eclipse.jgit.transport.TransportProtocol}'s class
219 	 * documentation to ensure their protocol does not get disabled by garbage
220 	 * collection earlier than expected.
221 	 * <p>
222 	 * The new protocol is registered in front of all earlier protocols, giving
223 	 * it higher priority than the built-in protocol definitions.
224 	 *
225 	 * @param proto
226 	 *            the protocol definition. Must not be null.
227 	 */
228 	public static void register(TransportProtocol proto) {
229 		protocols.add(0, new WeakReference<>(proto));
230 	}
231 
232 	/**
233 	 * Unregister a TransportProtocol instance.
234 	 * <p>
235 	 * Unregistering a protocol usually isn't necessary, as protocols are held
236 	 * by weak references and will automatically clear when they are garbage
237 	 * collected by the JVM. Matching is handled by reference equality, so the
238 	 * exact reference given to {@link #register(TransportProtocol)} must be
239 	 * used.
240 	 *
241 	 * @param proto
242 	 *            the exact object previously given to register.
243 	 */
244 	public static void unregister(TransportProtocol proto) {
245 		for (WeakReference<TransportProtocol> ref : protocols) {
246 			TransportProtocol refProto = ref.get();
247 			if (refProto == null || refProto == proto)
248 				protocols.remove(ref);
249 		}
250 	}
251 
252 	/**
253 	 * Obtain a copy of the registered protocols.
254 	 *
255 	 * @return an immutable copy of the currently registered protocols.
256 	 */
257 	public static List<TransportProtocol> getTransportProtocols() {
258 		int cnt = protocols.size();
259 		List<TransportProtocol> res = new ArrayList<>(cnt);
260 		for (WeakReference<TransportProtocol> ref : protocols) {
261 			TransportProtocol proto = ref.get();
262 			if (proto != null)
263 				res.add(proto);
264 			else
265 				protocols.remove(ref);
266 		}
267 		return Collections.unmodifiableList(res);
268 	}
269 
270 	/**
271 	 * Open a new transport instance to connect two repositories.
272 	 * <p>
273 	 * This method assumes
274 	 * {@link org.eclipse.jgit.transport.Transport.Operation#FETCH}.
275 	 *
276 	 * @param local
277 	 *            existing local repository.
278 	 * @param remote
279 	 *            location of the remote repository - may be URI or remote
280 	 *            configuration name.
281 	 * @return the new transport instance. Never null. In case of multiple URIs
282 	 *         in remote configuration, only the first is chosen.
283 	 * @throws java.net.URISyntaxException
284 	 *             the location is not a remote defined in the configuration
285 	 *             file and is not a well-formed URL.
286 	 * @throws org.eclipse.jgit.errors.NotSupportedException
287 	 *             the protocol specified is not supported.
288 	 * @throws org.eclipse.jgit.errors.TransportException
289 	 *             the transport cannot open this URI.
290 	 */
291 	public static Transport open(final Repository local, final String remote)
292 			throws NotSupportedException, URISyntaxException,
293 			TransportException {
294 		return open(local, remote, Operation.FETCH);
295 	}
296 
297 	/**
298 	 * Open a new transport instance to connect two repositories.
299 	 *
300 	 * @param local
301 	 *            existing local repository.
302 	 * @param remote
303 	 *            location of the remote repository - may be URI or remote
304 	 *            configuration name.
305 	 * @param op
306 	 *            planned use of the returned Transport; the URI may differ
307 	 *            based on the type of connection desired.
308 	 * @return the new transport instance. Never null. In case of multiple URIs
309 	 *         in remote configuration, only the first is chosen.
310 	 * @throws java.net.URISyntaxException
311 	 *             the location is not a remote defined in the configuration
312 	 *             file and is not a well-formed URL.
313 	 * @throws org.eclipse.jgit.errors.NotSupportedException
314 	 *             the protocol specified is not supported.
315 	 * @throws org.eclipse.jgit.errors.TransportException
316 	 *             the transport cannot open this URI.
317 	 */
318 	public static Transport open(final Repository local, final String remote,
319 			final Operation op) throws NotSupportedException,
320 			URISyntaxException, TransportException {
321 		if (local != null) {
322 			final RemoteConfig cfg = new RemoteConfig(local.getConfig(), remote);
323 			if (doesNotExist(cfg))
324 				return open(local, new URIish(remote), null);
325 			return open(local, cfg, op);
326 		} else
327 			return open(new URIish(remote));
328 
329 	}
330 
331 	/**
332 	 * Open new transport instances to connect two repositories.
333 	 * <p>
334 	 * This method assumes
335 	 * {@link org.eclipse.jgit.transport.Transport.Operation#FETCH}.
336 	 *
337 	 * @param local
338 	 *            existing local repository.
339 	 * @param remote
340 	 *            location of the remote repository - may be URI or remote
341 	 *            configuration name.
342 	 * @return the list of new transport instances for every URI in remote
343 	 *         configuration.
344 	 * @throws java.net.URISyntaxException
345 	 *             the location is not a remote defined in the configuration
346 	 *             file and is not a well-formed URL.
347 	 * @throws org.eclipse.jgit.errors.NotSupportedException
348 	 *             the protocol specified is not supported.
349 	 * @throws org.eclipse.jgit.errors.TransportException
350 	 *             the transport cannot open this URI.
351 	 */
352 	public static List<Transport> openAll(final Repository local,
353 			final String remote) throws NotSupportedException,
354 			URISyntaxException, TransportException {
355 		return openAll(local, remote, Operation.FETCH);
356 	}
357 
358 	/**
359 	 * Open new transport instances to connect two repositories.
360 	 *
361 	 * @param local
362 	 *            existing local repository.
363 	 * @param remote
364 	 *            location of the remote repository - may be URI or remote
365 	 *            configuration name.
366 	 * @param op
367 	 *            planned use of the returned Transport; the URI may differ
368 	 *            based on the type of connection desired.
369 	 * @return the list of new transport instances for every URI in remote
370 	 *         configuration.
371 	 * @throws java.net.URISyntaxException
372 	 *             the location is not a remote defined in the configuration
373 	 *             file and is not a well-formed URL.
374 	 * @throws org.eclipse.jgit.errors.NotSupportedException
375 	 *             the protocol specified is not supported.
376 	 * @throws org.eclipse.jgit.errors.TransportException
377 	 *             the transport cannot open this URI.
378 	 */
379 	public static List<Transport> openAll(final Repository local,
380 			final String remote, final Operation op)
381 			throws NotSupportedException, URISyntaxException,
382 			TransportException {
383 		final RemoteConfig cfg = new RemoteConfig(local.getConfig(), remote);
384 		if (doesNotExist(cfg)) {
385 			final ArrayList<Transport> transports = new ArrayList<>(1);
386 			transports.add(open(local, new URIish(remote), null));
387 			return transports;
388 		}
389 		return openAll(local, cfg, op);
390 	}
391 
392 	/**
393 	 * Open a new transport instance to connect two repositories.
394 	 * <p>
395 	 * This method assumes
396 	 * {@link org.eclipse.jgit.transport.Transport.Operation#FETCH}.
397 	 *
398 	 * @param local
399 	 *            existing local repository.
400 	 * @param cfg
401 	 *            configuration describing how to connect to the remote
402 	 *            repository.
403 	 * @return the new transport instance. Never null. In case of multiple URIs
404 	 *         in remote configuration, only the first is chosen.
405 	 * @throws org.eclipse.jgit.errors.NotSupportedException
406 	 *             the protocol specified is not supported.
407 	 * @throws org.eclipse.jgit.errors.TransportException
408 	 *             the transport cannot open this URI.
409 	 * @throws java.lang.IllegalArgumentException
410 	 *             if provided remote configuration doesn't have any URI
411 	 *             associated.
412 	 */
413 	public static Transport open(final Repository local, final RemoteConfig cfg)
414 			throws NotSupportedException, TransportException {
415 		return open(local, cfg, Operation.FETCH);
416 	}
417 
418 	/**
419 	 * Open a new transport instance to connect two repositories.
420 	 *
421 	 * @param local
422 	 *            existing local repository.
423 	 * @param cfg
424 	 *            configuration describing how to connect to the remote
425 	 *            repository.
426 	 * @param op
427 	 *            planned use of the returned Transport; the URI may differ
428 	 *            based on the type of connection desired.
429 	 * @return the new transport instance. Never null. In case of multiple URIs
430 	 *         in remote configuration, only the first is chosen.
431 	 * @throws org.eclipse.jgit.errors.NotSupportedException
432 	 *             the protocol specified is not supported.
433 	 * @throws org.eclipse.jgit.errors.TransportException
434 	 *             the transport cannot open this URI.
435 	 * @throws java.lang.IllegalArgumentException
436 	 *             if provided remote configuration doesn't have any URI
437 	 *             associated.
438 	 */
439 	public static Transport open(final Repository local,
440 			final RemoteConfig cfg, final Operation op)
441 			throws NotSupportedException, TransportException {
442 		final List<URIish> uris = getURIs(cfg, op);
443 		if (uris.isEmpty())
444 			throw new IllegalArgumentException(MessageFormat.format(
445 					JGitText.get().remoteConfigHasNoURIAssociated, cfg.getName()));
446 		final Transport tn = open(local, uris.get(0), cfg.getName());
447 		tn.applyConfig(cfg);
448 		return tn;
449 	}
450 
451 	/**
452 	 * Open new transport instances to connect two repositories.
453 	 * <p>
454 	 * This method assumes
455 	 * {@link org.eclipse.jgit.transport.Transport.Operation#FETCH}.
456 	 *
457 	 * @param local
458 	 *            existing local repository.
459 	 * @param cfg
460 	 *            configuration describing how to connect to the remote
461 	 *            repository.
462 	 * @return the list of new transport instances for every URI in remote
463 	 *         configuration.
464 	 * @throws org.eclipse.jgit.errors.NotSupportedException
465 	 *             the protocol specified is not supported.
466 	 * @throws org.eclipse.jgit.errors.TransportException
467 	 *             the transport cannot open this URI.
468 	 */
469 	public static List<Transport> openAll(final Repository local,
470 			final RemoteConfig cfg) throws NotSupportedException,
471 			TransportException {
472 		return openAll(local, cfg, Operation.FETCH);
473 	}
474 
475 	/**
476 	 * Open new transport instances to connect two repositories.
477 	 *
478 	 * @param local
479 	 *            existing local repository.
480 	 * @param cfg
481 	 *            configuration describing how to connect to the remote
482 	 *            repository.
483 	 * @param op
484 	 *            planned use of the returned Transport; the URI may differ
485 	 *            based on the type of connection desired.
486 	 * @return the list of new transport instances for every URI in remote
487 	 *         configuration.
488 	 * @throws org.eclipse.jgit.errors.NotSupportedException
489 	 *             the protocol specified is not supported.
490 	 * @throws org.eclipse.jgit.errors.TransportException
491 	 *             the transport cannot open this URI.
492 	 */
493 	public static List<Transport> openAll(final Repository local,
494 			final RemoteConfig cfg, final Operation op)
495 			throws NotSupportedException, TransportException {
496 		final List<URIish> uris = getURIs(cfg, op);
497 		final List<Transport> transports = new ArrayList<>(uris.size());
498 		for (final URIish uri : uris) {
499 			final Transport tn = open(local, uri, cfg.getName());
500 			tn.applyConfig(cfg);
501 			transports.add(tn);
502 		}
503 		return transports;
504 	}
505 
506 	private static List<URIish> getURIs(final RemoteConfig cfg,
507 			final Operation op) {
508 		switch (op) {
509 		case FETCH:
510 			return cfg.getURIs();
511 		case PUSH: {
512 			List<URIish> uris = cfg.getPushURIs();
513 			if (uris.isEmpty())
514 				uris = cfg.getURIs();
515 			return uris;
516 		}
517 		default:
518 			throw new IllegalArgumentException(op.toString());
519 		}
520 	}
521 
522 	private static boolean doesNotExist(final RemoteConfig cfg) {
523 		return cfg.getURIs().isEmpty() && cfg.getPushURIs().isEmpty();
524 	}
525 
526 	/**
527 	 * Open a new transport instance to connect two repositories.
528 	 *
529 	 * @param local
530 	 *            existing local repository.
531 	 * @param uri
532 	 *            location of the remote repository.
533 	 * @return the new transport instance. Never null.
534 	 * @throws org.eclipse.jgit.errors.NotSupportedException
535 	 *             the protocol specified is not supported.
536 	 * @throws org.eclipse.jgit.errors.TransportException
537 	 *             the transport cannot open this URI.
538 	 */
539 	public static Transport open(final Repository local, final URIish uri)
540 			throws NotSupportedException, TransportException {
541 		return open(local, uri, null);
542 	}
543 
544 	/**
545 	 * Open a new transport instance to connect two repositories.
546 	 *
547 	 * @param local
548 	 *            existing local repository.
549 	 * @param uri
550 	 *            location of the remote repository.
551 	 * @param remoteName
552 	 *            name of the remote, if the remote as configured in
553 	 *            {@code local}; otherwise null.
554 	 * @return the new transport instance. Never null.
555 	 * @throws org.eclipse.jgit.errors.NotSupportedException
556 	 *             the protocol specified is not supported.
557 	 * @throws org.eclipse.jgit.errors.TransportException
558 	 *             the transport cannot open this URI.
559 	 */
560 	public static Transport open(Repository local, URIish uri, String remoteName)
561 			throws NotSupportedException, TransportException {
562 		for (WeakReference<TransportProtocol> ref : protocols) {
563 			TransportProtocol proto = ref.get();
564 			if (proto == null) {
565 				protocols.remove(ref);
566 				continue;
567 			}
568 
569 			if (proto.canHandle(uri, local, remoteName)) {
570 				Transport tn = proto.open(uri, local, remoteName);
571 				tn.prePush = Hooks.prePush(local, tn.hookOutRedirect);
572 				tn.prePush.setRemoteLocation(uri.toString());
573 				tn.prePush.setRemoteName(remoteName);
574 				return tn;
575 			}
576 		}
577 
578 		throw new NotSupportedException(MessageFormat.format(JGitText.get().URINotSupported, uri));
579 	}
580 
581 	/**
582 	 * Open a new transport with no local repository.
583 	 * <p>
584 	 * Note that the resulting transport instance can not be used for fetching
585 	 * or pushing, but only for reading remote refs.
586 	 *
587 	 * @param uri a {@link org.eclipse.jgit.transport.URIish} object.
588 	 * @return new Transport instance
589 	 * @throws org.eclipse.jgit.errors.NotSupportedException
590 	 * @throws org.eclipse.jgit.errors.TransportException
591 	 */
592 	public static Transport open(URIish uri) throws NotSupportedException, TransportException {
593 		for (WeakReference<TransportProtocol> ref : protocols) {
594 			TransportProtocol proto = ref.get();
595 			if (proto == null) {
596 				protocols.remove(ref);
597 				continue;
598 			}
599 
600 			if (proto.canHandle(uri, null, null))
601 				return proto.open(uri);
602 		}
603 
604 		throw new NotSupportedException(MessageFormat.format(JGitText.get().URINotSupported, uri));
605 	}
606 
607 	/**
608 	 * Convert push remote refs update specification from
609 	 * {@link org.eclipse.jgit.transport.RefSpec} form to
610 	 * {@link org.eclipse.jgit.transport.RemoteRefUpdate}. Conversion expands
611 	 * wildcards by matching source part to local refs. expectedOldObjectId in
612 	 * RemoteRefUpdate is set when specified in leases. Tracking branch is
613 	 * configured if RefSpec destination matches source of any fetch ref spec
614 	 * for this transport remote configuration.
615 	 *
616 	 * @param db
617 	 *            local database.
618 	 * @param specs
619 	 *            collection of RefSpec to convert.
620 	 * @param leases
621 	 *            map from ref to lease (containing expected old object id)
622 	 * @param fetchSpecs
623 	 *            fetch specifications used for finding localtracking refs. May
624 	 *            be null or empty collection.
625 	 * @return collection of set up
626 	 *         {@link org.eclipse.jgit.transport.RemoteRefUpdate}.
627 	 * @throws java.io.IOException
628 	 *             when problem occurred during conversion or specification set
629 	 *             up: most probably, missing objects or refs.
630 	 * @since 4.7
631 	 */
632 	public static Collection<RemoteRefUpdate> findRemoteRefUpdatesFor(
633 			final Repository db, final Collection<RefSpec> specs,
634 			final Map<String, RefLeaseSpec> leases,
635 			Collection<RefSpec> fetchSpecs) throws IOException {
636 		if (fetchSpecs == null)
637 			fetchSpecs = Collections.emptyList();
638 		final List<RemoteRefUpdate> result = new LinkedList<>();
639 		final Collection<RefSpec> procRefs = expandPushWildcardsFor(db, specs);
640 
641 		for (final RefSpec spec : procRefs) {
642 			String srcSpec = spec.getSource();
643 			final Ref srcRef = db.findRef(srcSpec);
644 			if (srcRef != null)
645 				srcSpec = srcRef.getName();
646 
647 			String destSpec = spec.getDestination();
648 			if (destSpec == null) {
649 				// No destination (no-colon in ref-spec), DWIMery assumes src
650 				//
651 				destSpec = srcSpec;
652 			}
653 
654 			if (srcRef != null && !destSpec.startsWith(Constants.R_REFS)) {
655 				// Assume the same kind of ref at the destination, e.g.
656 				// "refs/heads/foo:master", DWIMery assumes master is also
657 				// under "refs/heads/".
658 				//
659 				final String n = srcRef.getName();
660 				final int kindEnd = n.indexOf('/', Constants.R_REFS.length());
661 				destSpec = n.substring(0, kindEnd + 1) + destSpec;
662 			}
663 
664 			final boolean forceUpdate = spec.isForceUpdate();
665 			final String localName = findTrackingRefName(destSpec, fetchSpecs);
666 			final RefLeaseSpec leaseSpec = leases.get(destSpec);
667 			final ObjectId expected = leaseSpec == null ? null :
668 				db.resolve(leaseSpec.getExpected());
669 			final RemoteRefUpdate rru = new RemoteRefUpdate(db, srcSpec,
670 					destSpec, forceUpdate, localName, expected);
671 			result.add(rru);
672 		}
673 		return result;
674 	}
675 
676 	/**
677 	 * Convert push remote refs update specification from
678 	 * {@link org.eclipse.jgit.transport.RefSpec} form to
679 	 * {@link org.eclipse.jgit.transport.RemoteRefUpdate}. Conversion expands
680 	 * wildcards by matching source part to local refs. expectedOldObjectId in
681 	 * RemoteRefUpdate is always set as null. Tracking branch is configured if
682 	 * RefSpec destination matches source of any fetch ref spec for this
683 	 * transport remote configuration.
684 	 *
685 	 * @param db
686 	 *            local database.
687 	 * @param specs
688 	 *            collection of RefSpec to convert.
689 	 * @param fetchSpecs
690 	 *            fetch specifications used for finding localtracking refs. May
691 	 *            be null or empty collection.
692 	 * @return collection of set up
693 	 *         {@link org.eclipse.jgit.transport.RemoteRefUpdate}.
694 	 * @throws java.io.IOException
695 	 *             when problem occurred during conversion or specification set
696 	 *             up: most probably, missing objects or refs.
697 	 */
698 	public static Collection<RemoteRefUpdate> findRemoteRefUpdatesFor(
699 			final Repository db, final Collection<RefSpec> specs,
700 			Collection<RefSpec> fetchSpecs) throws IOException {
701 		return findRemoteRefUpdatesFor(db, specs, Collections.emptyMap(),
702 					       fetchSpecs);
703 	}
704 
705 	private static Collection<RefSpec> expandPushWildcardsFor(
706 			final Repository db, final Collection<RefSpec> specs)
707 			throws IOException {
708 		final Map<String, Ref> localRefs = db.getRefDatabase().getRefs(ALL);
709 		final Collection<RefSpec> procRefs = new HashSet<>();
710 
711 		for (final RefSpec spec : specs) {
712 			if (spec.isWildcard()) {
713 				for (final Ref localRef : localRefs.values()) {
714 					if (spec.matchSource(localRef))
715 						procRefs.add(spec.expandFromSource(localRef));
716 				}
717 			} else {
718 				procRefs.add(spec);
719 			}
720 		}
721 		return procRefs;
722 	}
723 
724 	private static String findTrackingRefName(final String remoteName,
725 			final Collection<RefSpec> fetchSpecs) {
726 		// try to find matching tracking refs
727 		for (final RefSpec fetchSpec : fetchSpecs) {
728 			if (fetchSpec.matchSource(remoteName)) {
729 				if (fetchSpec.isWildcard())
730 					return fetchSpec.expandFromSource(remoteName)
731 							.getDestination();
732 				else
733 					return fetchSpec.getDestination();
734 			}
735 		}
736 		return null;
737 	}
738 
739 	/**
740 	 * Default setting for {@link #fetchThin} option.
741 	 */
742 	public static final boolean DEFAULT_FETCH_THIN = true;
743 
744 	/**
745 	 * Default setting for {@link #pushThin} option.
746 	 */
747 	public static final boolean DEFAULT_PUSH_THIN = false;
748 
749 	/**
750 	 * Specification for fetch or push operations, to fetch or push all tags.
751 	 * Acts as --tags.
752 	 */
753 	public static final RefSpec REFSPEC_TAGS = new RefSpec(
754 			"refs/tags/*:refs/tags/*"); //$NON-NLS-1$
755 
756 	/**
757 	 * Specification for push operation, to push all refs under refs/heads. Acts
758 	 * as --all.
759 	 */
760 	public static final RefSpec REFSPEC_PUSH_ALL = new RefSpec(
761 			"refs/heads/*:refs/heads/*"); //$NON-NLS-1$
762 
763 	/** The repository this transport fetches into, or pushes out of. */
764 	protected final Repository local;
765 
766 	/** The URI used to create this transport. */
767 	protected final URIish uri;
768 
769 	/** Name of the upload pack program, if it must be executed. */
770 	private String optionUploadPack = RemoteConfig.DEFAULT_UPLOAD_PACK;
771 
772 	/** Specifications to apply during fetch. */
773 	private List<RefSpec> fetch = Collections.emptyList();
774 
775 	/**
776 	 * How {@link #fetch(ProgressMonitor, Collection)} should handle tags.
777 	 * <p>
778 	 * We default to {@link TagOpt#NO_TAGS} so as to avoid fetching annotated
779 	 * tags during one-shot fetches used for later merges. This prevents
780 	 * dragging down tags from repositories that we do not have established
781 	 * tracking branches for. If we do not track the source repository, we most
782 	 * likely do not care about any tags it publishes.
783 	 */
784 	private TagOpt tagopt = TagOpt.NO_TAGS;
785 
786 	/** Should fetch request thin-pack if remote repository can produce it. */
787 	private boolean fetchThin = DEFAULT_FETCH_THIN;
788 
789 	/** Name of the receive pack program, if it must be executed. */
790 	private String optionReceivePack = RemoteConfig.DEFAULT_RECEIVE_PACK;
791 
792 	/** Specifications to apply during push. */
793 	private List<RefSpec> push = Collections.emptyList();
794 
795 	/** Should push produce thin-pack when sending objects to remote repository. */
796 	private boolean pushThin = DEFAULT_PUSH_THIN;
797 
798 	/** Should push be all-or-nothing atomic behavior? */
799 	private boolean pushAtomic;
800 
801 	/** Should push just check for operation result, not really push. */
802 	private boolean dryRun;
803 
804 	/** Should an incoming (fetch) transfer validate objects? */
805 	private ObjectChecker objectChecker;
806 
807 	/** Should refs no longer on the source be pruned from the destination? */
808 	private boolean removeDeletedRefs;
809 
810 	/** Timeout in seconds to wait before aborting an IO read or write. */
811 	private int timeout;
812 
813 	/** Pack configuration used by this transport to make pack file. */
814 	private PackConfig packConfig;
815 
816 	/** Assists with authentication the connection. */
817 	private CredentialsProvider credentialsProvider;
818 
819 	/** The option strings associated with the push operation. */
820 	private List<String> pushOptions;
821 
822 	private PrintStream hookOutRedirect;
823 
824 	private PrePushHook prePush;
825 	/**
826 	 * Create a new transport instance.
827 	 *
828 	 * @param local
829 	 *            the repository this instance will fetch into, or push out of.
830 	 *            This must be the repository passed to
831 	 *            {@link #open(Repository, URIish)}.
832 	 * @param uri
833 	 *            the URI used to access the remote repository. This must be the
834 	 *            URI passed to {@link #open(Repository, URIish)}.
835 	 */
836 	protected Transport(final Repository local, final URIish uri) {
837 		final TransferConfig tc = local.getConfig().get(TransferConfig.KEY);
838 		this.local = local;
839 		this.uri = uri;
840 		this.objectChecker = tc.newObjectChecker();
841 		this.credentialsProvider = CredentialsProvider.getDefault();
842 		prePush = Hooks.prePush(local, hookOutRedirect);
843 	}
844 
845 	/**
846 	 * Create a minimal transport instance not tied to a single repository.
847 	 *
848 	 * @param uri
849 	 *            a {@link org.eclipse.jgit.transport.URIish} object.
850 	 */
851 	protected Transport(final URIish uri) {
852 		this.uri = uri;
853 		this.local = null;
854 		this.objectChecker = new ObjectChecker();
855 		this.credentialsProvider = CredentialsProvider.getDefault();
856 	}
857 
858 	/**
859 	 * Get the URI this transport connects to.
860 	 * <p>
861 	 * Each transport instance connects to at most one URI at any point in time.
862 	 *
863 	 * @return the URI describing the location of the remote repository.
864 	 */
865 	public URIish getURI() {
866 		return uri;
867 	}
868 
869 	/**
870 	 * Get the name of the remote executable providing upload-pack service.
871 	 *
872 	 * @return typically "git-upload-pack".
873 	 */
874 	public String getOptionUploadPack() {
875 		return optionUploadPack;
876 	}
877 
878 	/**
879 	 * Set the name of the remote executable providing upload-pack services.
880 	 *
881 	 * @param where
882 	 *            name of the executable.
883 	 */
884 	public void setOptionUploadPack(final String where) {
885 		if (where != null && where.length() > 0)
886 			optionUploadPack = where;
887 		else
888 			optionUploadPack = RemoteConfig.DEFAULT_UPLOAD_PACK;
889 	}
890 
891 	/**
892 	 * Get the description of how annotated tags should be treated during fetch.
893 	 *
894 	 * @return option indicating the behavior of annotated tags in fetch.
895 	 */
896 	public TagOpt getTagOpt() {
897 		return tagopt;
898 	}
899 
900 	/**
901 	 * Set the description of how annotated tags should be treated on fetch.
902 	 *
903 	 * @param option
904 	 *            method to use when handling annotated tags.
905 	 */
906 	public void setTagOpt(final TagOpt option) {
907 		tagopt = option != null ? option : TagOpt.AUTO_FOLLOW;
908 	}
909 
910 	/**
911 	 * Default setting is: {@link #DEFAULT_FETCH_THIN}
912 	 *
913 	 * @return true if fetch should request thin-pack when possible; false
914 	 *         otherwise
915 	 * @see PackTransport
916 	 */
917 	public boolean isFetchThin() {
918 		return fetchThin;
919 	}
920 
921 	/**
922 	 * Set the thin-pack preference for fetch operation. Default setting is:
923 	 * {@link #DEFAULT_FETCH_THIN}
924 	 *
925 	 * @param fetchThin
926 	 *            true when fetch should request thin-pack when possible; false
927 	 *            when it shouldn't
928 	 * @see PackTransport
929 	 */
930 	public void setFetchThin(final boolean fetchThin) {
931 		this.fetchThin = fetchThin;
932 	}
933 
934 	/**
935 	 * Whether fetch will verify if received objects are formatted correctly.
936 	 *
937 	 * @return true if fetch will verify received objects are formatted
938 	 *         correctly. Validating objects requires more CPU time on the
939 	 *         client side of the connection.
940 	 */
941 	public boolean isCheckFetchedObjects() {
942 		return getObjectChecker() != null;
943 	}
944 
945 	/**
946 	 * Configure if checking received objects is enabled
947 	 *
948 	 * @param check
949 	 *            true to enable checking received objects; false to assume all
950 	 *            received objects are valid.
951 	 * @see #setObjectChecker(ObjectChecker)
952 	 */
953 	public void setCheckFetchedObjects(final boolean check) {
954 		if (check && objectChecker == null)
955 			setObjectChecker(new ObjectChecker());
956 		else if (!check && objectChecker != null)
957 			setObjectChecker(null);
958 	}
959 
960 	/**
961 	 * Get configured object checker for received objects
962 	 *
963 	 * @return configured object checker for received objects, or null.
964 	 * @since 3.6
965 	 */
966 	public ObjectChecker getObjectChecker() {
967 		return objectChecker;
968 	}
969 
970 	/**
971 	 * Set the object checker to verify each received object with
972 	 *
973 	 * @param impl
974 	 *            if non-null the object checking instance to verify each
975 	 *            received object with; null to disable object checking.
976 	 * @since 3.6
977 	 */
978 	public void setObjectChecker(ObjectChecker impl) {
979 		objectChecker = impl;
980 	}
981 
982 	/**
983 	 * Default setting is:
984 	 * {@link org.eclipse.jgit.transport.RemoteConfig#DEFAULT_RECEIVE_PACK}
985 	 *
986 	 * @return remote executable providing receive-pack service for pack
987 	 *         transports.
988 	 * @see PackTransport
989 	 */
990 	public String getOptionReceivePack() {
991 		return optionReceivePack;
992 	}
993 
994 	/**
995 	 * Set remote executable providing receive-pack service for pack transports.
996 	 * Default setting is:
997 	 * {@link org.eclipse.jgit.transport.RemoteConfig#DEFAULT_RECEIVE_PACK}
998 	 *
999 	 * @param optionReceivePack
1000 	 *            remote executable, if null or empty default one is set;
1001 	 */
1002 	public void setOptionReceivePack(String optionReceivePack) {
1003 		if (optionReceivePack != null && optionReceivePack.length() > 0)
1004 			this.optionReceivePack = optionReceivePack;
1005 		else
1006 			this.optionReceivePack = RemoteConfig.DEFAULT_RECEIVE_PACK;
1007 	}
1008 
1009 	/**
1010 	 * Default setting is: {@value #DEFAULT_PUSH_THIN}
1011 	 *
1012 	 * @return true if push should produce thin-pack in pack transports
1013 	 * @see PackTransport
1014 	 */
1015 	public boolean isPushThin() {
1016 		return pushThin;
1017 	}
1018 
1019 	/**
1020 	 * Set thin-pack preference for push operation. Default setting is:
1021 	 * {@value #DEFAULT_PUSH_THIN}
1022 	 *
1023 	 * @param pushThin
1024 	 *            true when push should produce thin-pack in pack transports;
1025 	 *            false when it shouldn't
1026 	 * @see PackTransport
1027 	 */
1028 	public void setPushThin(final boolean pushThin) {
1029 		this.pushThin = pushThin;
1030 	}
1031 
1032 	/**
1033 	 * Default setting is false.
1034 	 *
1035 	 * @return true if push requires all-or-nothing atomic behavior.
1036 	 * @since 4.2
1037 	 */
1038 	public boolean isPushAtomic() {
1039 		return pushAtomic;
1040 	}
1041 
1042 	/**
1043 	 * Request atomic push (all references succeed, or none do).
1044 	 * <p>
1045 	 * Server must also support atomic push. If the server does not support the
1046 	 * feature the push will abort without making changes.
1047 	 *
1048 	 * @param atomic
1049 	 *            true when push should be an all-or-nothing operation.
1050 	 * @see PackTransport
1051 	 * @since 4.2
1052 	 */
1053 	public void setPushAtomic(final boolean atomic) {
1054 		this.pushAtomic = atomic;
1055 	}
1056 
1057 	/**
1058 	 * Whether destination refs should be removed if they no longer exist at the
1059 	 * source repository.
1060 	 *
1061 	 * @return true if destination refs should be removed if they no longer
1062 	 *         exist at the source repository.
1063 	 */
1064 	public boolean isRemoveDeletedRefs() {
1065 		return removeDeletedRefs;
1066 	}
1067 
1068 	/**
1069 	 * Set whether or not to remove refs which no longer exist in the source.
1070 	 * <p>
1071 	 * If true, refs at the destination repository (local for fetch, remote for
1072 	 * push) are deleted if they no longer exist on the source side (remote for
1073 	 * fetch, local for push).
1074 	 * <p>
1075 	 * False by default, as this may cause data to become unreachable, and
1076 	 * eventually be deleted on the next GC.
1077 	 *
1078 	 * @param remove true to remove refs that no longer exist.
1079 	 */
1080 	public void setRemoveDeletedRefs(final boolean remove) {
1081 		removeDeletedRefs = remove;
1082 	}
1083 
1084 	/**
1085 	 * Apply provided remote configuration on this transport.
1086 	 *
1087 	 * @param cfg
1088 	 *            configuration to apply on this transport.
1089 	 */
1090 	public void applyConfig(final RemoteConfig cfg) {
1091 		setOptionUploadPack(cfg.getUploadPack());
1092 		setOptionReceivePack(cfg.getReceivePack());
1093 		setTagOpt(cfg.getTagOpt());
1094 		fetch = cfg.getFetchRefSpecs();
1095 		push = cfg.getPushRefSpecs();
1096 		timeout = cfg.getTimeout();
1097 	}
1098 
1099 	/**
1100 	 * Whether push operation should just check for possible result and not
1101 	 * really update remote refs
1102 	 *
1103 	 * @return true if push operation should just check for possible result and
1104 	 *         not really update remote refs, false otherwise - when push should
1105 	 *         act normally.
1106 	 */
1107 	public boolean isDryRun() {
1108 		return dryRun;
1109 	}
1110 
1111 	/**
1112 	 * Set dry run option for push operation.
1113 	 *
1114 	 * @param dryRun
1115 	 *            true if push operation should just check for possible result
1116 	 *            and not really update remote refs, false otherwise - when push
1117 	 *            should act normally.
1118 	 */
1119 	public void setDryRun(final boolean dryRun) {
1120 		this.dryRun = dryRun;
1121 	}
1122 
1123 	/**
1124 	 * Get timeout (in seconds) before aborting an IO operation.
1125 	 *
1126 	 * @return timeout (in seconds) before aborting an IO operation.
1127 	 */
1128 	public int getTimeout() {
1129 		return timeout;
1130 	}
1131 
1132 	/**
1133 	 * Set the timeout before willing to abort an IO call.
1134 	 *
1135 	 * @param seconds
1136 	 *            number of seconds to wait (with no data transfer occurring)
1137 	 *            before aborting an IO read or write operation with this
1138 	 *            remote.
1139 	 */
1140 	public void setTimeout(final int seconds) {
1141 		timeout = seconds;
1142 	}
1143 
1144 	/**
1145 	 * Get the configuration used by the pack generator to make packs.
1146 	 *
1147 	 * If {@link #setPackConfig(PackConfig)} was previously given null a new
1148 	 * PackConfig is created on demand by this method using the source
1149 	 * repository's settings.
1150 	 *
1151 	 * @return the pack configuration. Never null.
1152 	 */
1153 	public PackConfig getPackConfig() {
1154 		if (packConfig == null)
1155 			packConfig = new PackConfig(local);
1156 		return packConfig;
1157 	}
1158 
1159 	/**
1160 	 * Set the configuration used by the pack generator.
1161 	 *
1162 	 * @param pc
1163 	 *            configuration controlling packing parameters. If null the
1164 	 *            source repository's settings will be used.
1165 	 */
1166 	public void setPackConfig(PackConfig pc) {
1167 		packConfig = pc;
1168 	}
1169 
1170 	/**
1171 	 * A credentials provider to assist with authentication connections..
1172 	 *
1173 	 * @param credentialsProvider
1174 	 *            the credentials provider, or null if there is none
1175 	 */
1176 	public void setCredentialsProvider(CredentialsProvider credentialsProvider) {
1177 		this.credentialsProvider = credentialsProvider;
1178 	}
1179 
1180 	/**
1181 	 * The configured credentials provider.
1182 	 *
1183 	 * @return the credentials provider, or null if no credentials provider is
1184 	 *         associated with this transport.
1185 	 */
1186 	public CredentialsProvider getCredentialsProvider() {
1187 		return credentialsProvider;
1188 	}
1189 
1190 	/**
1191 	 * Get the option strings associated with the push operation
1192 	 *
1193 	 * @return the option strings associated with the push operation
1194 	 * @since 4.5
1195 	 */
1196 	public List<String> getPushOptions() {
1197 		return pushOptions;
1198 	}
1199 
1200 	/**
1201 	 * Sets the option strings associated with the push operation.
1202 	 *
1203 	 * @param pushOptions
1204 	 *            null if push options are unsupported
1205 	 * @since 4.5
1206 	 */
1207 	public void setPushOptions(final List<String> pushOptions) {
1208 		this.pushOptions = pushOptions;
1209 	}
1210 
1211 	/**
1212 	 * Fetch objects and refs from the remote repository to the local one.
1213 	 * <p>
1214 	 * This is a utility function providing standard fetch behavior. Local
1215 	 * tracking refs associated with the remote repository are automatically
1216 	 * updated if this transport was created from a
1217 	 * {@link org.eclipse.jgit.transport.RemoteConfig} with fetch RefSpecs
1218 	 * defined.
1219 	 *
1220 	 * @param monitor
1221 	 *            progress monitor to inform the user about our processing
1222 	 *            activity. Must not be null. Use
1223 	 *            {@link org.eclipse.jgit.lib.NullProgressMonitor} if progress
1224 	 *            updates are not interesting or necessary.
1225 	 * @param toFetch
1226 	 *            specification of refs to fetch locally. May be null or the
1227 	 *            empty collection to use the specifications from the
1228 	 *            RemoteConfig. Source for each RefSpec can't be null.
1229 	 * @return information describing the tracking refs updated.
1230 	 * @throws org.eclipse.jgit.errors.NotSupportedException
1231 	 *             this transport implementation does not support fetching
1232 	 *             objects.
1233 	 * @throws org.eclipse.jgit.errors.TransportException
1234 	 *             the remote connection could not be established or object
1235 	 *             copying (if necessary) failed or update specification was
1236 	 *             incorrect.
1237 	 */
1238 	public FetchResult fetch(final ProgressMonitor monitor,
1239 			Collection<RefSpec> toFetch) throws NotSupportedException,
1240 			TransportException {
1241 		if (toFetch == null || toFetch.isEmpty()) {
1242 			// If the caller did not ask for anything use the defaults.
1243 			//
1244 			if (fetch.isEmpty())
1245 				throw new TransportException(JGitText.get().nothingToFetch);
1246 			toFetch = fetch;
1247 		} else if (!fetch.isEmpty()) {
1248 			// If the caller asked for something specific without giving
1249 			// us the local tracking branch see if we can update any of
1250 			// the local tracking branches without incurring additional
1251 			// object transfer overheads.
1252 			//
1253 			final Collection<RefSpec> tmp = new ArrayList<>(toFetch);
1254 			for (final RefSpec requested : toFetch) {
1255 				final String reqSrc = requested.getSource();
1256 				for (final RefSpec configured : fetch) {
1257 					final String cfgSrc = configured.getSource();
1258 					final String cfgDst = configured.getDestination();
1259 					if (cfgSrc.equals(reqSrc) && cfgDst != null) {
1260 						tmp.add(configured);
1261 						break;
1262 					}
1263 				}
1264 			}
1265 			toFetch = tmp;
1266 		}
1267 
1268 		final FetchResult result = new FetchResult();
1269 		new FetchProcess(this, toFetch).execute(monitor, result);
1270 
1271 		local.autoGC(monitor);
1272 
1273 		return result;
1274 	}
1275 
1276 	/**
1277 	 * Push objects and refs from the local repository to the remote one.
1278 	 * <p>
1279 	 * This is a utility function providing standard push behavior. It updates
1280 	 * remote refs and send there necessary objects according to remote ref
1281 	 * update specification. After successful remote ref update, associated
1282 	 * locally stored tracking branch is updated if set up accordingly. Detailed
1283 	 * operation result is provided after execution.
1284 	 * <p>
1285 	 * For setting up remote ref update specification from ref spec, see helper
1286 	 * method {@link #findRemoteRefUpdatesFor(Collection)}, predefined refspecs
1287 	 * ({@link #REFSPEC_TAGS}, {@link #REFSPEC_PUSH_ALL}) or consider using
1288 	 * directly {@link org.eclipse.jgit.transport.RemoteRefUpdate} for more
1289 	 * possibilities.
1290 	 * <p>
1291 	 * When {@link #isDryRun()} is true, result of this operation is just
1292 	 * estimation of real operation result, no real action is performed.
1293 	 *
1294 	 * @see RemoteRefUpdate
1295 	 * @param monitor
1296 	 *            progress monitor to inform the user about our processing
1297 	 *            activity. Must not be null. Use
1298 	 *            {@link org.eclipse.jgit.lib.NullProgressMonitor} if progress
1299 	 *            updates are not interesting or necessary.
1300 	 * @param toPush
1301 	 *            specification of refs to push. May be null or the empty
1302 	 *            collection to use the specifications from the RemoteConfig
1303 	 *            converted by {@link #findRemoteRefUpdatesFor(Collection)}. No
1304 	 *            more than 1 RemoteRefUpdate with the same remoteName is
1305 	 *            allowed. These objects are modified during this call.
1306 	 * @param out
1307 	 *            output stream to write messages to
1308 	 * @return information about results of remote refs updates, tracking refs
1309 	 *         updates and refs advertised by remote repository.
1310 	 * @throws org.eclipse.jgit.errors.NotSupportedException
1311 	 *             this transport implementation does not support pushing
1312 	 *             objects.
1313 	 * @throws org.eclipse.jgit.errors.TransportException
1314 	 *             the remote connection could not be established or object
1315 	 *             copying (if necessary) failed at I/O or protocol level or
1316 	 *             update specification was incorrect.
1317 	 * @since 3.0
1318 	 */
1319 	public PushResult push(final ProgressMonitor monitor,
1320 			Collection<RemoteRefUpdate> toPush, OutputStream out)
1321 			throws NotSupportedException,
1322 			TransportException {
1323 		if (toPush == null || toPush.isEmpty()) {
1324 			// If the caller did not ask for anything use the defaults.
1325 			try {
1326 				toPush = findRemoteRefUpdatesFor(push);
1327 			} catch (final IOException e) {
1328 				throw new TransportException(MessageFormat.format(
1329 						JGitText.get().problemWithResolvingPushRefSpecsLocally, e.getMessage()), e);
1330 			}
1331 			if (toPush.isEmpty())
1332 				throw new TransportException(JGitText.get().nothingToPush);
1333 		}
1334 		if (prePush != null) {
1335 			try {
1336 				prePush.setRefs(toPush);
1337 				prePush.call();
1338 			} catch (AbortedByHookException | IOException e) {
1339 				throw new TransportException(e.getMessage(), e);
1340 			}
1341 		}
1342 
1343 		final PushProcess pushProcess = new PushProcess(this, toPush, out);
1344 		return pushProcess.execute(monitor);
1345 	}
1346 
1347 	/**
1348 	 * Push objects and refs from the local repository to the remote one.
1349 	 * <p>
1350 	 * This is a utility function providing standard push behavior. It updates
1351 	 * remote refs and sends necessary objects according to remote ref update
1352 	 * specification. After successful remote ref update, associated locally
1353 	 * stored tracking branch is updated if set up accordingly. Detailed
1354 	 * operation result is provided after execution.
1355 	 * <p>
1356 	 * For setting up remote ref update specification from ref spec, see helper
1357 	 * method {@link #findRemoteRefUpdatesFor(Collection)}, predefined refspecs
1358 	 * ({@link #REFSPEC_TAGS}, {@link #REFSPEC_PUSH_ALL}) or consider using
1359 	 * directly {@link org.eclipse.jgit.transport.RemoteRefUpdate} for more
1360 	 * possibilities.
1361 	 * <p>
1362 	 * When {@link #isDryRun()} is true, result of this operation is just
1363 	 * estimation of real operation result, no real action is performed.
1364 	 *
1365 	 * @see RemoteRefUpdate
1366 	 * @param monitor
1367 	 *            progress monitor to inform the user about our processing
1368 	 *            activity. Must not be null. Use
1369 	 *            {@link org.eclipse.jgit.lib.NullProgressMonitor} if progress
1370 	 *            updates are not interesting or necessary.
1371 	 * @param toPush
1372 	 *            specification of refs to push. May be null or the empty
1373 	 *            collection to use the specifications from the RemoteConfig
1374 	 *            converted by {@link #findRemoteRefUpdatesFor(Collection)}. No
1375 	 *            more than 1 RemoteRefUpdate with the same remoteName is
1376 	 *            allowed. These objects are modified during this call.
1377 	 * @return information about results of remote refs updates, tracking refs
1378 	 *         updates and refs advertised by remote repository.
1379 	 * @throws org.eclipse.jgit.errors.NotSupportedException
1380 	 *             this transport implementation does not support pushing
1381 	 *             objects.
1382 	 * @throws org.eclipse.jgit.errors.TransportException
1383 	 *             the remote connection could not be established or object
1384 	 *             copying (if necessary) failed at I/O or protocol level or
1385 	 *             update specification was incorrect.
1386 	 */
1387 	public PushResult push(final ProgressMonitor monitor,
1388 			Collection<RemoteRefUpdate> toPush) throws NotSupportedException,
1389 			TransportException {
1390 		return push(monitor, toPush, null);
1391 	}
1392 
1393 	/**
1394 	 * Convert push remote refs update specification from
1395 	 * {@link org.eclipse.jgit.transport.RefSpec} form to
1396 	 * {@link org.eclipse.jgit.transport.RemoteRefUpdate}. Conversion expands
1397 	 * wildcards by matching source part to local refs. expectedOldObjectId in
1398 	 * RemoteRefUpdate is always set as null. Tracking branch is configured if
1399 	 * RefSpec destination matches source of any fetch ref spec for this
1400 	 * transport remote configuration.
1401 	 * <p>
1402 	 * Conversion is performed for context of this transport (database, fetch
1403 	 * specifications).
1404 	 *
1405 	 * @param specs
1406 	 *            collection of RefSpec to convert.
1407 	 * @return collection of set up
1408 	 *         {@link org.eclipse.jgit.transport.RemoteRefUpdate}.
1409 	 * @throws java.io.IOException
1410 	 *             when problem occurred during conversion or specification set
1411 	 *             up: most probably, missing objects or refs.
1412 	 */
1413 	public Collection<RemoteRefUpdate> findRemoteRefUpdatesFor(
1414 			final Collection<RefSpec> specs) throws IOException {
1415 		return findRemoteRefUpdatesFor(local, specs, Collections.emptyMap(),
1416 					       fetch);
1417 	}
1418 
1419 	/**
1420 	 * Convert push remote refs update specification from
1421 	 * {@link org.eclipse.jgit.transport.RefSpec} form to
1422 	 * {@link org.eclipse.jgit.transport.RemoteRefUpdate}. Conversion expands
1423 	 * wildcards by matching source part to local refs. expectedOldObjectId in
1424 	 * RemoteRefUpdate is set according to leases. Tracking branch is configured
1425 	 * if RefSpec destination matches source of any fetch ref spec for this
1426 	 * transport remote configuration.
1427 	 * <p>
1428 	 * Conversion is performed for context of this transport (database, fetch
1429 	 * specifications).
1430 	 *
1431 	 * @param specs
1432 	 *            collection of RefSpec to convert.
1433 	 * @param leases
1434 	 *            map from ref to lease (containing expected old object id)
1435 	 * @return collection of set up
1436 	 *         {@link org.eclipse.jgit.transport.RemoteRefUpdate}.
1437 	 * @throws java.io.IOException
1438 	 *             when problem occurred during conversion or specification set
1439 	 *             up: most probably, missing objects or refs.
1440 	 * @since 4.7
1441 	 */
1442 	public Collection<RemoteRefUpdate> findRemoteRefUpdatesFor(
1443 			final Collection<RefSpec> specs,
1444 			final Map<String, RefLeaseSpec> leases) throws IOException {
1445 		return findRemoteRefUpdatesFor(local, specs, leases,
1446 					       fetch);
1447 	}
1448 
1449 	/**
1450 	 * Begins a new connection for fetching from the remote repository.
1451 	 * <p>
1452 	 * If the transport has no local repository, the fetch connection can only
1453 	 * be used for reading remote refs.
1454 	 *
1455 	 * @return a fresh connection to fetch from the remote repository.
1456 	 * @throws org.eclipse.jgit.errors.NotSupportedException
1457 	 *             the implementation does not support fetching.
1458 	 * @throws org.eclipse.jgit.errors.TransportException
1459 	 *             the remote connection could not be established.
1460 	 */
1461 	public abstract FetchConnection openFetch() throws NotSupportedException,
1462 			TransportException;
1463 
1464 	/**
1465 	 * Begins a new connection for pushing into the remote repository.
1466 	 *
1467 	 * @return a fresh connection to push into the remote repository.
1468 	 * @throws org.eclipse.jgit.errors.NotSupportedException
1469 	 *             the implementation does not support pushing.
1470 	 * @throws org.eclipse.jgit.errors.TransportException
1471 	 *             the remote connection could not be established
1472 	 */
1473 	public abstract PushConnection openPush() throws NotSupportedException,
1474 			TransportException;
1475 
1476 	/**
1477 	 * {@inheritDoc}
1478 	 * <p>
1479 	 * Close any resources used by this transport.
1480 	 * <p>
1481 	 * If the remote repository is contacted by a network socket this method
1482 	 * must close that network socket, disconnecting the two peers. If the
1483 	 * remote repository is actually local (same system) this method must close
1484 	 * any open file handles used to read the "remote" repository.
1485 	 * <p>
1486 	 * {@code AutoClosable.close()} declares that it throws {@link Exception}.
1487 	 * Implementers shouldn't throw checked exceptions. This override narrows
1488 	 * the signature to prevent them from doing so.
1489 	 */
1490 	@Override
1491 	public abstract void close();
1492 }