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

PackWriter.java 76KB

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