Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

FetchProcess.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. /*
  2. * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  4. * and other copyright owners as documented in the project's IP log.
  5. *
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Distribution License v1.0 which
  8. * accompanies this distribution, is reproduced below, and is
  9. * available at http://www.eclipse.org/org/documents/edl-v10.php
  10. *
  11. * All rights reserved.
  12. *
  13. * Redistribution and use in source and binary forms, with or
  14. * without modification, are permitted provided that the following
  15. * conditions are met:
  16. *
  17. * - Redistributions of source code must retain the above copyright
  18. * notice, this list of conditions and the following disclaimer.
  19. *
  20. * - Redistributions in binary form must reproduce the above
  21. * copyright notice, this list of conditions and the following
  22. * disclaimer in the documentation and/or other materials provided
  23. * with the distribution.
  24. *
  25. * - Neither the name of the Eclipse Foundation, Inc. nor the
  26. * names of its contributors may be used to endorse or promote
  27. * products derived from this software without specific prior
  28. * written permission.
  29. *
  30. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  31. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  32. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  33. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  35. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  36. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  37. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  38. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  39. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  40. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  41. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  42. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  43. */
  44. package org.eclipse.jgit.transport;
  45. import java.io.File;
  46. import java.io.IOException;
  47. import java.io.OutputStreamWriter;
  48. import java.io.Writer;
  49. import java.text.MessageFormat;
  50. import java.util.ArrayList;
  51. import java.util.Collection;
  52. import java.util.Collections;
  53. import java.util.HashMap;
  54. import java.util.HashSet;
  55. import java.util.Iterator;
  56. import java.util.Map;
  57. import java.util.Set;
  58. import org.eclipse.jgit.JGitText;
  59. import org.eclipse.jgit.errors.MissingObjectException;
  60. import org.eclipse.jgit.errors.NotSupportedException;
  61. import org.eclipse.jgit.errors.TransportException;
  62. import org.eclipse.jgit.lib.Constants;
  63. import org.eclipse.jgit.lib.ObjectId;
  64. import org.eclipse.jgit.lib.ProgressMonitor;
  65. import org.eclipse.jgit.lib.Ref;
  66. import org.eclipse.jgit.lib.Repository;
  67. import org.eclipse.jgit.revwalk.ObjectWalk;
  68. import org.eclipse.jgit.revwalk.RevWalk;
  69. import org.eclipse.jgit.storage.file.LockFile;
  70. import org.eclipse.jgit.storage.file.PackLock;
  71. class FetchProcess {
  72. /** Transport we will fetch over. */
  73. private final Transport transport;
  74. /** List of things we want to fetch from the remote repository. */
  75. private final Collection<RefSpec> toFetch;
  76. /** Set of refs we will actually wind up asking to obtain. */
  77. private final HashMap<ObjectId, Ref> askFor = new HashMap<ObjectId, Ref>();
  78. /** Objects we know we have locally. */
  79. private final HashSet<ObjectId> have = new HashSet<ObjectId>();
  80. /** Updates to local tracking branches (if any). */
  81. private final ArrayList<TrackingRefUpdate> localUpdates = new ArrayList<TrackingRefUpdate>();
  82. /** Records to be recorded into FETCH_HEAD. */
  83. private final ArrayList<FetchHeadRecord> fetchHeadUpdates = new ArrayList<FetchHeadRecord>();
  84. private final ArrayList<PackLock> packLocks = new ArrayList<PackLock>();
  85. private FetchConnection conn;
  86. FetchProcess(final Transport t, final Collection<RefSpec> f) {
  87. transport = t;
  88. toFetch = f;
  89. }
  90. void execute(final ProgressMonitor monitor, final FetchResult result)
  91. throws NotSupportedException, TransportException {
  92. askFor.clear();
  93. localUpdates.clear();
  94. fetchHeadUpdates.clear();
  95. packLocks.clear();
  96. try {
  97. executeImp(monitor, result);
  98. } finally {
  99. try {
  100. for (final PackLock lock : packLocks)
  101. lock.unlock();
  102. } catch (IOException e) {
  103. throw new TransportException(e.getMessage(), e);
  104. }
  105. }
  106. }
  107. private void executeImp(final ProgressMonitor monitor,
  108. final FetchResult result) throws NotSupportedException,
  109. TransportException {
  110. conn = transport.openFetch();
  111. try {
  112. result.setAdvertisedRefs(transport.getURI(), conn.getRefsMap());
  113. final Set<Ref> matched = new HashSet<Ref>();
  114. for (final RefSpec spec : toFetch) {
  115. if (spec.getSource() == null)
  116. throw new TransportException(MessageFormat.format(
  117. JGitText.get().sourceRefNotSpecifiedForRefspec, spec));
  118. if (spec.isWildcard())
  119. expandWildcard(spec, matched);
  120. else
  121. expandSingle(spec, matched);
  122. }
  123. Collection<Ref> additionalTags = Collections.<Ref> emptyList();
  124. final TagOpt tagopt = transport.getTagOpt();
  125. if (tagopt == TagOpt.AUTO_FOLLOW)
  126. additionalTags = expandAutoFollowTags();
  127. else if (tagopt == TagOpt.FETCH_TAGS)
  128. expandFetchTags();
  129. final boolean includedTags;
  130. if (!askFor.isEmpty() && !askForIsComplete()) {
  131. fetchObjects(monitor);
  132. includedTags = conn.didFetchIncludeTags();
  133. // Connection was used for object transfer. If we
  134. // do another fetch we must open a new connection.
  135. //
  136. closeConnection(result);
  137. } else {
  138. includedTags = false;
  139. }
  140. if (tagopt == TagOpt.AUTO_FOLLOW && !additionalTags.isEmpty()) {
  141. // There are more tags that we want to follow, but
  142. // not all were asked for on the initial request.
  143. //
  144. have.addAll(askFor.keySet());
  145. askFor.clear();
  146. for (final Ref r : additionalTags) {
  147. final ObjectId id = r.getPeeledObjectId();
  148. if (id == null || transport.local.hasObject(id))
  149. wantTag(r);
  150. }
  151. if (!askFor.isEmpty() && (!includedTags || !askForIsComplete())) {
  152. reopenConnection();
  153. if (!askFor.isEmpty())
  154. fetchObjects(monitor);
  155. }
  156. }
  157. } finally {
  158. closeConnection(result);
  159. }
  160. final RevWalk walk = new RevWalk(transport.local);
  161. try {
  162. if (transport.isRemoveDeletedRefs())
  163. deleteStaleTrackingRefs(result, walk);
  164. for (TrackingRefUpdate u : localUpdates) {
  165. try {
  166. u.update(walk);
  167. result.add(u);
  168. } catch (IOException err) {
  169. throw new TransportException(MessageFormat.format(JGitText
  170. .get().failureUpdatingTrackingRef,
  171. u.getLocalName(), err.getMessage()), err);
  172. }
  173. }
  174. } finally {
  175. walk.release();
  176. }
  177. if (!fetchHeadUpdates.isEmpty()) {
  178. try {
  179. updateFETCH_HEAD(result);
  180. } catch (IOException err) {
  181. throw new TransportException(MessageFormat.format(
  182. JGitText.get().failureUpdatingFETCH_HEAD, err.getMessage()), err);
  183. }
  184. }
  185. }
  186. private void fetchObjects(final ProgressMonitor monitor)
  187. throws TransportException {
  188. try {
  189. conn.setPackLockMessage("jgit fetch " + transport.uri);
  190. conn.fetch(monitor, askFor.values(), have);
  191. } finally {
  192. packLocks.addAll(conn.getPackLocks());
  193. }
  194. if (transport.isCheckFetchedObjects()
  195. && !conn.didFetchTestConnectivity() && !askForIsComplete())
  196. throw new TransportException(transport.getURI(),
  197. JGitText.get().peerDidNotSupplyACompleteObjectGraph);
  198. }
  199. private void closeConnection(final FetchResult result) {
  200. if (conn != null) {
  201. conn.close();
  202. result.addMessages(conn.getMessages());
  203. conn = null;
  204. }
  205. }
  206. private void reopenConnection() throws NotSupportedException,
  207. TransportException {
  208. if (conn != null)
  209. return;
  210. conn = transport.openFetch();
  211. // Since we opened a new connection we cannot be certain
  212. // that the system we connected to has the same exact set
  213. // of objects available (think round-robin DNS and mirrors
  214. // that aren't updated at the same time).
  215. //
  216. // We rebuild our askFor list using only the refs that the
  217. // new connection has offered to us.
  218. //
  219. final HashMap<ObjectId, Ref> avail = new HashMap<ObjectId, Ref>();
  220. for (final Ref r : conn.getRefs())
  221. avail.put(r.getObjectId(), r);
  222. final Collection<Ref> wants = new ArrayList<Ref>(askFor.values());
  223. askFor.clear();
  224. for (final Ref want : wants) {
  225. final Ref newRef = avail.get(want.getObjectId());
  226. if (newRef != null) {
  227. askFor.put(newRef.getObjectId(), newRef);
  228. } else {
  229. removeFetchHeadRecord(want.getObjectId());
  230. removeTrackingRefUpdate(want.getObjectId());
  231. }
  232. }
  233. }
  234. private void removeTrackingRefUpdate(final ObjectId want) {
  235. final Iterator<TrackingRefUpdate> i = localUpdates.iterator();
  236. while (i.hasNext()) {
  237. final TrackingRefUpdate u = i.next();
  238. if (u.getNewObjectId().equals(want))
  239. i.remove();
  240. }
  241. }
  242. private void removeFetchHeadRecord(final ObjectId want) {
  243. final Iterator<FetchHeadRecord> i = fetchHeadUpdates.iterator();
  244. while (i.hasNext()) {
  245. final FetchHeadRecord fh = i.next();
  246. if (fh.newValue.equals(want))
  247. i.remove();
  248. }
  249. }
  250. private void updateFETCH_HEAD(final FetchResult result) throws IOException {
  251. File meta = transport.local.getDirectory();
  252. if (meta == null)
  253. return;
  254. final LockFile lock = new LockFile(new File(meta, "FETCH_HEAD"),
  255. transport.local.getFS());
  256. try {
  257. if (lock.lock()) {
  258. final Writer w = new OutputStreamWriter(lock.getOutputStream());
  259. try {
  260. for (final FetchHeadRecord h : fetchHeadUpdates) {
  261. h.write(w);
  262. result.add(h);
  263. }
  264. } finally {
  265. w.close();
  266. }
  267. lock.commit();
  268. }
  269. } finally {
  270. lock.unlock();
  271. }
  272. }
  273. private boolean askForIsComplete() throws TransportException {
  274. try {
  275. final ObjectWalk ow = new ObjectWalk(transport.local);
  276. try {
  277. for (final ObjectId want : askFor.keySet())
  278. ow.markStart(ow.parseAny(want));
  279. for (final Ref ref : transport.local.getAllRefs().values())
  280. ow.markUninteresting(ow.parseAny(ref.getObjectId()));
  281. ow.checkConnectivity();
  282. } finally {
  283. ow.release();
  284. }
  285. return true;
  286. } catch (MissingObjectException e) {
  287. return false;
  288. } catch (IOException e) {
  289. throw new TransportException(JGitText.get().unableToCheckConnectivity, e);
  290. }
  291. }
  292. private void expandWildcard(final RefSpec spec, final Set<Ref> matched)
  293. throws TransportException {
  294. for (final Ref src : conn.getRefs()) {
  295. if (spec.matchSource(src) && matched.add(src))
  296. want(src, spec.expandFromSource(src));
  297. }
  298. }
  299. private void expandSingle(final RefSpec spec, final Set<Ref> matched)
  300. throws TransportException {
  301. final Ref src = conn.getRef(spec.getSource());
  302. if (src == null) {
  303. throw new TransportException(MessageFormat.format(JGitText.get().remoteDoesNotHaveSpec, spec.getSource()));
  304. }
  305. if (matched.add(src))
  306. want(src, spec);
  307. }
  308. private Collection<Ref> expandAutoFollowTags() throws TransportException {
  309. final Collection<Ref> additionalTags = new ArrayList<Ref>();
  310. final Map<String, Ref> haveRefs = transport.local.getAllRefs();
  311. for (final Ref r : conn.getRefs()) {
  312. if (!isTag(r))
  313. continue;
  314. if (r.getPeeledObjectId() == null) {
  315. additionalTags.add(r);
  316. continue;
  317. }
  318. final Ref local = haveRefs.get(r.getName());
  319. if (local != null) {
  320. if (!r.getObjectId().equals(local.getObjectId()))
  321. wantTag(r);
  322. } else if (askFor.containsKey(r.getPeeledObjectId())
  323. || transport.local.hasObject(r.getPeeledObjectId()))
  324. wantTag(r);
  325. else
  326. additionalTags.add(r);
  327. }
  328. return additionalTags;
  329. }
  330. private void expandFetchTags() throws TransportException {
  331. final Map<String, Ref> haveRefs = transport.local.getAllRefs();
  332. for (final Ref r : conn.getRefs()) {
  333. if (!isTag(r))
  334. continue;
  335. final Ref local = haveRefs.get(r.getName());
  336. if (local == null || !r.getObjectId().equals(local.getObjectId()))
  337. wantTag(r);
  338. }
  339. }
  340. private void wantTag(final Ref r) throws TransportException {
  341. want(r, new RefSpec().setSource(r.getName())
  342. .setDestination(r.getName()));
  343. }
  344. private void want(final Ref src, final RefSpec spec)
  345. throws TransportException {
  346. final ObjectId newId = src.getObjectId();
  347. if (spec.getDestination() != null) {
  348. try {
  349. final TrackingRefUpdate tru = createUpdate(spec, newId);
  350. if (newId.equals(tru.getOldObjectId()))
  351. return;
  352. localUpdates.add(tru);
  353. } catch (IOException err) {
  354. // Bad symbolic ref? That is the most likely cause.
  355. //
  356. throw new TransportException( MessageFormat.format(
  357. JGitText.get().cannotResolveLocalTrackingRefForUpdating, spec.getDestination()), err);
  358. }
  359. }
  360. askFor.put(newId, src);
  361. final FetchHeadRecord fhr = new FetchHeadRecord();
  362. fhr.newValue = newId;
  363. fhr.notForMerge = spec.getDestination() != null;
  364. fhr.sourceName = src.getName();
  365. fhr.sourceURI = transport.getURI();
  366. fetchHeadUpdates.add(fhr);
  367. }
  368. private TrackingRefUpdate createUpdate(final RefSpec spec,
  369. final ObjectId newId) throws IOException {
  370. return new TrackingRefUpdate(transport.local, spec, newId, "fetch");
  371. }
  372. private void deleteStaleTrackingRefs(final FetchResult result,
  373. final RevWalk walk) throws TransportException {
  374. final Repository db = transport.local;
  375. for (final Ref ref : db.getAllRefs().values()) {
  376. final String refname = ref.getName();
  377. for (final RefSpec spec : toFetch) {
  378. if (spec.matchDestination(refname)) {
  379. final RefSpec s = spec.expandFromDestination(refname);
  380. if (result.getAdvertisedRef(s.getSource()) == null) {
  381. deleteTrackingRef(result, db, walk, s, ref);
  382. }
  383. }
  384. }
  385. }
  386. }
  387. private void deleteTrackingRef(final FetchResult result,
  388. final Repository db, final RevWalk walk, final RefSpec spec,
  389. final Ref localRef) throws TransportException {
  390. final String name = localRef.getName();
  391. try {
  392. final TrackingRefUpdate u = new TrackingRefUpdate(db, name, spec
  393. .getSource(), true, ObjectId.zeroId(), "deleted");
  394. result.add(u);
  395. if (transport.isDryRun()){
  396. return;
  397. }
  398. u.delete(walk);
  399. switch (u.getResult()) {
  400. case NEW:
  401. case NO_CHANGE:
  402. case FAST_FORWARD:
  403. case FORCED:
  404. break;
  405. default:
  406. throw new TransportException(transport.getURI(), MessageFormat.format(
  407. JGitText.get().cannotDeleteStaleTrackingRef2, name, u.getResult().name()));
  408. }
  409. } catch (IOException e) {
  410. throw new TransportException(transport.getURI(), MessageFormat.format(
  411. JGitText.get().cannotDeleteStaleTrackingRef, name), e);
  412. }
  413. }
  414. private static boolean isTag(final Ref r) {
  415. return isTag(r.getName());
  416. }
  417. private static boolean isTag(final String name) {
  418. return name.startsWith(Constants.R_TAGS);
  419. }
  420. }