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

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