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

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