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

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