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

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