View Javadoc
1   /*
2    * Copyright (C) 2008-2010, Google Inc.
3    * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com> and others
4    *
5    * This program and the accompanying materials are made available under the
6    * terms of the Eclipse Distribution License v. 1.0 which is available at
7    * https://www.eclipse.org/org/documents/edl-v10.php.
8    *
9    * SPDX-License-Identifier: BSD-3-Clause
10   */
11  
12  package org.eclipse.jgit.internal.storage.pack;
13  
14  import static java.util.Objects.requireNonNull;
15  import static org.eclipse.jgit.internal.storage.pack.StoredObjectRepresentation.PACK_DELTA;
16  import static org.eclipse.jgit.internal.storage.pack.StoredObjectRepresentation.PACK_WHOLE;
17  import static org.eclipse.jgit.lib.Constants.OBJECT_ID_LENGTH;
18  import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
19  import static org.eclipse.jgit.lib.Constants.OBJ_COMMIT;
20  import static org.eclipse.jgit.lib.Constants.OBJ_TAG;
21  import static org.eclipse.jgit.lib.Constants.OBJ_TREE;
22  
23  import java.io.IOException;
24  import java.io.OutputStream;
25  import java.lang.ref.WeakReference;
26  import java.security.MessageDigest;
27  import java.text.MessageFormat;
28  import java.util.ArrayList;
29  import java.util.Arrays;
30  import java.util.Collection;
31  import java.util.Collections;
32  import java.util.HashMap;
33  import java.util.HashSet;
34  import java.util.Iterator;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.NoSuchElementException;
38  import java.util.Set;
39  import java.util.concurrent.ConcurrentHashMap;
40  import java.util.concurrent.ExecutionException;
41  import java.util.concurrent.Executor;
42  import java.util.concurrent.ExecutorService;
43  import java.util.concurrent.Executors;
44  import java.util.concurrent.Future;
45  import java.util.concurrent.TimeUnit;
46  import java.util.zip.CRC32;
47  import java.util.zip.CheckedOutputStream;
48  import java.util.zip.Deflater;
49  import java.util.zip.DeflaterOutputStream;
50  
51  import org.eclipse.jgit.annotations.NonNull;
52  import org.eclipse.jgit.annotations.Nullable;
53  import org.eclipse.jgit.errors.CorruptObjectException;
54  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
55  import org.eclipse.jgit.errors.LargeObjectException;
56  import org.eclipse.jgit.errors.MissingObjectException;
57  import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
58  import org.eclipse.jgit.internal.JGitText;
59  import org.eclipse.jgit.internal.storage.file.PackBitmapIndexBuilder;
60  import org.eclipse.jgit.internal.storage.file.PackBitmapIndexWriterV1;
61  import org.eclipse.jgit.internal.storage.file.PackIndexWriter;
62  import org.eclipse.jgit.lib.AnyObjectId;
63  import org.eclipse.jgit.lib.AsyncObjectSizeQueue;
64  import org.eclipse.jgit.lib.BatchingProgressMonitor;
65  import org.eclipse.jgit.lib.BitmapIndex;
66  import org.eclipse.jgit.lib.BitmapIndex.BitmapBuilder;
67  import org.eclipse.jgit.lib.BitmapObject;
68  import org.eclipse.jgit.lib.Constants;
69  import org.eclipse.jgit.lib.NullProgressMonitor;
70  import org.eclipse.jgit.lib.ObjectId;
71  import org.eclipse.jgit.lib.ObjectIdOwnerMap;
72  import org.eclipse.jgit.lib.ObjectIdSet;
73  import org.eclipse.jgit.lib.ObjectLoader;
74  import org.eclipse.jgit.lib.ObjectReader;
75  import org.eclipse.jgit.lib.ProgressMonitor;
76  import org.eclipse.jgit.lib.Repository;
77  import org.eclipse.jgit.lib.ThreadSafeProgressMonitor;
78  import org.eclipse.jgit.revwalk.AsyncRevObjectQueue;
79  import org.eclipse.jgit.revwalk.BitmapWalker;
80  import org.eclipse.jgit.revwalk.DepthWalk;
81  import org.eclipse.jgit.revwalk.ObjectWalk;
82  import org.eclipse.jgit.revwalk.RevCommit;
83  import org.eclipse.jgit.revwalk.RevFlag;
84  import org.eclipse.jgit.revwalk.RevObject;
85  import org.eclipse.jgit.revwalk.RevSort;
86  import org.eclipse.jgit.revwalk.RevTag;
87  import org.eclipse.jgit.revwalk.RevTree;
88  import org.eclipse.jgit.storage.pack.PackConfig;
89  import org.eclipse.jgit.storage.pack.PackStatistics;
90  import org.eclipse.jgit.transport.FilterSpec;
91  import org.eclipse.jgit.transport.ObjectCountCallback;
92  import org.eclipse.jgit.transport.PacketLineOut;
93  import org.eclipse.jgit.transport.WriteAbortedException;
94  import org.eclipse.jgit.util.BlockList;
95  import org.eclipse.jgit.util.TemporaryBuffer;
96  
97  /**
98   * <p>
99   * PackWriter class is responsible for generating pack files from specified set
100  * of objects from repository. This implementation produce pack files in format
101  * version 2.
102  * </p>
103  * <p>
104  * Source of objects may be specified in two ways:
105  * <ul>
106  * <li>(usually) by providing sets of interesting and uninteresting objects in
107  * repository - all interesting objects and their ancestors except uninteresting
108  * objects and their ancestors will be included in pack, or</li>
109  * <li>by providing iterator of {@link org.eclipse.jgit.revwalk.RevObject}
110  * specifying exact list and order of objects in pack</li>
111  * </ul>
112  * <p>
113  * Typical usage consists of creating an instance, configuring options,
114  * preparing the list of objects by calling {@link #preparePack(Iterator)} or
115  * {@link #preparePack(ProgressMonitor, Set, Set)}, and streaming with
116  * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)}. If the
117  * pack is being stored as a file the matching index can be written out after
118  * writing the pack by {@link #writeIndex(OutputStream)}. An optional bitmap
119  * index can be made by calling {@link #prepareBitmapIndex(ProgressMonitor)}
120  * followed by {@link #writeBitmapIndex(OutputStream)}.
121  * </p>
122  * <p>
123  * Class provide set of configurable options and
124  * {@link org.eclipse.jgit.lib.ProgressMonitor} support, as operations may take
125  * a long time for big repositories. Deltas searching algorithm is <b>NOT
126  * IMPLEMENTED</b> yet - this implementation relies only on deltas and objects
127  * reuse.
128  * </p>
129  * <p>
130  * This class is not thread safe. It is intended to be used in one thread as a
131  * single pass to produce one pack. Invoking methods multiple times or out of
132  * order is not supported as internal data structures are destroyed during
133  * certain phases to save memory when packing large repositories.
134  * </p>
135  */
136 public class PackWriter implements AutoCloseable {
137 	private static final int PACK_VERSION_GENERATED = 2;
138 
139 	/** Empty set of objects for {@code preparePack()}. */
140 	public static final Set<ObjectId> NONE = Collections.emptySet();
141 
142 	private static final Map<WeakReference<PackWriter>, Boolean> instances =
143 			new ConcurrentHashMap<>();
144 
145 	private static final Iterable<PackWriter> instancesIterable = () -> new Iterator<PackWriter>() {
146 
147 		private final Iterator<WeakReference<PackWriter>> it = instances
148 				.keySet().iterator();
149 
150 		private PackWriter next;
151 
152 		@Override
153 		public boolean hasNext() {
154 			if (next != null) {
155 				return true;
156 			}
157 			while (it.hasNext()) {
158 				WeakReference<PackWriter> ref = it.next();
159 				next = ref.get();
160 				if (next != null) {
161 					return true;
162 				}
163 				it.remove();
164 			}
165 			return false;
166 		}
167 
168 		@Override
169 		public PackWriter next() {
170 			if (hasNext()) {
171 				PackWriter result = next;
172 				next = null;
173 				return result;
174 			}
175 			throw new NoSuchElementException();
176 		}
177 
178 		@Override
179 		public void remove() {
180 			throw new UnsupportedOperationException();
181 		}
182 	};
183 
184 	/**
185 	 * Get all allocated, non-released PackWriters instances.
186 	 *
187 	 * @return all allocated, non-released PackWriters instances.
188 	 */
189 	public static Iterable<PackWriter> getInstances() {
190 		return instancesIterable;
191 	}
192 
193 	@SuppressWarnings("unchecked")
194 	BlockList<ObjectToPack>[] objectsLists = new BlockList[OBJ_TAG + 1];
195 	{
196 		objectsLists[OBJ_COMMIT] = new BlockList<>();
197 		objectsLists[OBJ_TREE] = new BlockList<>();
198 		objectsLists[OBJ_BLOB] = new BlockList<>();
199 		objectsLists[OBJ_TAG] = new BlockList<>();
200 	}
201 
202 	private ObjectIdOwnerMap<ObjectToPack> objectsMap = new ObjectIdOwnerMap<>();
203 
204 	// edge objects for thin packs
205 	private List<ObjectToPack> edgeObjects = new BlockList<>();
206 
207 	// Objects the client is known to have already.
208 	private BitmapBuilder haveObjects;
209 
210 	private List<CachedPack> cachedPacks = new ArrayList<>(2);
211 
212 	private Set<ObjectId> tagTargets = NONE;
213 
214 	private Set<? extends ObjectId> excludeFromBitmapSelection = NONE;
215 
216 	private ObjectIdSet[] excludeInPacks;
217 
218 	private ObjectIdSet excludeInPackLast;
219 
220 	private Deflater myDeflater;
221 
222 	private final ObjectReader reader;
223 
224 	/** {@link #reader} recast to the reuse interface, if it supports it. */
225 	private final ObjectReuseAsIs reuseSupport;
226 
227 	final PackConfig config;
228 
229 	private final PackStatistics.Accumulator stats;
230 
231 	private final MutableState state;
232 
233 	private final WeakReference<PackWriter> selfRef;
234 
235 	private PackStatistics.ObjectType.Accumulator typeStats;
236 
237 	private List<ObjectToPack> sortedByName;
238 
239 	private byte[] packcsum;
240 
241 	private boolean deltaBaseAsOffset;
242 
243 	private boolean reuseDeltas;
244 
245 	private boolean reuseDeltaCommits;
246 
247 	private boolean reuseValidate;
248 
249 	private boolean thin;
250 
251 	private boolean useCachedPacks;
252 
253 	private boolean useBitmaps;
254 
255 	private boolean ignoreMissingUninteresting = true;
256 
257 	private boolean pruneCurrentObjectList;
258 
259 	private boolean shallowPack;
260 
261 	private boolean canBuildBitmaps;
262 
263 	private boolean indexDisabled;
264 
265 	private int depth;
266 
267 	private Collection<? extends ObjectId> unshallowObjects;
268 
269 	private PackBitmapIndexBuilder writeBitmaps;
270 
271 	private CRC32 crc32;
272 
273 	private ObjectCountCallback callback;
274 
275 	private FilterSpec filterSpec = FilterSpec.NO_FILTER;
276 
277 	private PackfileUriConfig packfileUriConfig;
278 
279 	/**
280 	 * Create writer for specified repository.
281 	 * <p>
282 	 * Objects for packing are specified in {@link #preparePack(Iterator)} or
283 	 * {@link #preparePack(ProgressMonitor, Set, Set)}.
284 	 *
285 	 * @param repo
286 	 *            repository where objects are stored.
287 	 */
288 	public PackWriter(Repository repo) {
289 		this(repo, repo.newObjectReader());
290 	}
291 
292 	/**
293 	 * Create a writer to load objects from the specified reader.
294 	 * <p>
295 	 * Objects for packing are specified in {@link #preparePack(Iterator)} or
296 	 * {@link #preparePack(ProgressMonitor, Set, Set)}.
297 	 *
298 	 * @param reader
299 	 *            reader to read from the repository with.
300 	 */
301 	public PackWriter(ObjectReader reader) {
302 		this(new PackConfig(), reader);
303 	}
304 
305 	/**
306 	 * Create writer for specified repository.
307 	 * <p>
308 	 * Objects for packing are specified in {@link #preparePack(Iterator)} or
309 	 * {@link #preparePack(ProgressMonitor, Set, Set)}.
310 	 *
311 	 * @param repo
312 	 *            repository where objects are stored.
313 	 * @param reader
314 	 *            reader to read from the repository with.
315 	 */
316 	public PackWriter(Repository repo, ObjectReader reader) {
317 		this(new PackConfig(repo), reader);
318 	}
319 
320 	/**
321 	 * Create writer with a specified configuration.
322 	 * <p>
323 	 * Objects for packing are specified in {@link #preparePack(Iterator)} or
324 	 * {@link #preparePack(ProgressMonitor, Set, Set)}.
325 	 *
326 	 * @param config
327 	 *            configuration for the pack writer.
328 	 * @param reader
329 	 *            reader to read from the repository with.
330 	 */
331 	public PackWriter(PackConfig config, ObjectReader reader) {
332 		this(config, reader, null);
333 	}
334 
335 	/**
336 	 * Create writer with a specified configuration.
337 	 * <p>
338 	 * Objects for packing are specified in {@link #preparePack(Iterator)} or
339 	 * {@link #preparePack(ProgressMonitor, Set, Set)}.
340 	 *
341 	 * @param config
342 	 *            configuration for the pack writer.
343 	 * @param reader
344 	 *            reader to read from the repository with.
345 	 * @param statsAccumulator
346 	 *            accumulator for statics
347 	 */
348 	public PackWriter(PackConfig config, final ObjectReader reader,
349 			@Nullable PackStatistics.Accumulator statsAccumulator) {
350 		this.config = config;
351 		this.reader = reader;
352 		if (reader instanceof ObjectReuseAsIs)
353 			reuseSupport = ((ObjectReuseAsIs) reader);
354 		else
355 			reuseSupport = null;
356 
357 		deltaBaseAsOffset = config.isDeltaBaseAsOffset();
358 		reuseDeltas = config.isReuseDeltas();
359 		reuseValidate = true; // be paranoid by default
360 		stats = statsAccumulator != null ? statsAccumulator
361 				: new PackStatistics.Accumulator();
362 		state = new MutableState();
363 		selfRef = new WeakReference<>(this);
364 		instances.put(selfRef, Boolean.TRUE);
365 	}
366 
367 	/**
368 	 * Set the {@code ObjectCountCallback}.
369 	 * <p>
370 	 * It should be set before calling
371 	 * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)}.
372 	 *
373 	 * @param callback
374 	 *            the callback to set
375 	 * @return this object for chaining.
376 	 */
377 	public PackWriter setObjectCountCallback(ObjectCountCallback callback) {
378 		this.callback = callback;
379 		return this;
380 	}
381 
382 	/**
383 	 * Records the set of shallow commits in the client.
384 	 *
385 	 * @param clientShallowCommits
386 	 *            the shallow commits in the client
387 	 */
388 	public void setClientShallowCommits(Set<ObjectId> clientShallowCommits) {
389 		stats.clientShallowCommits = Collections
390 				.unmodifiableSet(new HashSet<>(clientShallowCommits));
391 	}
392 
393 	/**
394 	 * Check whether writer can store delta base as an offset (new style
395 	 * reducing pack size) or should store it as an object id (legacy style,
396 	 * compatible with old readers).
397 	 *
398 	 * Default setting: {@value PackConfig#DEFAULT_DELTA_BASE_AS_OFFSET}
399 	 *
400 	 * @return true if delta base is stored as an offset; false if it is stored
401 	 *         as an object id.
402 	 */
403 	public boolean isDeltaBaseAsOffset() {
404 		return deltaBaseAsOffset;
405 	}
406 
407 	/**
408 	 * Set writer delta base format. Delta base can be written as an offset in a
409 	 * pack file (new approach reducing file size) or as an object id (legacy
410 	 * approach, compatible with old readers).
411 	 *
412 	 * Default setting: {@value PackConfig#DEFAULT_DELTA_BASE_AS_OFFSET}
413 	 *
414 	 * @param deltaBaseAsOffset
415 	 *            boolean indicating whether delta base can be stored as an
416 	 *            offset.
417 	 */
418 	public void setDeltaBaseAsOffset(boolean deltaBaseAsOffset) {
419 		this.deltaBaseAsOffset = deltaBaseAsOffset;
420 	}
421 
422 	/**
423 	 * Check if the writer will reuse commits that are already stored as deltas.
424 	 *
425 	 * @return true if the writer would reuse commits stored as deltas, assuming
426 	 *         delta reuse is already enabled.
427 	 */
428 	public boolean isReuseDeltaCommits() {
429 		return reuseDeltaCommits;
430 	}
431 
432 	/**
433 	 * Set the writer to reuse existing delta versions of commits.
434 	 *
435 	 * @param reuse
436 	 *            if true, the writer will reuse any commits stored as deltas.
437 	 *            By default the writer does not reuse delta commits.
438 	 */
439 	public void setReuseDeltaCommits(boolean reuse) {
440 		reuseDeltaCommits = reuse;
441 	}
442 
443 	/**
444 	 * Check if the writer validates objects before copying them.
445 	 *
446 	 * @return true if validation is enabled; false if the reader will handle
447 	 *         object validation as a side-effect of it consuming the output.
448 	 */
449 	public boolean isReuseValidatingObjects() {
450 		return reuseValidate;
451 	}
452 
453 	/**
454 	 * Enable (or disable) object validation during packing.
455 	 *
456 	 * @param validate
457 	 *            if true the pack writer will validate an object before it is
458 	 *            put into the output. This additional validation work may be
459 	 *            necessary to avoid propagating corruption from one local pack
460 	 *            file to another local pack file.
461 	 */
462 	public void setReuseValidatingObjects(boolean validate) {
463 		reuseValidate = validate;
464 	}
465 
466 	/**
467 	 * Whether this writer is producing a thin pack.
468 	 *
469 	 * @return true if this writer is producing a thin pack.
470 	 */
471 	public boolean isThin() {
472 		return thin;
473 	}
474 
475 	/**
476 	 * Whether writer may pack objects with delta base object not within set of
477 	 * objects to pack
478 	 *
479 	 * @param packthin
480 	 *            a boolean indicating whether writer may pack objects with
481 	 *            delta base object not within set of objects to pack, but
482 	 *            belonging to party repository (uninteresting/boundary) as
483 	 *            determined by set; this kind of pack is used only for
484 	 *            transport; true - to produce thin pack, false - otherwise.
485 	 */
486 	public void setThin(boolean packthin) {
487 		thin = packthin;
488 	}
489 
490 	/**
491 	 * Whether to reuse cached packs.
492 	 *
493 	 * @return {@code true} to reuse cached packs. If true index creation isn't
494 	 *         available.
495 	 */
496 	public boolean isUseCachedPacks() {
497 		return useCachedPacks;
498 	}
499 
500 	/**
501 	 * Whether to use cached packs
502 	 *
503 	 * @param useCached
504 	 *            if set to {@code true} and a cached pack is present, it will
505 	 *            be appended onto the end of a thin-pack, reducing the amount
506 	 *            of working set space and CPU used by PackWriter. Enabling this
507 	 *            feature prevents PackWriter from creating an index for the
508 	 *            newly created pack, so its only suitable for writing to a
509 	 *            network client, where the client will make the index.
510 	 */
511 	public void setUseCachedPacks(boolean useCached) {
512 		useCachedPacks = useCached;
513 	}
514 
515 	/**
516 	 * Whether to use bitmaps
517 	 *
518 	 * @return {@code true} to use bitmaps for ObjectWalks, if available.
519 	 */
520 	public boolean isUseBitmaps() {
521 		return useBitmaps;
522 	}
523 
524 	/**
525 	 * Whether to use bitmaps
526 	 *
527 	 * @param useBitmaps
528 	 *            if set to true, bitmaps will be used when preparing a pack.
529 	 */
530 	public void setUseBitmaps(boolean useBitmaps) {
531 		this.useBitmaps = useBitmaps;
532 	}
533 
534 	/**
535 	 * Whether the index file cannot be created by this PackWriter.
536 	 *
537 	 * @return {@code true} if the index file cannot be created by this
538 	 *         PackWriter.
539 	 */
540 	public boolean isIndexDisabled() {
541 		return indexDisabled || !cachedPacks.isEmpty();
542 	}
543 
544 	/**
545 	 * Whether to disable creation of the index file.
546 	 *
547 	 * @param noIndex
548 	 *            {@code true} to disable creation of the index file.
549 	 */
550 	public void setIndexDisabled(boolean noIndex) {
551 		this.indexDisabled = noIndex;
552 	}
553 
554 	/**
555 	 * Whether to ignore missing uninteresting objects
556 	 *
557 	 * @return {@code true} to ignore objects that are uninteresting and also
558 	 *         not found on local disk; false to throw a
559 	 *         {@link org.eclipse.jgit.errors.MissingObjectException} out of
560 	 *         {@link #preparePack(ProgressMonitor, Set, Set)} if an
561 	 *         uninteresting object is not in the source repository. By default,
562 	 *         true, permitting gracefully ignoring of uninteresting objects.
563 	 */
564 	public boolean isIgnoreMissingUninteresting() {
565 		return ignoreMissingUninteresting;
566 	}
567 
568 	/**
569 	 * Whether writer should ignore non existing uninteresting objects
570 	 *
571 	 * @param ignore
572 	 *            {@code true} if writer should ignore non existing
573 	 *            uninteresting objects during construction set of objects to
574 	 *            pack; false otherwise - non existing uninteresting objects may
575 	 *            cause {@link org.eclipse.jgit.errors.MissingObjectException}
576 	 */
577 	public void setIgnoreMissingUninteresting(boolean ignore) {
578 		ignoreMissingUninteresting = ignore;
579 	}
580 
581 	/**
582 	 * Set the tag targets that should be hoisted earlier during packing.
583 	 * <p>
584 	 * Callers may put objects into this set before invoking any of the
585 	 * preparePack methods to influence where an annotated tag's target is
586 	 * stored within the resulting pack. Typically these will be clustered
587 	 * together, and hoisted earlier in the file even if they are ancient
588 	 * revisions, allowing readers to find tag targets with better locality.
589 	 *
590 	 * @param objects
591 	 *            objects that annotated tags point at.
592 	 */
593 	public void setTagTargets(Set<ObjectId> objects) {
594 		tagTargets = objects;
595 	}
596 
597 	/**
598 	 * Configure this pack for a shallow clone.
599 	 *
600 	 * @param depth
601 	 *            maximum depth of history to return. 1 means return only the
602 	 *            "wants".
603 	 * @param unshallow
604 	 *            objects which used to be shallow on the client, but are being
605 	 *            extended as part of this fetch
606 	 */
607 	public void setShallowPack(int depth,
608 			Collection<? extends ObjectId> unshallow) {
609 		this.shallowPack = true;
610 		this.depth = depth;
611 		this.unshallowObjects = unshallow;
612 	}
613 
614 	/**
615 	 * @param filter the filter which indicates what and what not this writer
616 	 *            should include
617 	 */
618 	public void setFilterSpec(@NonNull FilterSpec filter) {
619 		filterSpec = requireNonNull(filter);
620 	}
621 
622 	/**
623 	 * @param config configuration related to packfile URIs
624 	 * @since 5.5
625 	 */
626 	public void setPackfileUriConfig(PackfileUriConfig config) {
627 		packfileUriConfig = config;
628 	}
629 
630 	/**
631 	 * Returns objects number in a pack file that was created by this writer.
632 	 *
633 	 * @return number of objects in pack.
634 	 * @throws java.io.IOException
635 	 *             a cached pack cannot supply its object count.
636 	 */
637 	public long getObjectCount() throws IOException {
638 		if (stats.totalObjects == 0) {
639 			long objCnt = 0;
640 
641 			objCnt += objectsLists[OBJ_COMMIT].size();
642 			objCnt += objectsLists[OBJ_TREE].size();
643 			objCnt += objectsLists[OBJ_BLOB].size();
644 			objCnt += objectsLists[OBJ_TAG].size();
645 
646 			for (CachedPack pack : cachedPacks)
647 				objCnt += pack.getObjectCount();
648 			return objCnt;
649 		}
650 		return stats.totalObjects;
651 	}
652 
653 	private long getUnoffloadedObjectCount() throws IOException {
654 		long objCnt = 0;
655 
656 		objCnt += objectsLists[OBJ_COMMIT].size();
657 		objCnt += objectsLists[OBJ_TREE].size();
658 		objCnt += objectsLists[OBJ_BLOB].size();
659 		objCnt += objectsLists[OBJ_TAG].size();
660 
661 		for (CachedPack pack : cachedPacks) {
662 			CachedPackUriProvider.PackInfo packInfo =
663 				packfileUriConfig.cachedPackUriProvider.getInfo(
664 					pack, packfileUriConfig.protocolsSupported);
665 			if (packInfo == null) {
666 				objCnt += pack.getObjectCount();
667 			}
668 		}
669 
670 		return objCnt;
671 	}
672 
673 	/**
674 	 * Returns the object ids in the pack file that was created by this writer.
675 	 * <p>
676 	 * This method can only be invoked after
677 	 * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)} has
678 	 * been invoked and completed successfully.
679 	 *
680 	 * @return set of objects in pack.
681 	 * @throws java.io.IOException
682 	 *             a cached pack cannot supply its object ids.
683 	 */
684 	public ObjectIdOwnerMap<ObjectIdOwnerMap.Entry> getObjectSet()
685 			throws IOException {
686 		if (!cachedPacks.isEmpty())
687 			throw new IOException(
688 					JGitText.get().cachedPacksPreventsListingObjects);
689 
690 		if (writeBitmaps != null) {
691 			return writeBitmaps.getObjectSet();
692 		}
693 
694 		ObjectIdOwnerMap<ObjectIdOwnerMap.Entry> r = new ObjectIdOwnerMap<>();
695 		for (BlockList<ObjectToPack> objList : objectsLists) {
696 			if (objList != null) {
697 				for (ObjectToPack otp : objList)
698 					r.add(new ObjectIdOwnerMap.Entry(otp) {
699 						// A new entry that copies the ObjectId
700 					});
701 			}
702 		}
703 		return r;
704 	}
705 
706 	/**
707 	 * Add a pack index whose contents should be excluded from the result.
708 	 *
709 	 * @param idx
710 	 *            objects in this index will not be in the output pack.
711 	 */
712 	public void excludeObjects(ObjectIdSet idx) {
713 		if (excludeInPacks == null) {
714 			excludeInPacks = new ObjectIdSet[] { idx };
715 			excludeInPackLast = idx;
716 		} else {
717 			int cnt = excludeInPacks.length;
718 			ObjectIdSet[] newList = new ObjectIdSet[cnt + 1];
719 			System.arraycopy(excludeInPacks, 0, newList, 0, cnt);
720 			newList[cnt] = idx;
721 			excludeInPacks = newList;
722 		}
723 	}
724 
725 	/**
726 	 * Prepare the list of objects to be written to the pack stream.
727 	 * <p>
728 	 * Iterator <b>exactly</b> determines which objects are included in a pack
729 	 * and order they appear in pack (except that objects order by type is not
730 	 * needed at input). This order should conform general rules of ordering
731 	 * objects in git - by recency and path (type and delta-base first is
732 	 * internally secured) and responsibility for guaranteeing this order is on
733 	 * a caller side. Iterator must return each id of object to write exactly
734 	 * once.
735 	 * </p>
736 	 *
737 	 * @param objectsSource
738 	 *            iterator of object to store in a pack; order of objects within
739 	 *            each type is important, ordering by type is not needed;
740 	 *            allowed types for objects are
741 	 *            {@link org.eclipse.jgit.lib.Constants#OBJ_COMMIT},
742 	 *            {@link org.eclipse.jgit.lib.Constants#OBJ_TREE},
743 	 *            {@link org.eclipse.jgit.lib.Constants#OBJ_BLOB} and
744 	 *            {@link org.eclipse.jgit.lib.Constants#OBJ_TAG}; objects
745 	 *            returned by iterator may be later reused by caller as object
746 	 *            id and type are internally copied in each iteration.
747 	 * @throws java.io.IOException
748 	 *             when some I/O problem occur during reading objects.
749 	 */
750 	public void preparePack(@NonNull Iterator<RevObject> objectsSource)
751 			throws IOException {
752 		while (objectsSource.hasNext()) {
753 			addObject(objectsSource.next());
754 		}
755 	}
756 
757 	/**
758 	 * Prepare the list of objects to be written to the pack stream.
759 	 * <p>
760 	 * Basing on these 2 sets, another set of objects to put in a pack file is
761 	 * created: this set consists of all objects reachable (ancestors) from
762 	 * interesting objects, except uninteresting objects and their ancestors.
763 	 * This method uses class {@link org.eclipse.jgit.revwalk.ObjectWalk}
764 	 * extensively to find out that appropriate set of output objects and their
765 	 * optimal order in output pack. Order is consistent with general git
766 	 * in-pack rules: sort by object type, recency, path and delta-base first.
767 	 * </p>
768 	 *
769 	 * @param countingMonitor
770 	 *            progress during object enumeration.
771 	 * @param want
772 	 *            collection of objects to be marked as interesting (start
773 	 *            points of graph traversal). Must not be {@code null}.
774 	 * @param have
775 	 *            collection of objects to be marked as uninteresting (end
776 	 *            points of graph traversal). Pass {@link #NONE} if all objects
777 	 *            reachable from {@code want} are desired, such as when serving
778 	 *            a clone.
779 	 * @throws java.io.IOException
780 	 *             when some I/O problem occur during reading objects.
781 	 */
782 	public void preparePack(ProgressMonitor countingMonitor,
783 			@NonNull Set<? extends ObjectId> want,
784 			@NonNull Set<? extends ObjectId> have) throws IOException {
785 		preparePack(countingMonitor, want, have, NONE, NONE);
786 	}
787 
788 	/**
789 	 * Prepare the list of objects to be written to the pack stream.
790 	 * <p>
791 	 * Like {@link #preparePack(ProgressMonitor, Set, Set)} but also allows
792 	 * specifying commits that should not be walked past ("shallow" commits).
793 	 * The caller is responsible for filtering out commits that should not be
794 	 * shallow any more ("unshallow" commits as in {@link #setShallowPack}) from
795 	 * the shallow set.
796 	 *
797 	 * @param countingMonitor
798 	 *            progress during object enumeration.
799 	 * @param want
800 	 *            objects of interest, ancestors of which will be included in
801 	 *            the pack. Must not be {@code null}.
802 	 * @param have
803 	 *            objects whose ancestors (up to and including {@code shallow}
804 	 *            commits) do not need to be included in the pack because they
805 	 *            are already available from elsewhere. Must not be
806 	 *            {@code null}.
807 	 * @param shallow
808 	 *            commits indicating the boundary of the history marked with
809 	 *            {@code have}. Shallow commits have parents but those parents
810 	 *            are considered not to be already available. Parents of
811 	 *            {@code shallow} commits and earlier generations will be
812 	 *            included in the pack if requested by {@code want}. Must not be
813 	 *            {@code null}.
814 	 * @throws java.io.IOException
815 	 *             an I/O problem occurred while reading objects.
816 	 */
817 	public void preparePack(ProgressMonitor countingMonitor,
818 			@NonNull Set<? extends ObjectId> want,
819 			@NonNull Set<? extends ObjectId> have,
820 			@NonNull Set<? extends ObjectId> shallow) throws IOException {
821 		preparePack(countingMonitor, want, have, shallow, NONE);
822 	}
823 
824 	/**
825 	 * Prepare the list of objects to be written to the pack stream.
826 	 * <p>
827 	 * Like {@link #preparePack(ProgressMonitor, Set, Set)} but also allows
828 	 * specifying commits that should not be walked past ("shallow" commits).
829 	 * The caller is responsible for filtering out commits that should not be
830 	 * shallow any more ("unshallow" commits as in {@link #setShallowPack}) from
831 	 * the shallow set.
832 	 *
833 	 * @param countingMonitor
834 	 *            progress during object enumeration.
835 	 * @param want
836 	 *            objects of interest, ancestors of which will be included in
837 	 *            the pack. Must not be {@code null}.
838 	 * @param have
839 	 *            objects whose ancestors (up to and including {@code shallow}
840 	 *            commits) do not need to be included in the pack because they
841 	 *            are already available from elsewhere. Must not be
842 	 *            {@code null}.
843 	 * @param shallow
844 	 *            commits indicating the boundary of the history marked with
845 	 *            {@code have}. Shallow commits have parents but those parents
846 	 *            are considered not to be already available. Parents of
847 	 *            {@code shallow} commits and earlier generations will be
848 	 *            included in the pack if requested by {@code want}. Must not be
849 	 *            {@code null}.
850 	 * @param noBitmaps
851 	 *            collection of objects to be excluded from bitmap commit
852 	 *            selection.
853 	 * @throws java.io.IOException
854 	 *             an I/O problem occurred while reading objects.
855 	 */
856 	public void preparePack(ProgressMonitor countingMonitor,
857 			@NonNull Set<? extends ObjectId> want,
858 			@NonNull Set<? extends ObjectId> have,
859 			@NonNull Set<? extends ObjectId> shallow,
860 			@NonNull Set<? extends ObjectId> noBitmaps) throws IOException {
861 		try (ObjectWalk ow = getObjectWalk()) {
862 			ow.assumeShallow(shallow);
863 			preparePack(countingMonitor, ow, want, have, noBitmaps);
864 		}
865 	}
866 
867 	private ObjectWalk getObjectWalk() {
868 		return shallowPack ? new DepthWalk.ObjectWalk(reader, depth - 1)
869 				: new ObjectWalk(reader);
870 	}
871 
872 	/**
873 	 * A visitation policy which uses the depth at which the object is seen to
874 	 * decide if re-traversal is necessary. In particular, if the object has
875 	 * already been visited at this depth or shallower, it is not necessary to
876 	 * re-visit at this depth.
877 	 */
878 	private static class DepthAwareVisitationPolicy
879 			implements ObjectWalk.VisitationPolicy {
880 		private final Map<ObjectId, Integer> lowestDepthVisited = new HashMap<>();
881 
882 		private final ObjectWalk walk;
883 
884 		DepthAwareVisitationPolicy(ObjectWalk walk) {
885 			this.walk = requireNonNull(walk);
886 		}
887 
888 		@Override
889 		public boolean shouldVisit(RevObject o) {
890 			Integer lastDepth = lowestDepthVisited.get(o);
891 			if (lastDepth == null) {
892 				return true;
893 			}
894 			return walk.getTreeDepth() < lastDepth.intValue();
895 		}
896 
897 		@Override
898 		public void visited(RevObject o) {
899 			lowestDepthVisited.put(o, Integer.valueOf(walk.getTreeDepth()));
900 		}
901 	}
902 
903 	/**
904 	 * Prepare the list of objects to be written to the pack stream.
905 	 * <p>
906 	 * Basing on these 2 sets, another set of objects to put in a pack file is
907 	 * created: this set consists of all objects reachable (ancestors) from
908 	 * interesting objects, except uninteresting objects and their ancestors.
909 	 * This method uses class {@link org.eclipse.jgit.revwalk.ObjectWalk}
910 	 * extensively to find out that appropriate set of output objects and their
911 	 * optimal order in output pack. Order is consistent with general git
912 	 * in-pack rules: sort by object type, recency, path and delta-base first.
913 	 * </p>
914 	 *
915 	 * @param countingMonitor
916 	 *            progress during object enumeration.
917 	 * @param walk
918 	 *            ObjectWalk to perform enumeration.
919 	 * @param interestingObjects
920 	 *            collection of objects to be marked as interesting (start
921 	 *            points of graph traversal). Must not be {@code null}.
922 	 * @param uninterestingObjects
923 	 *            collection of objects to be marked as uninteresting (end
924 	 *            points of graph traversal). Pass {@link #NONE} if all objects
925 	 *            reachable from {@code want} are desired, such as when serving
926 	 *            a clone.
927 	 * @param noBitmaps
928 	 *            collection of objects to be excluded from bitmap commit
929 	 *            selection.
930 	 * @throws java.io.IOException
931 	 *             when some I/O problem occur during reading objects.
932 	 */
933 	public void preparePack(ProgressMonitor countingMonitor,
934 			@NonNull ObjectWalk walk,
935 			@NonNull Set<? extends ObjectId> interestingObjects,
936 			@NonNull Set<? extends ObjectId> uninterestingObjects,
937 			@NonNull Set<? extends ObjectId> noBitmaps)
938 			throws IOException {
939 		if (countingMonitor == null)
940 			countingMonitor = NullProgressMonitor.INSTANCE;
941 		if (shallowPack && !(walk instanceof DepthWalk.ObjectWalk))
942 			throw new IllegalArgumentException(
943 					JGitText.get().shallowPacksRequireDepthWalk);
944 		if (filterSpec.getTreeDepthLimit() >= 0) {
945 			walk.setVisitationPolicy(new DepthAwareVisitationPolicy(walk));
946 		}
947 		findObjectsToPack(countingMonitor, walk, interestingObjects,
948 				uninterestingObjects, noBitmaps);
949 	}
950 
951 	/**
952 	 * Determine if the pack file will contain the requested object.
953 	 *
954 	 * @param id
955 	 *            the object to test the existence of.
956 	 * @return true if the object will appear in the output pack file.
957 	 * @throws java.io.IOException
958 	 *             a cached pack cannot be examined.
959 	 */
960 	public boolean willInclude(AnyObjectId id) throws IOException {
961 		ObjectToPack obj = objectsMap.get(id);
962 		return obj != null && !obj.isEdge();
963 	}
964 
965 	/**
966 	 * Lookup the ObjectToPack object for a given ObjectId.
967 	 *
968 	 * @param id
969 	 *            the object to find in the pack.
970 	 * @return the object we are packing, or null.
971 	 */
972 	public ObjectToPack get(AnyObjectId id) {
973 		ObjectToPack obj = objectsMap.get(id);
974 		return obj != null && !obj.isEdge() ? obj : null;
975 	}
976 
977 	/**
978 	 * Computes SHA-1 of lexicographically sorted objects ids written in this
979 	 * pack, as used to name a pack file in repository.
980 	 *
981 	 * @return ObjectId representing SHA-1 name of a pack that was created.
982 	 */
983 	public ObjectId computeName() {
984 		final byte[] buf = new byte[OBJECT_ID_LENGTH];
985 		final MessageDigest md = Constants.newMessageDigest();
986 		for (ObjectToPack otp : sortByName()) {
987 			otp.copyRawTo(buf, 0);
988 			md.update(buf, 0, OBJECT_ID_LENGTH);
989 		}
990 		return ObjectId.fromRaw(md.digest());
991 	}
992 
993 	/**
994 	 * Returns the index format version that will be written.
995 	 * <p>
996 	 * This method can only be invoked after
997 	 * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)} has
998 	 * been invoked and completed successfully.
999 	 *
1000 	 * @return the index format version.
1001 	 */
1002 	public int getIndexVersion() {
1003 		int indexVersion = config.getIndexVersion();
1004 		if (indexVersion <= 0) {
1005 			for (BlockList<ObjectToPack> objs : objectsLists)
1006 				indexVersion = Math.max(indexVersion,
1007 						PackIndexWriter.oldestPossibleFormat(objs));
1008 		}
1009 		return indexVersion;
1010 	}
1011 
1012 	/**
1013 	 * Create an index file to match the pack file just written.
1014 	 * <p>
1015 	 * Called after
1016 	 * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)}.
1017 	 * <p>
1018 	 * Writing an index is only required for local pack storage. Packs sent on
1019 	 * the network do not need to create an index.
1020 	 *
1021 	 * @param indexStream
1022 	 *            output for the index data. Caller is responsible for closing
1023 	 *            this stream.
1024 	 * @throws java.io.IOException
1025 	 *             the index data could not be written to the supplied stream.
1026 	 */
1027 	public void writeIndex(OutputStream indexStream) throws IOException {
1028 		if (isIndexDisabled())
1029 			throw new IOException(JGitText.get().cachedPacksPreventsIndexCreation);
1030 
1031 		long writeStart = System.currentTimeMillis();
1032 		final PackIndexWriter iw = PackIndexWriter.createVersion(
1033 				indexStream, getIndexVersion());
1034 		iw.write(sortByName(), packcsum);
1035 		stats.timeWriting += System.currentTimeMillis() - writeStart;
1036 	}
1037 
1038 	/**
1039 	 * Create a bitmap index file to match the pack file just written.
1040 	 * <p>
1041 	 * Called after {@link #prepareBitmapIndex(ProgressMonitor)}.
1042 	 *
1043 	 * @param bitmapIndexStream
1044 	 *            output for the bitmap index data. Caller is responsible for
1045 	 *            closing this stream.
1046 	 * @throws java.io.IOException
1047 	 *             the index data could not be written to the supplied stream.
1048 	 */
1049 	public void writeBitmapIndex(OutputStream bitmapIndexStream)
1050 			throws IOException {
1051 		if (writeBitmaps == null)
1052 			throw new IOException(JGitText.get().bitmapsMustBePrepared);
1053 
1054 		long writeStart = System.currentTimeMillis();
1055 		final PackBitmapIndexWriterV1ile/PackBitmapIndexWriterV1.html#PackBitmapIndexWriterV1">PackBitmapIndexWriterV1 iw = new PackBitmapIndexWriterV1(bitmapIndexStream);
1056 		iw.write(writeBitmaps, packcsum);
1057 		stats.timeWriting += System.currentTimeMillis() - writeStart;
1058 	}
1059 
1060 	private List<ObjectToPack> sortByName() {
1061 		if (sortedByName == null) {
1062 			int cnt = 0;
1063 			cnt += objectsLists[OBJ_COMMIT].size();
1064 			cnt += objectsLists[OBJ_TREE].size();
1065 			cnt += objectsLists[OBJ_BLOB].size();
1066 			cnt += objectsLists[OBJ_TAG].size();
1067 
1068 			sortedByName = new BlockList<>(cnt);
1069 			sortedByName.addAll(objectsLists[OBJ_COMMIT]);
1070 			sortedByName.addAll(objectsLists[OBJ_TREE]);
1071 			sortedByName.addAll(objectsLists[OBJ_BLOB]);
1072 			sortedByName.addAll(objectsLists[OBJ_TAG]);
1073 			Collections.sort(sortedByName);
1074 		}
1075 		return sortedByName;
1076 	}
1077 
1078 	private void beginPhase(PackingPhase phase, ProgressMonitor monitor,
1079 			long cnt) {
1080 		state.phase = phase;
1081 		String task;
1082 		switch (phase) {
1083 		case COUNTING:
1084 			task = JGitText.get().countingObjects;
1085 			break;
1086 		case GETTING_SIZES:
1087 			task = JGitText.get().searchForSizes;
1088 			break;
1089 		case FINDING_SOURCES:
1090 			task = JGitText.get().searchForReuse;
1091 			break;
1092 		case COMPRESSING:
1093 			task = JGitText.get().compressingObjects;
1094 			break;
1095 		case WRITING:
1096 			task = JGitText.get().writingObjects;
1097 			break;
1098 		case BUILDING_BITMAPS:
1099 			task = JGitText.get().buildingBitmaps;
1100 			break;
1101 		default:
1102 			throw new IllegalArgumentException(
1103 					MessageFormat.format(JGitText.get().illegalPackingPhase, phase));
1104 		}
1105 		monitor.beginTask(task, (int) cnt);
1106 	}
1107 
1108 	private void endPhase(ProgressMonitor monitor) {
1109 		monitor.endTask();
1110 	}
1111 
1112 	/**
1113 	 * Write the prepared pack to the supplied stream.
1114 	 * <p>
1115 	 * Called after
1116 	 * {@link #preparePack(ProgressMonitor, ObjectWalk, Set, Set, Set)} or
1117 	 * {@link #preparePack(ProgressMonitor, Set, Set)}.
1118 	 * <p>
1119 	 * Performs delta search if enabled and writes the pack stream.
1120 	 * <p>
1121 	 * All reused objects data checksum (Adler32/CRC32) is computed and
1122 	 * validated against existing checksum.
1123 	 *
1124 	 * @param compressMonitor
1125 	 *            progress monitor to report object compression work.
1126 	 * @param writeMonitor
1127 	 *            progress monitor to report the number of objects written.
1128 	 * @param packStream
1129 	 *            output stream of pack data. The stream should be buffered by
1130 	 *            the caller. The caller is responsible for closing the stream.
1131 	 * @throws java.io.IOException
1132 	 *             an error occurred reading a local object's data to include in
1133 	 *             the pack, or writing compressed object data to the output
1134 	 *             stream.
1135 	 * @throws WriteAbortedException
1136 	 *             the write operation is aborted by
1137 	 *             {@link org.eclipse.jgit.transport.ObjectCountCallback} .
1138 	 */
1139 	public void writePack(ProgressMonitor compressMonitor,
1140 			ProgressMonitor writeMonitor, OutputStream packStream)
1141 			throws IOException {
1142 		if (compressMonitor == null)
1143 			compressMonitor = NullProgressMonitor.INSTANCE;
1144 		if (writeMonitor == null)
1145 			writeMonitor = NullProgressMonitor.INSTANCE;
1146 
1147 		excludeInPacks = null;
1148 		excludeInPackLast = null;
1149 
1150 		boolean needSearchForReuse = reuseSupport != null && (
1151 				   reuseDeltas
1152 				|| config.isReuseObjects()
1153 				|| !cachedPacks.isEmpty());
1154 
1155 		if (compressMonitor instanceof BatchingProgressMonitor) {
1156 			long delay = 1000;
1157 			if (needSearchForReuse && config.isDeltaCompress())
1158 				delay = 500;
1159 			((BatchingProgressMonitor) compressMonitor).setDelayStart(
1160 					delay,
1161 					TimeUnit.MILLISECONDS);
1162 		}
1163 
1164 		if (needSearchForReuse)
1165 			searchForReuse(compressMonitor);
1166 		if (config.isDeltaCompress())
1167 			searchForDeltas(compressMonitor);
1168 
1169 		crc32 = new CRC32();
1170 		final PackOutputStreamrage/pack/PackOutputStream.html#PackOutputStream">PackOutputStream out = new PackOutputStream(
1171 			writeMonitor,
1172 			isIndexDisabled()
1173 				? packStream
1174 				: new CheckedOutputStream(packStream, crc32),
1175 			this);
1176 
1177 		long objCnt = packfileUriConfig == null ? getObjectCount() :
1178 			getUnoffloadedObjectCount();
1179 		stats.totalObjects = objCnt;
1180 		if (callback != null)
1181 			callback.setObjectCount(objCnt);
1182 		beginPhase(PackingPhase.WRITING, writeMonitor, objCnt);
1183 		long writeStart = System.currentTimeMillis();
1184 		try {
1185 			List<CachedPack> unwrittenCachedPacks;
1186 
1187 			if (packfileUriConfig != null) {
1188 				unwrittenCachedPacks = new ArrayList<>();
1189 				CachedPackUriProvider p = packfileUriConfig.cachedPackUriProvider;
1190 				PacketLineOut o = packfileUriConfig.pckOut;
1191 
1192 				o.writeString("packfile-uris\n"); //$NON-NLS-1$
1193 				for (CachedPack pack : cachedPacks) {
1194 					CachedPackUriProvider.PackInfo packInfo = p.getInfo(
1195 							pack, packfileUriConfig.protocolsSupported);
1196 					if (packInfo != null) {
1197 						o.writeString(packInfo.getHash() + ' ' +
1198 								packInfo.getUri() + '\n');
1199 						stats.offloadedPackfiles += 1;
1200 						stats.offloadedPackfileSize += packInfo.getSize();
1201 					} else {
1202 						unwrittenCachedPacks.add(pack);
1203 					}
1204 				}
1205 				packfileUriConfig.pckOut.writeDelim();
1206 				packfileUriConfig.pckOut.writeString("packfile\n"); //$NON-NLS-1$
1207 			} else {
1208 				unwrittenCachedPacks = cachedPacks;
1209 			}
1210 
1211 			out.writeFileHeader(PACK_VERSION_GENERATED, objCnt);
1212 			out.flush();
1213 
1214 			writeObjects(out);
1215 			if (!edgeObjects.isEmpty() || !cachedPacks.isEmpty()) {
1216 				for (PackStatistics.ObjectType.Accumulator typeStat : stats.objectTypes) {
1217 					if (typeStat == null)
1218 						continue;
1219 					stats.thinPackBytes += typeStat.bytes;
1220 				}
1221 			}
1222 
1223 			stats.reusedPacks = Collections.unmodifiableList(cachedPacks);
1224 			for (CachedPack pack : unwrittenCachedPacks) {
1225 				long deltaCnt = pack.getDeltaCount();
1226 				stats.reusedObjects += pack.getObjectCount();
1227 				stats.reusedDeltas += deltaCnt;
1228 				stats.totalDeltas += deltaCnt;
1229 				reuseSupport.copyPackAsIs(out, pack);
1230 			}
1231 			writeChecksum(out);
1232 			out.flush();
1233 		} finally {
1234 			stats.timeWriting = System.currentTimeMillis() - writeStart;
1235 			stats.depth = depth;
1236 
1237 			for (PackStatistics.ObjectType.Accumulator typeStat : stats.objectTypes) {
1238 				if (typeStat == null)
1239 					continue;
1240 				typeStat.cntDeltas += typeStat.reusedDeltas;
1241 				stats.reusedObjects += typeStat.reusedObjects;
1242 				stats.reusedDeltas += typeStat.reusedDeltas;
1243 				stats.totalDeltas += typeStat.cntDeltas;
1244 			}
1245 		}
1246 
1247 		stats.totalBytes = out.length();
1248 		reader.close();
1249 		endPhase(writeMonitor);
1250 	}
1251 
1252 	/**
1253 	 * Get statistics of what this PackWriter did in order to create the final
1254 	 * pack stream.
1255 	 *
1256 	 * @return description of what this PackWriter did in order to create the
1257 	 *         final pack stream. This should only be invoked after the calls to
1258 	 *         create the pack/index/bitmap have completed.
1259 	 */
1260 	public PackStatistics getStatistics() {
1261 		return new PackStatistics(stats);
1262 	}
1263 
1264 	/**
1265 	 * Get snapshot of the current state of this PackWriter.
1266 	 *
1267 	 * @return snapshot of the current state of this PackWriter.
1268 	 */
1269 	public State getState() {
1270 		return state.snapshot();
1271 	}
1272 
1273 	/**
1274 	 * {@inheritDoc}
1275 	 * <p>
1276 	 * Release all resources used by this writer.
1277 	 */
1278 	@Override
1279 	public void close() {
1280 		reader.close();
1281 		if (myDeflater != null) {
1282 			myDeflater.end();
1283 			myDeflater = null;
1284 		}
1285 		instances.remove(selfRef);
1286 	}
1287 
1288 	private void searchForReuse(ProgressMonitor monitor) throws IOException {
1289 		long cnt = 0;
1290 		cnt += objectsLists[OBJ_COMMIT].size();
1291 		cnt += objectsLists[OBJ_TREE].size();
1292 		cnt += objectsLists[OBJ_BLOB].size();
1293 		cnt += objectsLists[OBJ_TAG].size();
1294 
1295 		long start = System.currentTimeMillis();
1296 		beginPhase(PackingPhase.FINDING_SOURCES, monitor, cnt);
1297 		if (cnt <= 4096) {
1298 			// For small object counts, do everything as one list.
1299 			BlockList<ObjectToPack> tmp = new BlockList<>((int) cnt);
1300 			tmp.addAll(objectsLists[OBJ_TAG]);
1301 			tmp.addAll(objectsLists[OBJ_COMMIT]);
1302 			tmp.addAll(objectsLists[OBJ_TREE]);
1303 			tmp.addAll(objectsLists[OBJ_BLOB]);
1304 			searchForReuse(monitor, tmp);
1305 			if (pruneCurrentObjectList) {
1306 				// If the list was pruned, we need to re-prune the main lists.
1307 				pruneEdgesFromObjectList(objectsLists[OBJ_COMMIT]);
1308 				pruneEdgesFromObjectList(objectsLists[OBJ_TREE]);
1309 				pruneEdgesFromObjectList(objectsLists[OBJ_BLOB]);
1310 				pruneEdgesFromObjectList(objectsLists[OBJ_TAG]);
1311 			}
1312 		} else {
1313 			searchForReuse(monitor, objectsLists[OBJ_TAG]);
1314 			searchForReuse(monitor, objectsLists[OBJ_COMMIT]);
1315 			searchForReuse(monitor, objectsLists[OBJ_TREE]);
1316 			searchForReuse(monitor, objectsLists[OBJ_BLOB]);
1317 		}
1318 		endPhase(monitor);
1319 		stats.timeSearchingForReuse = System.currentTimeMillis() - start;
1320 
1321 		if (config.isReuseDeltas() && config.getCutDeltaChains()) {
1322 			cutDeltaChains(objectsLists[OBJ_TREE]);
1323 			cutDeltaChains(objectsLists[OBJ_BLOB]);
1324 		}
1325 	}
1326 
1327 	private void searchForReuse(ProgressMonitor monitor, List<ObjectToPack> list)
1328 			throws IOException, MissingObjectException {
1329 		pruneCurrentObjectList = false;
1330 		reuseSupport.selectObjectRepresentation(this, monitor, list);
1331 		if (pruneCurrentObjectList)
1332 			pruneEdgesFromObjectList(list);
1333 	}
1334 
1335 	private void cutDeltaChains(BlockList<ObjectToPack> list)
1336 			throws IOException {
1337 		int max = config.getMaxDeltaDepth();
1338 		for (int idx = list.size() - 1; idx >= 0; idx--) {
1339 			int d = 0;
1340 			ObjectToPack b = list.get(idx).getDeltaBase();
1341 			while (b != null) {
1342 				if (d < b.getChainLength())
1343 					break;
1344 				b.setChainLength(++d);
1345 				if (d >= max && b.isDeltaRepresentation()) {
1346 					reselectNonDelta(b);
1347 					break;
1348 				}
1349 				b = b.getDeltaBase();
1350 			}
1351 		}
1352 		if (config.isDeltaCompress()) {
1353 			for (ObjectToPack otp : list)
1354 				otp.clearChainLength();
1355 		}
1356 	}
1357 
1358 	private void searchForDeltas(ProgressMonitor monitor)
1359 			throws MissingObjectException, IncorrectObjectTypeException,
1360 			IOException {
1361 		// Commits and annotated tags tend to have too many differences to
1362 		// really benefit from delta compression. Consequently just don't
1363 		// bother examining those types here.
1364 		//
1365 		ObjectToPack[] list = new ObjectToPack[
1366 				  objectsLists[OBJ_TREE].size()
1367 				+ objectsLists[OBJ_BLOB].size()
1368 				+ edgeObjects.size()];
1369 		int cnt = 0;
1370 		cnt = findObjectsNeedingDelta(list, cnt, OBJ_TREE);
1371 		cnt = findObjectsNeedingDelta(list, cnt, OBJ_BLOB);
1372 		if (cnt == 0)
1373 			return;
1374 		int nonEdgeCnt = cnt;
1375 
1376 		// Queue up any edge objects that we might delta against.  We won't
1377 		// be sending these as we assume the other side has them, but we need
1378 		// them in the search phase below.
1379 		//
1380 		for (ObjectToPack eo : edgeObjects) {
1381 			eo.setWeight(0);
1382 			list[cnt++] = eo;
1383 		}
1384 
1385 		// Compute the sizes of the objects so we can do a proper sort.
1386 		// We let the reader skip missing objects if it chooses. For
1387 		// some readers this can be a huge win. We detect missing objects
1388 		// by having set the weights above to 0 and allowing the delta
1389 		// search code to discover the missing object and skip over it, or
1390 		// abort with an exception if we actually had to have it.
1391 		//
1392 		final long sizingStart = System.currentTimeMillis();
1393 		beginPhase(PackingPhase.GETTING_SIZES, monitor, cnt);
1394 		AsyncObjectSizeQueue<ObjectToPack> sizeQueue = reader.getObjectSize(
1395 				Arrays.<ObjectToPack> asList(list).subList(0, cnt), false);
1396 		try {
1397 			final long limit = Math.min(
1398 					config.getBigFileThreshold(),
1399 					Integer.MAX_VALUE);
1400 			for (;;) {
1401 				try {
1402 					if (!sizeQueue.next())
1403 						break;
1404 				} catch (MissingObjectException notFound) {
1405 					monitor.update(1);
1406 					if (ignoreMissingUninteresting) {
1407 						ObjectToPack otp = sizeQueue.getCurrent();
1408 						if (otp != null && otp.isEdge()) {
1409 							otp.setDoNotDelta();
1410 							continue;
1411 						}
1412 
1413 						otp = objectsMap.get(notFound.getObjectId());
1414 						if (otp != null && otp.isEdge()) {
1415 							otp.setDoNotDelta();
1416 							continue;
1417 						}
1418 					}
1419 					throw notFound;
1420 				}
1421 
1422 				ObjectToPack otp = sizeQueue.getCurrent();
1423 				if (otp == null)
1424 					otp = objectsMap.get(sizeQueue.getObjectId());
1425 
1426 				long sz = sizeQueue.getSize();
1427 				if (DeltaIndex.BLKSZ < sz && sz < limit)
1428 					otp.setWeight((int) sz);
1429 				else
1430 					otp.setDoNotDelta(); // too small, or too big
1431 				monitor.update(1);
1432 			}
1433 		} finally {
1434 			sizeQueue.release();
1435 		}
1436 		endPhase(monitor);
1437 		stats.timeSearchingForSizes = System.currentTimeMillis() - sizingStart;
1438 
1439 		// Sort the objects by path hash so like files are near each other,
1440 		// and then by size descending so that bigger files are first. This
1441 		// applies "Linus' Law" which states that newer files tend to be the
1442 		// bigger ones, because source files grow and hardly ever shrink.
1443 		//
1444 		Arrays.sort(list, 0, cnt, (ObjectToPack"../../../../../../org/eclipse/jgit/internal/storage/pack/ObjectToPack.html#ObjectToPack">ObjectToPack a, ObjectToPack b) -> {
1445 			int cmp = (a.isDoNotDelta() ? 1 : 0) - (b.isDoNotDelta() ? 1 : 0);
1446 			if (cmp != 0) {
1447 				return cmp;
1448 			}
1449 
1450 			cmp = a.getType() - b.getType();
1451 			if (cmp != 0) {
1452 				return cmp;
1453 			}
1454 
1455 			cmp = (a.getPathHash() >>> 1) - (b.getPathHash() >>> 1);
1456 			if (cmp != 0) {
1457 				return cmp;
1458 			}
1459 
1460 			cmp = (a.getPathHash() & 1) - (b.getPathHash() & 1);
1461 			if (cmp != 0) {
1462 				return cmp;
1463 			}
1464 
1465 			cmp = (a.isEdge() ? 0 : 1) - (b.isEdge() ? 0 : 1);
1466 			if (cmp != 0) {
1467 				return cmp;
1468 			}
1469 
1470 			return b.getWeight() - a.getWeight();
1471 		});
1472 
1473 		// Above we stored the objects we cannot delta onto the end.
1474 		// Remove them from the list so we don't waste time on them.
1475 		while (0 < cnt && list[cnt - 1].isDoNotDelta()) {
1476 			if (!list[cnt - 1].isEdge())
1477 				nonEdgeCnt--;
1478 			cnt--;
1479 		}
1480 		if (cnt == 0)
1481 			return;
1482 
1483 		final long searchStart = System.currentTimeMillis();
1484 		searchForDeltas(monitor, list, cnt);
1485 		stats.deltaSearchNonEdgeObjects = nonEdgeCnt;
1486 		stats.timeCompressing = System.currentTimeMillis() - searchStart;
1487 
1488 		for (int i = 0; i < cnt; i++)
1489 			if (!list[i].isEdge() && list[i].isDeltaRepresentation())
1490 				stats.deltasFound++;
1491 	}
1492 
1493 	private int findObjectsNeedingDelta(ObjectToPack[] list, int cnt, int type) {
1494 		for (ObjectToPack otp : objectsLists[type]) {
1495 			if (otp.isDoNotDelta()) // delta is disabled for this path
1496 				continue;
1497 			if (otp.isDeltaRepresentation()) // already reusing a delta
1498 				continue;
1499 			otp.setWeight(0);
1500 			list[cnt++] = otp;
1501 		}
1502 		return cnt;
1503 	}
1504 
1505 	private void reselectNonDelta(ObjectToPack otp) throws IOException {
1506 		otp.clearDeltaBase();
1507 		otp.clearReuseAsIs();
1508 		boolean old = reuseDeltas;
1509 		reuseDeltas = false;
1510 		reuseSupport.selectObjectRepresentation(this,
1511 				NullProgressMonitor.INSTANCE,
1512 				Collections.singleton(otp));
1513 		reuseDeltas = old;
1514 	}
1515 
1516 	private void searchForDeltas(final ProgressMonitor monitor,
1517 			final ObjectToPack[] list, final int cnt)
1518 			throws MissingObjectException, IncorrectObjectTypeException,
1519 			LargeObjectException, IOException {
1520 		int threads = config.getThreads();
1521 		if (threads == 0)
1522 			threads = Runtime.getRuntime().availableProcessors();
1523 		if (threads <= 1 || cnt <= config.getDeltaSearchWindowSize())
1524 			singleThreadDeltaSearch(monitor, list, cnt);
1525 		else
1526 			parallelDeltaSearch(monitor, list, cnt, threads);
1527 	}
1528 
1529 	private void singleThreadDeltaSearch(ProgressMonitor monitor,
1530 			ObjectToPack[] list, int cnt) throws IOException {
1531 		long totalWeight = 0;
1532 		for (int i = 0; i < cnt; i++) {
1533 			ObjectToPack o = list[i];
1534 			totalWeight += DeltaTask.getAdjustedWeight(o);
1535 		}
1536 
1537 		long bytesPerUnit = 1;
1538 		while (DeltaTask.MAX_METER <= (totalWeight / bytesPerUnit))
1539 			bytesPerUnit <<= 10;
1540 		int cost = (int) (totalWeight / bytesPerUnit);
1541 		if (totalWeight % bytesPerUnit != 0)
1542 			cost++;
1543 
1544 		beginPhase(PackingPhase.COMPRESSING, monitor, cost);
1545 		new DeltaWindow(config, new DeltaCache(config), reader,
1546 				monitor, bytesPerUnit,
1547 				list, 0, cnt).search();
1548 		endPhase(monitor);
1549 	}
1550 
1551 	private void parallelDeltaSearch(ProgressMonitor monitor,
1552 			ObjectToPack[] list, int cnt, int threads) throws IOException {
1553 		DeltaCache dc = new ThreadSafeDeltaCache(config);
1554 		ThreadSafeProgressMonitor pm = new ThreadSafeProgressMonitor(monitor);
1555 		DeltaTask.Block taskBlock = new DeltaTask.Block(threads, config,
1556 				reader, dc, pm,
1557 				list, 0, cnt);
1558 		taskBlock.partitionTasks();
1559 		beginPhase(PackingPhase.COMPRESSING, monitor, taskBlock.cost());
1560 		pm.startWorkers(taskBlock.tasks.size());
1561 
1562 		Executor executor = config.getExecutor();
1563 		final List<Throwable> errors =
1564 				Collections.synchronizedList(new ArrayList<>(threads));
1565 		if (executor instanceof ExecutorService) {
1566 			// Caller supplied us a service, use it directly.
1567 			runTasks((ExecutorService) executor, pm, taskBlock, errors);
1568 		} else if (executor == null) {
1569 			// Caller didn't give us a way to run the tasks, spawn up a
1570 			// temporary thread pool and make sure it tears down cleanly.
1571 			ExecutorService pool = Executors.newFixedThreadPool(threads);
1572 			try {
1573 				runTasks(pool, pm, taskBlock, errors);
1574 			} finally {
1575 				pool.shutdown();
1576 				for (;;) {
1577 					try {
1578 						if (pool.awaitTermination(60, TimeUnit.SECONDS))
1579 							break;
1580 					} catch (InterruptedException e) {
1581 						throw new IOException(JGitText
1582 								.get().packingCancelledDuringObjectsWriting, e);
1583 					}
1584 				}
1585 			}
1586 		} else {
1587 			// The caller gave us an executor, but it might not do
1588 			// asynchronous execution.  Wrap everything and hope it
1589 			// can schedule these for us.
1590 			for (DeltaTask task : taskBlock.tasks) {
1591 				executor.execute(() -> {
1592 					try {
1593 						task.call();
1594 					} catch (Throwable failure) {
1595 						errors.add(failure);
1596 					}
1597 				});
1598 			}
1599 			try {
1600 				pm.waitForCompletion();
1601 			} catch (InterruptedException ie) {
1602 				// We can't abort the other tasks as we have no handle.
1603 				// Cross our fingers and just break out anyway.
1604 				//
1605 				throw new IOException(
1606 						JGitText.get().packingCancelledDuringObjectsWriting,
1607 						ie);
1608 			}
1609 		}
1610 
1611 		// If any task threw an error, try to report it back as
1612 		// though we weren't using a threaded search algorithm.
1613 		//
1614 		if (!errors.isEmpty()) {
1615 			Throwable err = errors.get(0);
1616 			if (err instanceof Error)
1617 				throw (Error) err;
1618 			if (err instanceof RuntimeException)
1619 				throw (RuntimeException) err;
1620 			if (err instanceof IOException)
1621 				throw (IOException) err;
1622 
1623 			throw new IOException(err.getMessage(), err);
1624 		}
1625 		endPhase(monitor);
1626 	}
1627 
1628 	private static void runTasks(ExecutorService pool,
1629 			ThreadSafeProgressMonitor pm,
1630 			DeltaTask.Block tb, List<Throwable> errors) throws IOException {
1631 		List<Future<?>> futures = new ArrayList<>(tb.tasks.size());
1632 		for (DeltaTask task : tb.tasks)
1633 			futures.add(pool.submit(task));
1634 
1635 		try {
1636 			pm.waitForCompletion();
1637 			for (Future<?> f : futures) {
1638 				try {
1639 					f.get();
1640 				} catch (ExecutionException failed) {
1641 					errors.add(failed.getCause());
1642 				}
1643 			}
1644 		} catch (InterruptedException ie) {
1645 			for (Future<?> f : futures)
1646 				f.cancel(true);
1647 			throw new IOException(
1648 					JGitText.get().packingCancelledDuringObjectsWriting, ie);
1649 		}
1650 	}
1651 
1652 	private void writeObjects(PackOutputStream out) throws IOException {
1653 		writeObjects(out, objectsLists[OBJ_COMMIT]);
1654 		writeObjects(out, objectsLists[OBJ_TAG]);
1655 		writeObjects(out, objectsLists[OBJ_TREE]);
1656 		writeObjects(out, objectsLists[OBJ_BLOB]);
1657 	}
1658 
1659 	private void writeObjects(PackOutputStream out, List<ObjectToPack> list)
1660 			throws IOException {
1661 		if (list.isEmpty())
1662 			return;
1663 
1664 		typeStats = stats.objectTypes[list.get(0).getType()];
1665 		long beginOffset = out.length();
1666 
1667 		if (reuseSupport != null) {
1668 			reuseSupport.writeObjects(out, list);
1669 		} else {
1670 			for (ObjectToPack otp : list)
1671 				out.writeObject(otp);
1672 		}
1673 
1674 		typeStats.bytes += out.length() - beginOffset;
1675 		typeStats.cntObjects = list.size();
1676 	}
1677 
1678 	void writeObject(PackOutputStream out, ObjectToPack otp) throws IOException {
1679 		if (!otp.isWritten())
1680 			writeObjectImpl(out, otp);
1681 	}
1682 
1683 	private void writeObjectImpl(PackOutputStream out, ObjectToPack otp)
1684 			throws IOException {
1685 		if (otp.wantWrite()) {
1686 			// A cycle exists in this delta chain. This should only occur if a
1687 			// selected object representation disappeared during writing
1688 			// (for example due to a concurrent repack) and a different base
1689 			// was chosen, forcing a cycle. Select something other than a
1690 			// delta, and write this object.
1691 			reselectNonDelta(otp);
1692 		}
1693 		otp.markWantWrite();
1694 
1695 		while (otp.isReuseAsIs()) {
1696 			writeBase(out, otp.getDeltaBase());
1697 			if (otp.isWritten())
1698 				return; // Delta chain cycle caused this to write already.
1699 
1700 			crc32.reset();
1701 			otp.setOffset(out.length());
1702 			try {
1703 				reuseSupport.copyObjectAsIs(out, otp, reuseValidate);
1704 				out.endObject();
1705 				otp.setCRC((int) crc32.getValue());
1706 				typeStats.reusedObjects++;
1707 				if (otp.isDeltaRepresentation()) {
1708 					typeStats.reusedDeltas++;
1709 					typeStats.deltaBytes += out.length() - otp.getOffset();
1710 				}
1711 				return;
1712 			} catch (StoredObjectRepresentationNotAvailableException gone) {
1713 				if (otp.getOffset() == out.length()) {
1714 					otp.setOffset(0);
1715 					otp.clearDeltaBase();
1716 					otp.clearReuseAsIs();
1717 					reuseSupport.selectObjectRepresentation(this,
1718 							NullProgressMonitor.INSTANCE,
1719 							Collections.singleton(otp));
1720 					continue;
1721 				}
1722 				// Object writing already started, we cannot recover.
1723 				//
1724 				CorruptObjectException coe;
1725 				coe = new CorruptObjectException(otp, ""); //$NON-NLS-1$
1726 				coe.initCause(gone);
1727 				throw coe;
1728 			}
1729 		}
1730 
1731 		// If we reached here, reuse wasn't possible.
1732 		//
1733 		if (otp.isDeltaRepresentation()) {
1734 			writeDeltaObjectDeflate(out, otp);
1735 		} else {
1736 			writeWholeObjectDeflate(out, otp);
1737 		}
1738 		out.endObject();
1739 		otp.setCRC((int) crc32.getValue());
1740 	}
1741 
1742 	private void writeBase(PackOutputStream out, ObjectToPack base)
1743 			throws IOException {
1744 		if (base != null && !base.isWritten() && !base.isEdge())
1745 			writeObjectImpl(out, base);
1746 	}
1747 
1748 	private void writeWholeObjectDeflate(PackOutputStream out,
1749 			final ObjectToPack otp) throws IOException {
1750 		final Deflater deflater = deflater();
1751 		final ObjectLoader ldr = reader.open(otp, otp.getType());
1752 
1753 		crc32.reset();
1754 		otp.setOffset(out.length());
1755 		out.writeHeader(otp, ldr.getSize());
1756 
1757 		deflater.reset();
1758 		DeflaterOutputStream dst = new DeflaterOutputStream(out, deflater);
1759 		ldr.copyTo(dst);
1760 		dst.finish();
1761 	}
1762 
1763 	private void writeDeltaObjectDeflate(PackOutputStream out,
1764 			final ObjectToPack otp) throws IOException {
1765 		writeBase(out, otp.getDeltaBase());
1766 
1767 		crc32.reset();
1768 		otp.setOffset(out.length());
1769 
1770 		DeltaCache.Ref ref = otp.popCachedDelta();
1771 		if (ref != null) {
1772 			byte[] zbuf = ref.get();
1773 			if (zbuf != null) {
1774 				out.writeHeader(otp, otp.getCachedSize());
1775 				out.write(zbuf);
1776 				typeStats.cntDeltas++;
1777 				typeStats.deltaBytes += out.length() - otp.getOffset();
1778 				return;
1779 			}
1780 		}
1781 
1782 		try (TemporaryBuffer.Heap delta = delta(otp)) {
1783 			out.writeHeader(otp, delta.length());
1784 
1785 			Deflater deflater = deflater();
1786 			deflater.reset();
1787 			DeflaterOutputStream dst = new DeflaterOutputStream(out, deflater);
1788 			delta.writeTo(dst, null);
1789 			dst.finish();
1790 		}
1791 		typeStats.cntDeltas++;
1792 		typeStats.deltaBytes += out.length() - otp.getOffset();
1793 	}
1794 
1795 	private TemporaryBuffer.Heap delta(ObjectToPack otp)
1796 			throws IOException {
1797 		DeltaIndex index = new DeltaIndex(buffer(otp.getDeltaBaseId()));
1798 		byte[] res = buffer(otp);
1799 
1800 		// We never would have proposed this pair if the delta would be
1801 		// larger than the unpacked version of the object. So using it
1802 		// as our buffer limit is valid: we will never reach it.
1803 		//
1804 		TemporaryBuffer.Heap delta = new TemporaryBuffer.Heap(res.length);
1805 		index.encode(delta, res);
1806 		return delta;
1807 	}
1808 
1809 	private byte[] buffer(AnyObjectId objId) throws IOException {
1810 		return buffer(config, reader, objId);
1811 	}
1812 
1813 	static byte[] buffer(PackConfig config, ObjectReader or, AnyObjectId objId)
1814 			throws IOException {
1815 		// PackWriter should have already pruned objects that
1816 		// are above the big file threshold, so our chances of
1817 		// the object being below it are very good. We really
1818 		// shouldn't be here, unless the implementation is odd.
1819 
1820 		return or.open(objId).getCachedBytes(config.getBigFileThreshold());
1821 	}
1822 
1823 	private Deflater deflater() {
1824 		if (myDeflater == null)
1825 			myDeflater = new Deflater(config.getCompressionLevel());
1826 		return myDeflater;
1827 	}
1828 
1829 	private void writeChecksum(PackOutputStream out) throws IOException {
1830 		packcsum = out.getDigest();
1831 		out.write(packcsum);
1832 	}
1833 
1834 	private void findObjectsToPack(@NonNull ProgressMonitor countingMonitor,
1835 			@NonNull ObjectWalk walker, @NonNull Set<? extends ObjectId> want,
1836 			@NonNull Set<? extends ObjectId> have,
1837 			@NonNull Set<? extends ObjectId> noBitmaps) throws IOException {
1838 		final long countingStart = System.currentTimeMillis();
1839 		beginPhase(PackingPhase.COUNTING, countingMonitor, ProgressMonitor.UNKNOWN);
1840 
1841 		stats.interestingObjects = Collections.unmodifiableSet(new HashSet<ObjectId>(want));
1842 		stats.uninterestingObjects = Collections.unmodifiableSet(new HashSet<ObjectId>(have));
1843 		excludeFromBitmapSelection = noBitmaps;
1844 
1845 		canBuildBitmaps = config.isBuildBitmaps()
1846 				&& !shallowPack
1847 				&& have.isEmpty()
1848 				&& (excludeInPacks == null || excludeInPacks.length == 0);
1849 		if (!shallowPack && useBitmaps) {
1850 			BitmapIndex bitmapIndex = reader.getBitmapIndex();
1851 			if (bitmapIndex != null) {
1852 				BitmapWalker bitmapWalker = new BitmapWalker(
1853 						walker, bitmapIndex, countingMonitor);
1854 				findObjectsToPackUsingBitmaps(bitmapWalker, want, have);
1855 				endPhase(countingMonitor);
1856 				stats.timeCounting = System.currentTimeMillis() - countingStart;
1857 				stats.bitmapIndexMisses = bitmapWalker.getCountOfBitmapIndexMisses();
1858 				return;
1859 			}
1860 		}
1861 
1862 		List<ObjectId> all = new ArrayList<>(want.size() + have.size());
1863 		all.addAll(want);
1864 		all.addAll(have);
1865 
1866 		final RevFlag include = walker.newFlag("include"); //$NON-NLS-1$
1867 		final RevFlag added = walker.newFlag("added"); //$NON-NLS-1$
1868 
1869 		walker.carry(include);
1870 
1871 		int haveEst = have.size();
1872 		if (have.isEmpty()) {
1873 			walker.sort(RevSort.COMMIT_TIME_DESC);
1874 		} else {
1875 			walker.sort(RevSort.TOPO);
1876 			if (thin)
1877 				walker.sort(RevSort.BOUNDARY, true);
1878 		}
1879 
1880 		List<RevObject> wantObjs = new ArrayList<>(want.size());
1881 		List<RevObject> haveObjs = new ArrayList<>(haveEst);
1882 		List<RevTag> wantTags = new ArrayList<>(want.size());
1883 
1884 		// Retrieve the RevWalk's versions of "want" and "have" objects to
1885 		// maintain any state previously set in the RevWalk.
1886 		AsyncRevObjectQueue q = walker.parseAny(all, true);
1887 		try {
1888 			for (;;) {
1889 				try {
1890 					RevObject o = q.next();
1891 					if (o == null)
1892 						break;
1893 					if (have.contains(o))
1894 						haveObjs.add(o);
1895 					if (want.contains(o)) {
1896 						o.add(include);
1897 						wantObjs.add(o);
1898 						if (o instanceof RevTag)
1899 							wantTags.add((RevTag) o);
1900 					}
1901 				} catch (MissingObjectException e) {
1902 					if (ignoreMissingUninteresting
1903 							&& have.contains(e.getObjectId()))
1904 						continue;
1905 					throw e;
1906 				}
1907 			}
1908 		} finally {
1909 			q.release();
1910 		}
1911 
1912 		if (!wantTags.isEmpty()) {
1913 			all = new ArrayList<>(wantTags.size());
1914 			for (RevTag tag : wantTags)
1915 				all.add(tag.getObject());
1916 			q = walker.parseAny(all, true);
1917 			try {
1918 				while (q.next() != null) {
1919 					// Just need to pop the queue item to parse the object.
1920 				}
1921 			} finally {
1922 				q.release();
1923 			}
1924 		}
1925 
1926 		if (walker instanceof DepthWalk.ObjectWalk) {
1927 			DepthWalk.ObjectWalk depthWalk = (DepthWalk.ObjectWalk) walker;
1928 			for (RevObject obj : wantObjs) {
1929 				depthWalk.markRoot(obj);
1930 			}
1931 			// Mark the tree objects associated with "have" commits as
1932 			// uninteresting to avoid writing redundant blobs. A normal RevWalk
1933 			// lazily propagates the "uninteresting" state from a commit to its
1934 			// tree during the walk, but DepthWalks can terminate early so
1935 			// preemptively propagate that state here.
1936 			for (RevObject obj : haveObjs) {
1937 				if (obj instanceof RevCommit) {
1938 					RevTree t = ((RevCommit) obj).getTree();
1939 					depthWalk.markUninteresting(t);
1940 				}
1941 			}
1942 
1943 			if (unshallowObjects != null) {
1944 				for (ObjectId id : unshallowObjects) {
1945 					depthWalk.markUnshallow(walker.parseAny(id));
1946 				}
1947 			}
1948 		} else {
1949 			for (RevObject obj : wantObjs)
1950 				walker.markStart(obj);
1951 		}
1952 		for (RevObject obj : haveObjs)
1953 			walker.markUninteresting(obj);
1954 
1955 		final int maxBases = config.getDeltaSearchWindowSize();
1956 		Set<RevTree> baseTrees = new HashSet<>();
1957 		BlockList<RevCommit> commits = new BlockList<>();
1958 		Set<ObjectId> roots = new HashSet<>();
1959 		RevCommit c;
1960 		while ((c = walker.next()) != null) {
1961 			if (exclude(c))
1962 				continue;
1963 			if (c.has(RevFlag.UNINTERESTING)) {
1964 				if (baseTrees.size() <= maxBases)
1965 					baseTrees.add(c.getTree());
1966 				continue;
1967 			}
1968 
1969 			commits.add(c);
1970 			if (c.getParentCount() == 0) {
1971 				roots.add(c.copy());
1972 			}
1973 			countingMonitor.update(1);
1974 		}
1975 		stats.rootCommits = Collections.unmodifiableSet(roots);
1976 
1977 		if (shallowPack) {
1978 			for (RevCommit cmit : commits) {
1979 				addObject(cmit, 0);
1980 			}
1981 		} else {
1982 			int commitCnt = 0;
1983 			boolean putTagTargets = false;
1984 			for (RevCommit cmit : commits) {
1985 				if (!cmit.has(added)) {
1986 					cmit.add(added);
1987 					addObject(cmit, 0);
1988 					commitCnt++;
1989 				}
1990 
1991 				for (int i = 0; i < cmit.getParentCount(); i++) {
1992 					RevCommit p = cmit.getParent(i);
1993 					if (!p.has(added) && !p.has(RevFlag.UNINTERESTING)
1994 							&& !exclude(p)) {
1995 						p.add(added);
1996 						addObject(p, 0);
1997 						commitCnt++;
1998 					}
1999 				}
2000 
2001 				if (!putTagTargets && 4096 < commitCnt) {
2002 					for (ObjectId id : tagTargets) {
2003 						RevObject obj = walker.lookupOrNull(id);
2004 						if (obj instanceof RevCommit
2005 								&& obj.has(include)
2006 								&& !obj.has(RevFlag.UNINTERESTING)
2007 								&& !obj.has(added)) {
2008 							obj.add(added);
2009 							addObject(obj, 0);
2010 						}
2011 					}
2012 					putTagTargets = true;
2013 				}
2014 			}
2015 		}
2016 		commits = null;
2017 
2018 		if (thin && !baseTrees.isEmpty()) {
2019 			BaseSearch bases = new BaseSearch(countingMonitor, baseTrees, //
2020 					objectsMap, edgeObjects, reader);
2021 			RevObject o;
2022 			while ((o = walker.nextObject()) != null) {
2023 				if (o.has(RevFlag.UNINTERESTING))
2024 					continue;
2025 				if (exclude(o))
2026 					continue;
2027 
2028 				int pathHash = walker.getPathHashCode();
2029 				byte[] pathBuf = walker.getPathBuffer();
2030 				int pathLen = walker.getPathLength();
2031 				bases.addBase(o.getType(), pathBuf, pathLen, pathHash);
2032 				if (!depthSkip(o, walker)) {
2033 					filterAndAddObject(o, o.getType(), pathHash, want);
2034 				}
2035 				countingMonitor.update(1);
2036 			}
2037 		} else {
2038 			RevObject o;
2039 			while ((o = walker.nextObject()) != null) {
2040 				if (o.has(RevFlag.UNINTERESTING))
2041 					continue;
2042 				if (exclude(o))
2043 					continue;
2044 				if (!depthSkip(o, walker)) {
2045 					filterAndAddObject(o, o.getType(), walker.getPathHashCode(),
2046 									   want);
2047 				}
2048 				countingMonitor.update(1);
2049 			}
2050 		}
2051 
2052 		for (CachedPack pack : cachedPacks)
2053 			countingMonitor.update((int) pack.getObjectCount());
2054 		endPhase(countingMonitor);
2055 		stats.timeCounting = System.currentTimeMillis() - countingStart;
2056 		stats.bitmapIndexMisses = -1;
2057 	}
2058 
2059 	private void findObjectsToPackUsingBitmaps(
2060 			BitmapWalker bitmapWalker, Set<? extends ObjectId> want,
2061 			Set<? extends ObjectId> have)
2062 			throws MissingObjectException, IncorrectObjectTypeException,
2063 			IOException {
2064 		BitmapBuilder haveBitmap = bitmapWalker.findObjects(have, null, true);
2065 		BitmapBuilder wantBitmap = bitmapWalker.findObjects(want, haveBitmap,
2066 				false);
2067 		BitmapBuilder needBitmap = wantBitmap.andNot(haveBitmap);
2068 
2069 		if (useCachedPacks && reuseSupport != null && !reuseValidate
2070 				&& (excludeInPacks == null || excludeInPacks.length == 0))
2071 			cachedPacks.addAll(
2072 					reuseSupport.getCachedPacksAndUpdate(needBitmap));
2073 
2074 		for (BitmapObject obj : needBitmap) {
2075 			ObjectId objectId = obj.getObjectId();
2076 			if (exclude(objectId)) {
2077 				needBitmap.remove(objectId);
2078 				continue;
2079 			}
2080 			filterAndAddObject(objectId, obj.getType(), 0, want);
2081 		}
2082 
2083 		if (thin)
2084 			haveObjects = haveBitmap;
2085 	}
2086 
2087 	private static void pruneEdgesFromObjectList(List<ObjectToPack> list) {
2088 		final int size = list.size();
2089 		int src = 0;
2090 		int dst = 0;
2091 
2092 		for (; src < size; src++) {
2093 			ObjectToPack obj = list.get(src);
2094 			if (obj.isEdge())
2095 				continue;
2096 			if (dst != src)
2097 				list.set(dst, obj);
2098 			dst++;
2099 		}
2100 
2101 		while (dst < list.size())
2102 			list.remove(list.size() - 1);
2103 	}
2104 
2105 	/**
2106 	 * Include one object to the output file.
2107 	 * <p>
2108 	 * Objects are written in the order they are added. If the same object is
2109 	 * added twice, it may be written twice, creating a larger than necessary
2110 	 * file.
2111 	 *
2112 	 * @param object
2113 	 *            the object to add.
2114 	 * @throws org.eclipse.jgit.errors.IncorrectObjectTypeException
2115 	 *             the object is an unsupported type.
2116 	 */
2117 	public void addObject(RevObject object)
2118 			throws IncorrectObjectTypeException {
2119 		if (!exclude(object))
2120 			addObject(object, 0);
2121 	}
2122 
2123 	private void addObject(RevObject object, int pathHashCode) {
2124 		addObject(object, object.getType(), pathHashCode);
2125 	}
2126 
2127 	private void addObject(
2128 			final AnyObjectId src, final int type, final int pathHashCode) {
2129 		final ObjectToPack otp;
2130 		if (reuseSupport != null)
2131 			otp = reuseSupport.newObjectToPack(src, type);
2132 		else
2133 			otp = new ObjectToPack(src, type);
2134 		otp.setPathHash(pathHashCode);
2135 		objectsLists[type].add(otp);
2136 		objectsMap.add(otp);
2137 	}
2138 
2139 	/**
2140 	 * Determines if the object should be omitted from the pack as a result of
2141 	 * its depth (probably because of the tree:<depth> filter).
2142 	 * <p>
2143 	 * Causes {@code walker} to skip traversing the current tree, which ought to
2144 	 * have just started traversal, assuming this method is called as soon as a
2145 	 * new depth is reached.
2146 	 * <p>
2147 	 * This method increments the {@code treesTraversed} statistic.
2148 	 *
2149 	 * @param obj
2150 	 *            the object to check whether it should be omitted.
2151 	 * @param walker
2152 	 *            the walker being used for traveresal.
2153 	 * @return whether the given object should be skipped.
2154 	 */
2155 	private boolean depthSkip(@NonNull RevObject obj, ObjectWalk walker) {
2156 		long treeDepth = walker.getTreeDepth();
2157 
2158 		// Check if this object needs to be rejected because it is a tree or
2159 		// blob that is too deep from the root tree.
2160 
2161 		// A blob is considered one level deeper than the tree that contains it.
2162 		if (obj.getType() == OBJ_BLOB) {
2163 			treeDepth++;
2164 		} else {
2165 			stats.treesTraversed++;
2166 		}
2167 
2168 		if (filterSpec.getTreeDepthLimit() < 0 ||
2169 			treeDepth <= filterSpec.getTreeDepthLimit()) {
2170 			return false;
2171 		}
2172 
2173 		walker.skipTree();
2174 		return true;
2175 	}
2176 
2177 	// Adds the given object as an object to be packed, first performing
2178 	// filtering on blobs at or exceeding a given size.
2179 	private void filterAndAddObject(@NonNull AnyObjectId src, int type,
2180 			int pathHashCode, @NonNull Set<? extends AnyObjectId> want)
2181 			throws IOException {
2182 
2183 		// Check if this object needs to be rejected, doing the cheaper
2184 		// checks first.
2185 		boolean reject = filterSpec.getBlobLimit() >= 0 &&
2186 			type == OBJ_BLOB &&
2187 			!want.contains(src) &&
2188 			reader.getObjectSize(src, OBJ_BLOB) > filterSpec.getBlobLimit();
2189 		if (!reject) {
2190 			addObject(src, type, pathHashCode);
2191 		}
2192 	}
2193 
2194 	private boolean exclude(AnyObjectId objectId) {
2195 		if (excludeInPacks == null)
2196 			return false;
2197 		if (excludeInPackLast.contains(objectId))
2198 			return true;
2199 		for (ObjectIdSet idx : excludeInPacks) {
2200 			if (idx.contains(objectId)) {
2201 				excludeInPackLast = idx;
2202 				return true;
2203 			}
2204 		}
2205 		return false;
2206 	}
2207 
2208 	/**
2209 	 * Select an object representation for this writer.
2210 	 * <p>
2211 	 * An {@link org.eclipse.jgit.lib.ObjectReader} implementation should invoke
2212 	 * this method once for each representation available for an object, to
2213 	 * allow the writer to find the most suitable one for the output.
2214 	 *
2215 	 * @param otp
2216 	 *            the object being packed.
2217 	 * @param next
2218 	 *            the next available representation from the repository.
2219 	 */
2220 	public void select(ObjectToPack otp, StoredObjectRepresentation next) {
2221 		int nFmt = next.getFormat();
2222 
2223 		if (!cachedPacks.isEmpty()) {
2224 			if (otp.isEdge())
2225 				return;
2226 			if (nFmt == PACK_WHOLE || nFmt == PACK_DELTA) {
2227 				for (CachedPack pack : cachedPacks) {
2228 					if (pack.hasObject(otp, next)) {
2229 						otp.setEdge();
2230 						otp.clearDeltaBase();
2231 						otp.clearReuseAsIs();
2232 						pruneCurrentObjectList = true;
2233 						return;
2234 					}
2235 				}
2236 			}
2237 		}
2238 
2239 		if (nFmt == PACK_DELTA && reuseDeltas && reuseDeltaFor(otp)) {
2240 			ObjectId baseId = next.getDeltaBase();
2241 			ObjectToPack ptr = objectsMap.get(baseId);
2242 			if (ptr != null && !ptr.isEdge()) {
2243 				otp.setDeltaBase(ptr);
2244 				otp.setReuseAsIs();
2245 			} else if (thin && have(ptr, baseId)) {
2246 				otp.setDeltaBase(baseId);
2247 				otp.setReuseAsIs();
2248 			} else {
2249 				otp.clearDeltaBase();
2250 				otp.clearReuseAsIs();
2251 			}
2252 		} else if (nFmt == PACK_WHOLE && config.isReuseObjects()) {
2253 			int nWeight = next.getWeight();
2254 			if (otp.isReuseAsIs() && !otp.isDeltaRepresentation()) {
2255 				// We've chosen another PACK_WHOLE format for this object,
2256 				// choose the one that has the smaller compressed size.
2257 				//
2258 				if (otp.getWeight() <= nWeight)
2259 					return;
2260 			}
2261 			otp.clearDeltaBase();
2262 			otp.setReuseAsIs();
2263 			otp.setWeight(nWeight);
2264 		} else {
2265 			otp.clearDeltaBase();
2266 			otp.clearReuseAsIs();
2267 		}
2268 
2269 		otp.setDeltaAttempted(reuseDeltas && next.wasDeltaAttempted());
2270 		otp.select(next);
2271 	}
2272 
2273 	private final boolean have(ObjectToPack ptr, AnyObjectId objectId) {
2274 		return (ptr != null && ptr.isEdge())
2275 				|| (haveObjects != null && haveObjects.contains(objectId));
2276 	}
2277 
2278 	/**
2279 	 * Prepares the bitmaps to be written to the bitmap index file.
2280 	 * <p>
2281 	 * Bitmaps can be used to speed up fetches and clones by storing the entire
2282 	 * object graph at selected commits. Writing a bitmap index is an optional
2283 	 * feature that not all pack users may require.
2284 	 * <p>
2285 	 * Called after {@link #writeIndex(OutputStream)}.
2286 	 * <p>
2287 	 * To reduce memory internal state is cleared during this method, rendering
2288 	 * the PackWriter instance useless for anything further than a call to write
2289 	 * out the new bitmaps with {@link #writeBitmapIndex(OutputStream)}.
2290 	 *
2291 	 * @param pm
2292 	 *            progress monitor to report bitmap building work.
2293 	 * @return whether a bitmap index may be written.
2294 	 * @throws java.io.IOException
2295 	 *             when some I/O problem occur during reading objects.
2296 	 */
2297 	public boolean prepareBitmapIndex(ProgressMonitor pm) throws IOException {
2298 		if (!canBuildBitmaps || getObjectCount() > Integer.MAX_VALUE
2299 				|| !cachedPacks.isEmpty())
2300 			return false;
2301 
2302 		if (pm == null)
2303 			pm = NullProgressMonitor.INSTANCE;
2304 
2305 		int numCommits = objectsLists[OBJ_COMMIT].size();
2306 		List<ObjectToPack> byName = sortByName();
2307 		sortedByName = null;
2308 		objectsLists = null;
2309 		objectsMap = null;
2310 		writeBitmaps = new PackBitmapIndexBuilder(byName);
2311 		byName = null;
2312 
2313 		PackWriterBitmapPreparer bitmapPreparer = new PackWriterBitmapPreparer(
2314 				reader, writeBitmaps, pm, stats.interestingObjects, config);
2315 
2316 		Collection<PackWriterBitmapPreparer.BitmapCommit> selectedCommits = bitmapPreparer
2317 				.selectCommits(numCommits, excludeFromBitmapSelection);
2318 
2319 		beginPhase(PackingPhase.BUILDING_BITMAPS, pm, selectedCommits.size());
2320 
2321 		BitmapWalker walker = bitmapPreparer.newBitmapWalker();
2322 		AnyObjectId last = null;
2323 		for (PackWriterBitmapPreparer.BitmapCommit cmit : selectedCommits) {
2324 			if (!cmit.isReuseWalker()) {
2325 				walker = bitmapPreparer.newBitmapWalker();
2326 			}
2327 			BitmapBuilder bitmap = walker.findObjects(
2328 					Collections.singleton(cmit), null, false);
2329 
2330 			if (last != null && cmit.isReuseWalker() && !bitmap.contains(last))
2331 				throw new IllegalStateException(MessageFormat.format(
2332 						JGitText.get().bitmapMissingObject, cmit.name(),
2333 						last.name()));
2334 			last = cmit;
2335 			writeBitmaps.addBitmap(cmit, bitmap.build(), cmit.getFlags());
2336 
2337 			pm.update(1);
2338 		}
2339 
2340 		endPhase(pm);
2341 		return true;
2342 	}
2343 
2344 	private boolean reuseDeltaFor(ObjectToPack otp) {
2345 		int type = otp.getType();
2346 		if ((type & 2) != 0) // OBJ_TREE(2) or OBJ_BLOB(3)
2347 			return true;
2348 		if (type == OBJ_COMMIT)
2349 			return reuseDeltaCommits;
2350 		if (type == OBJ_TAG)
2351 			return false;
2352 		return true;
2353 	}
2354 
2355 	private class MutableState {
2356 		/** Estimated size of a single ObjectToPack instance. */
2357 		// Assume 64-bit pointers, since this is just an estimate.
2358 		private static final long OBJECT_TO_PACK_SIZE =
2359 				(2 * 8)               // Object header
2360 				+ (2 * 8) + (2 * 8)   // ObjectToPack fields
2361 				+ (8 + 8)             // PackedObjectInfo fields
2362 				+ 8                   // ObjectIdOwnerMap fields
2363 				+ 40                  // AnyObjectId fields
2364 				+ 8;                  // Reference in BlockList
2365 
2366 		private final long totalDeltaSearchBytes;
2367 
2368 		private volatile PackingPhase phase;
2369 
2370 		MutableState() {
2371 			phase = PackingPhase.COUNTING;
2372 			if (config.isDeltaCompress()) {
2373 				int threads = config.getThreads();
2374 				if (threads <= 0)
2375 					threads = Runtime.getRuntime().availableProcessors();
2376 				totalDeltaSearchBytes = (threads * config.getDeltaSearchMemoryLimit())
2377 						+ config.getBigFileThreshold();
2378 			} else
2379 				totalDeltaSearchBytes = 0;
2380 		}
2381 
2382 		State snapshot() {
2383 			long objCnt = 0;
2384 			BlockList<ObjectToPack>[] lists = objectsLists;
2385 			if (lists != null) {
2386 				objCnt += lists[OBJ_COMMIT].size();
2387 				objCnt += lists[OBJ_TREE].size();
2388 				objCnt += lists[OBJ_BLOB].size();
2389 				objCnt += lists[OBJ_TAG].size();
2390 				// Exclude CachedPacks.
2391 			}
2392 
2393 			long bytesUsed = OBJECT_TO_PACK_SIZE * objCnt;
2394 			PackingPhase curr = phase;
2395 			if (curr == PackingPhase.COMPRESSING)
2396 				bytesUsed += totalDeltaSearchBytes;
2397 			return new State(curr, bytesUsed);
2398 		}
2399 	}
2400 
2401 	/** Possible states that a PackWriter can be in. */
2402 	public enum PackingPhase {
2403 		/** Counting objects phase. */
2404 		COUNTING,
2405 
2406 		/** Getting sizes phase. */
2407 		GETTING_SIZES,
2408 
2409 		/** Finding sources phase. */
2410 		FINDING_SOURCES,
2411 
2412 		/** Compressing objects phase. */
2413 		COMPRESSING,
2414 
2415 		/** Writing objects phase. */
2416 		WRITING,
2417 
2418 		/** Building bitmaps phase. */
2419 		BUILDING_BITMAPS;
2420 	}
2421 
2422 	/** Summary of the current state of a PackWriter. */
2423 	public class State {
2424 		private final PackingPhase phase;
2425 
2426 		private final long bytesUsed;
2427 
2428 		State(PackingPhase phase, long bytesUsed) {
2429 			this.phase = phase;
2430 			this.bytesUsed = bytesUsed;
2431 		}
2432 
2433 		/** @return the PackConfig used to build the writer. */
2434 		public PackConfig getConfig() {
2435 			return config;
2436 		}
2437 
2438 		/** @return the current phase of the writer. */
2439 		public PackingPhase getPhase() {
2440 			return phase;
2441 		}
2442 
2443 		/** @return an estimate of the total memory used by the writer. */
2444 		public long estimateBytesUsed() {
2445 			return bytesUsed;
2446 		}
2447 
2448 		@SuppressWarnings("nls")
2449 		@Override
2450 		public String toString() {
2451 			return "PackWriter.State[" + phase + ", memory=" + bytesUsed + "]";
2452 		}
2453 	}
2454 
2455 	/**
2456 	 * Configuration related to the packfile URI feature.
2457 	 *
2458 	 * @since 5.5
2459 	 */
2460 	public static class PackfileUriConfig {
2461 		@NonNull
2462 		private final PacketLineOut pckOut;
2463 
2464 		@NonNull
2465 		private final Collection<String> protocolsSupported;
2466 
2467 		@NonNull
2468 		private final CachedPackUriProvider cachedPackUriProvider;
2469 
2470 		/**
2471 		 * @param pckOut where to write "packfile-uri" lines to (should
2472 		 *     output to the same stream as the one passed to
2473 		 *     PackWriter#writePack)
2474 		 * @param protocolsSupported list of protocols supported (e.g. "https")
2475 		 * @param cachedPackUriProvider provider of URIs corresponding
2476 		 *     to cached packs
2477 		 * @since 5.5
2478 		 */
2479 		public PackfileUriConfig(@NonNull PacketLineOut pckOut,
2480 				@NonNull Collection<String> protocolsSupported,
2481 				@NonNull CachedPackUriProvider cachedPackUriProvider) {
2482 			this.pckOut = pckOut;
2483 			this.protocolsSupported = protocolsSupported;
2484 			this.cachedPackUriProvider = cachedPackUriProvider;
2485 		}
2486 	}
2487 }