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 52KB

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