You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Transport.java 51KB

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