You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PackWriter.java 76KB

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