1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 package org.eclipse.jgit.transport;
46
47 import static org.eclipse.jgit.transport.ReceiveCommand.Result.NOT_ATTEMPTED;
48 import static org.eclipse.jgit.transport.ReceiveCommand.Result.OK;
49 import static org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_NONFASTFORWARD;
50 import static org.eclipse.jgit.transport.ReceiveCommand.Type.UPDATE_NONFASTFORWARD;
51
52 import java.io.File;
53 import java.io.IOException;
54 import java.io.OutputStreamWriter;
55 import java.io.Writer;
56 import java.text.MessageFormat;
57 import java.util.ArrayList;
58 import java.util.Collection;
59 import java.util.Collections;
60 import java.util.HashMap;
61 import java.util.HashSet;
62 import java.util.Iterator;
63 import java.util.Map;
64 import java.util.Set;
65 import java.util.concurrent.TimeUnit;
66
67 import org.eclipse.jgit.errors.MissingObjectException;
68 import org.eclipse.jgit.errors.NotSupportedException;
69 import org.eclipse.jgit.errors.TransportException;
70 import org.eclipse.jgit.internal.JGitText;
71 import org.eclipse.jgit.internal.storage.file.LockFile;
72 import org.eclipse.jgit.internal.storage.file.PackLock;
73 import org.eclipse.jgit.lib.BatchRefUpdate;
74 import org.eclipse.jgit.lib.BatchingProgressMonitor;
75 import org.eclipse.jgit.lib.Constants;
76 import org.eclipse.jgit.lib.ObjectId;
77 import org.eclipse.jgit.lib.ObjectIdRef;
78 import org.eclipse.jgit.lib.ProgressMonitor;
79 import org.eclipse.jgit.lib.Ref;
80 import org.eclipse.jgit.lib.RefDatabase;
81 import org.eclipse.jgit.revwalk.ObjectWalk;
82 import org.eclipse.jgit.revwalk.RevWalk;
83
84 class FetchProcess {
85
86 private final Transport transport;
87
88
89 private final Collection<RefSpec> toFetch;
90
91
92 private final HashMap<ObjectId, Ref> askFor = new HashMap<>();
93
94
95 private final HashSet<ObjectId> have = new HashSet<>();
96
97
98 private final ArrayList<TrackingRefUpdate> localUpdates = new ArrayList<>();
99
100
101 private final ArrayList<FetchHeadRecord> fetchHeadUpdates = new ArrayList<>();
102
103 private final ArrayList<PackLock> packLocks = new ArrayList<>();
104
105 private FetchConnection conn;
106
107 private Map<String, Ref> localRefs;
108
109 FetchProcess(Transport t, Collection<RefSpec> f) {
110 transport = t;
111 toFetch = f;
112 }
113
114 void execute(ProgressMonitor monitor, FetchResult result)
115 throws NotSupportedException, TransportException {
116 askFor.clear();
117 localUpdates.clear();
118 fetchHeadUpdates.clear();
119 packLocks.clear();
120 localRefs = null;
121
122 try {
123 executeImp(monitor, result);
124 } finally {
125 try {
126 for (PackLock lock : packLocks)
127 lock.unlock();
128 } catch (IOException e) {
129 throw new TransportException(e.getMessage(), e);
130 }
131 }
132 }
133
134 private void executeImp(final ProgressMonitor monitor,
135 final FetchResult result) throws NotSupportedException,
136 TransportException {
137 conn = transport.openFetch();
138 try {
139 result.setAdvertisedRefs(transport.getURI(), conn.getRefsMap());
140 result.peerUserAgent = conn.getPeerUserAgent();
141 final Set<Ref> matched = new HashSet<>();
142 for (RefSpec spec : toFetch) {
143 if (spec.getSource() == null)
144 throw new TransportException(MessageFormat.format(
145 JGitText.get().sourceRefNotSpecifiedForRefspec, spec));
146
147 if (spec.isWildcard())
148 expandWildcard(spec, matched);
149 else
150 expandSingle(spec, matched);
151 }
152
153 Collection<Ref> additionalTags = Collections.<Ref> emptyList();
154 final TagOpt tagopt = transport.getTagOpt();
155 if (tagopt == TagOpt.AUTO_FOLLOW)
156 additionalTags = expandAutoFollowTags();
157 else if (tagopt == TagOpt.FETCH_TAGS)
158 expandFetchTags();
159
160 final boolean includedTags;
161 if (!askFor.isEmpty() && !askForIsComplete()) {
162 fetchObjects(monitor);
163 includedTags = conn.didFetchIncludeTags();
164
165
166
167
168 closeConnection(result);
169 } else {
170 includedTags = false;
171 }
172
173 if (tagopt == TagOpt.AUTO_FOLLOW && !additionalTags.isEmpty()) {
174
175
176
177 have.addAll(askFor.keySet());
178 askFor.clear();
179 for (Ref r : additionalTags) {
180 ObjectId id = r.getPeeledObjectId();
181 if (id == null)
182 id = r.getObjectId();
183 if (transport.local.hasObject(id))
184 wantTag(r);
185 }
186
187 if (!askFor.isEmpty() && (!includedTags || !askForIsComplete())) {
188 reopenConnection();
189 if (!askFor.isEmpty())
190 fetchObjects(monitor);
191 }
192 }
193 } finally {
194 closeConnection(result);
195 }
196
197 BatchRefUpdate batch = transport.local.getRefDatabase()
198 .newBatchUpdate()
199 .setAllowNonFastForwards(true)
200 .setRefLogMessage("fetch", true);
201 try (RevWalk walk = new RevWalk(transport.local)) {
202 if (monitor instanceof BatchingProgressMonitor) {
203 ((BatchingProgressMonitor) monitor).setDelayStart(
204 250, TimeUnit.MILLISECONDS);
205 }
206 if (transport.isRemoveDeletedRefs())
207 deleteStaleTrackingRefs(result, batch);
208 for (TrackingRefUpdate u : localUpdates) {
209 result.add(u);
210 batch.addCommand(u.asReceiveCommand());
211 }
212 for (ReceiveCommand cmd : batch.getCommands()) {
213 cmd.updateType(walk);
214 if (cmd.getType() == UPDATE_NONFASTFORWARD
215 && cmd instanceof TrackingRefUpdate.Command
216 && !((TrackingRefUpdate.Command) cmd).canForceUpdate())
217 cmd.setResult(REJECTED_NONFASTFORWARD);
218 }
219 if (transport.isDryRun()) {
220 for (ReceiveCommand cmd : batch.getCommands()) {
221 if (cmd.getResult() == NOT_ATTEMPTED)
222 cmd.setResult(OK);
223 }
224 } else
225 batch.execute(walk, monitor);
226 } catch (IOException err) {
227 throw new TransportException(MessageFormat.format(
228 JGitText.get().failureUpdatingTrackingRef,
229 getFirstFailedRefName(batch), err.getMessage()), err);
230 }
231
232 if (!fetchHeadUpdates.isEmpty()) {
233 try {
234 updateFETCH_HEAD(result);
235 } catch (IOException err) {
236 throw new TransportException(MessageFormat.format(
237 JGitText.get().failureUpdatingFETCH_HEAD, err.getMessage()), err);
238 }
239 }
240 }
241
242 private void fetchObjects(ProgressMonitor monitor)
243 throws TransportException {
244 try {
245 conn.setPackLockMessage("jgit fetch " + transport.uri);
246 conn.fetch(monitor, askFor.values(), have);
247 } finally {
248 packLocks.addAll(conn.getPackLocks());
249 }
250 if (transport.isCheckFetchedObjects()
251 && !conn.didFetchTestConnectivity() && !askForIsComplete())
252 throw new TransportException(transport.getURI(),
253 JGitText.get().peerDidNotSupplyACompleteObjectGraph);
254 }
255
256 private void closeConnection(FetchResult result) {
257 if (conn != null) {
258 conn.close();
259 result.addMessages(conn.getMessages());
260 conn = null;
261 }
262 }
263
264 private void reopenConnection() throws NotSupportedException,
265 TransportException {
266 if (conn != null)
267 return;
268
269 conn = transport.openFetch();
270
271
272
273
274
275
276
277
278
279 final HashMap<ObjectId, Ref> avail = new HashMap<>();
280 for (Ref r : conn.getRefs())
281 avail.put(r.getObjectId(), r);
282
283 final Collection<Ref> wants = new ArrayList<>(askFor.values());
284 askFor.clear();
285 for (Ref want : wants) {
286 final Ref newRef = avail.get(want.getObjectId());
287 if (newRef != null) {
288 askFor.put(newRef.getObjectId(), newRef);
289 } else {
290 removeFetchHeadRecord(want.getObjectId());
291 removeTrackingRefUpdate(want.getObjectId());
292 }
293 }
294 }
295
296 private void removeTrackingRefUpdate(ObjectId want) {
297 final Iterator<TrackingRefUpdate> i = localUpdates.iterator();
298 while (i.hasNext()) {
299 final TrackingRefUpdate u = i.next();
300 if (u.getNewObjectId().equals(want))
301 i.remove();
302 }
303 }
304
305 private void removeFetchHeadRecord(ObjectId want) {
306 final Iterator<FetchHeadRecord> i = fetchHeadUpdates.iterator();
307 while (i.hasNext()) {
308 final FetchHeadRecord fh = i.next();
309 if (fh.newValue.equals(want))
310 i.remove();
311 }
312 }
313
314 private void updateFETCH_HEAD(FetchResult result) throws IOException {
315 File meta = transport.local.getDirectory();
316 if (meta == null)
317 return;
318 final LockFile lock = new LockFile(new File(meta, "FETCH_HEAD"));
319 try {
320 if (lock.lock()) {
321 try (Writer w = new OutputStreamWriter(
322 lock.getOutputStream())) {
323 for (FetchHeadRecord h : fetchHeadUpdates) {
324 h.write(w);
325 result.add(h);
326 }
327 }
328 lock.commit();
329 }
330 } finally {
331 lock.unlock();
332 }
333 }
334
335 private boolean askForIsComplete() throws TransportException {
336 try {
337 try (ObjectWalk ow = new ObjectWalk(transport.local)) {
338 for (ObjectId want : askFor.keySet())
339 ow.markStart(ow.parseAny(want));
340 for (Ref ref : localRefs().values())
341 ow.markUninteresting(ow.parseAny(ref.getObjectId()));
342 ow.checkConnectivity();
343 }
344 return true;
345 } catch (MissingObjectException e) {
346 return false;
347 } catch (IOException e) {
348 throw new TransportException(JGitText.get().unableToCheckConnectivity, e);
349 }
350 }
351
352 private void expandWildcard(RefSpec spec, Set<Ref> matched)
353 throws TransportException {
354 for (Ref src : conn.getRefs()) {
355 if (spec.matchSource(src) && matched.add(src))
356 want(src, spec.expandFromSource(src));
357 }
358 }
359
360 private void expandSingle(RefSpec spec, Set<Ref> matched)
361 throws TransportException {
362 String want = spec.getSource();
363 if (ObjectId.isId(want)) {
364 want(ObjectId.fromString(want));
365 return;
366 }
367
368 Ref src = conn.getRef(want);
369 if (src == null) {
370 throw new TransportException(MessageFormat.format(JGitText.get().remoteDoesNotHaveSpec, want));
371 }
372 if (matched.add(src)) {
373 want(src, spec);
374 }
375 }
376
377 private Collection<Ref> expandAutoFollowTags() throws TransportException {
378 final Collection<Ref> additionalTags = new ArrayList<>();
379 final Map<String, Ref> haveRefs = localRefs();
380 for (Ref r : conn.getRefs()) {
381 if (!isTag(r))
382 continue;
383
384 Ref local = haveRefs.get(r.getName());
385 if (local != null)
386
387
388 continue;
389
390 ObjectId obj = r.getPeeledObjectId();
391 if (obj == null)
392 obj = r.getObjectId();
393
394 if (askFor.containsKey(obj) || transport.local.hasObject(obj))
395 wantTag(r);
396 else
397 additionalTags.add(r);
398 }
399 return additionalTags;
400 }
401
402 private void expandFetchTags() throws TransportException {
403 final Map<String, Ref> haveRefs = localRefs();
404 for (Ref r : conn.getRefs()) {
405 if (!isTag(r)) {
406 continue;
407 }
408 ObjectId id = r.getObjectId();
409 if (id == null) {
410 continue;
411 }
412 final Ref local = haveRefs.get(r.getName());
413 if (local == null || !id.equals(local.getObjectId())) {
414 wantTag(r);
415 }
416 }
417 }
418
419 private void wantTag(Ref r) throws TransportException {
420 want(r, new RefSpec().setSource(r.getName())
421 .setDestination(r.getName()).setForceUpdate(true));
422 }
423
424 private void want(Ref src, RefSpec spec)
425 throws TransportException {
426 final ObjectId newId = src.getObjectId();
427 if (newId == null) {
428 throw new NullPointerException(MessageFormat.format(
429 JGitText.get().transportProvidedRefWithNoObjectId,
430 src.getName()));
431 }
432 if (spec.getDestination() != null) {
433 final TrackingRefUpdate tru = createUpdate(spec, newId);
434 if (newId.equals(tru.getOldObjectId()))
435 return;
436 localUpdates.add(tru);
437 }
438
439 askFor.put(newId, src);
440
441 final FetchHeadRecord fhr = new FetchHeadRecord();
442 fhr.newValue = newId;
443 fhr.notForMerge = spec.getDestination() != null;
444 fhr.sourceName = src.getName();
445 fhr.sourceURI = transport.getURI();
446 fetchHeadUpdates.add(fhr);
447 }
448
449 private void want(ObjectId id) {
450 askFor.put(id,
451 new ObjectIdRef.Unpeeled(Ref.Storage.NETWORK, id.name(), id));
452 }
453
454 private TrackingRefUpdate createUpdate(RefSpec spec, ObjectId newId)
455 throws TransportException {
456 Ref ref = localRefs().get(spec.getDestination());
457 ObjectId oldId = ref != null && ref.getObjectId() != null
458 ? ref.getObjectId()
459 : ObjectId.zeroId();
460 return new TrackingRefUpdate(
461 spec.isForceUpdate(),
462 spec.getSource(),
463 spec.getDestination(),
464 oldId,
465 newId);
466 }
467
468 private Map<String, Ref> localRefs() throws TransportException {
469 if (localRefs == null) {
470 try {
471 localRefs = transport.local.getRefDatabase()
472 .getRefs(RefDatabase.ALL);
473 } catch (IOException err) {
474 throw new TransportException(JGitText.get().cannotListRefs, err);
475 }
476 }
477 return localRefs;
478 }
479
480 private void deleteStaleTrackingRefs(FetchResult result,
481 BatchRefUpdate batch) throws IOException {
482 for (Ref ref : localRefs().values()) {
483 if (ref.isSymbolic()) {
484 continue;
485 }
486 final String refname = ref.getName();
487 for (RefSpec spec : toFetch) {
488 if (spec.matchDestination(refname)) {
489 final RefSpec s = spec.expandFromDestination(refname);
490 if (result.getAdvertisedRef(s.getSource()) == null) {
491 deleteTrackingRef(result, batch, s, ref);
492 }
493 }
494 }
495 }
496 }
497
498 private void deleteTrackingRef(final FetchResult result,
499 final BatchRefUpdate batch, final RefSpec spec, final Ref localRef) {
500 if (localRef.getObjectId() == null)
501 return;
502 TrackingRefUpdate update = new TrackingRefUpdate(
503 true,
504 spec.getSource(),
505 localRef.getName(),
506 localRef.getObjectId(),
507 ObjectId.zeroId());
508 result.add(update);
509 batch.addCommand(update.asReceiveCommand());
510 }
511
512 private static boolean isTag(Ref r) {
513 return isTag(r.getName());
514 }
515
516 private static boolean isTag(String name) {
517 return name.startsWith(Constants.R_TAGS);
518 }
519
520 private static String getFirstFailedRefName(BatchRefUpdate batch) {
521 for (ReceiveCommand cmd : batch.getCommands()) {
522 if (cmd.getResult() != ReceiveCommand.Result.OK)
523 return cmd.getRefName();
524 }
525 return "";
526 }
527 }