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 75KB

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