選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

PackWriter.java 75KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478
  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 {
  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. out.writeFileHeader(PACK_VERSION_GENERATED, objCnt);
  933. out.flush();
  934. writeObjects(out);
  935. if (!edgeObjects.isEmpty() || !cachedPacks.isEmpty()) {
  936. for (Statistics.ObjectType typeStat : stats.objectTypes) {
  937. if (typeStat == null)
  938. continue;
  939. stats.thinPackBytes += typeStat.bytes;
  940. }
  941. }
  942. for (CachedPack pack : cachedPacks) {
  943. long deltaCnt = pack.getDeltaCount();
  944. stats.reusedObjects += pack.getObjectCount();
  945. stats.reusedDeltas += deltaCnt;
  946. stats.totalDeltas += deltaCnt;
  947. reuseSupport.copyPackAsIs(out, pack, reuseValidate);
  948. }
  949. writeChecksum(out);
  950. out.flush();
  951. stats.timeWriting = System.currentTimeMillis() - writeStart;
  952. stats.totalBytes = out.length();
  953. stats.reusedPacks = Collections.unmodifiableList(cachedPacks);
  954. stats.depth = depth;
  955. for (Statistics.ObjectType typeStat : stats.objectTypes) {
  956. if (typeStat == null)
  957. continue;
  958. typeStat.cntDeltas += typeStat.reusedDeltas;
  959. stats.reusedObjects += typeStat.reusedObjects;
  960. stats.reusedDeltas += typeStat.reusedDeltas;
  961. stats.totalDeltas += typeStat.cntDeltas;
  962. }
  963. reader.release();
  964. endPhase(writeMonitor);
  965. }
  966. /**
  967. * @return description of what this PackWriter did in order to create the
  968. * final pack stream. The object is only available to callers after
  969. * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)}
  970. */
  971. public Statistics getStatistics() {
  972. return stats;
  973. }
  974. /** @return snapshot of the current state of this PackWriter. */
  975. public State getState() {
  976. return state.snapshot();
  977. }
  978. /** Release all resources used by this writer. */
  979. public void release() {
  980. reader.release();
  981. if (myDeflater != null) {
  982. myDeflater.end();
  983. myDeflater = null;
  984. }
  985. instances.remove(selfRef);
  986. }
  987. private void searchForReuse(ProgressMonitor monitor) throws IOException {
  988. long cnt = 0;
  989. cnt += objectsLists[OBJ_COMMIT].size();
  990. cnt += objectsLists[OBJ_TREE].size();
  991. cnt += objectsLists[OBJ_BLOB].size();
  992. cnt += objectsLists[OBJ_TAG].size();
  993. long start = System.currentTimeMillis();
  994. beginPhase(PackingPhase.FINDING_SOURCES, monitor, cnt);
  995. if (cnt <= 4096) {
  996. // For small object counts, do everything as one list.
  997. BlockList<ObjectToPack> tmp = new BlockList<ObjectToPack>((int) cnt);
  998. tmp.addAll(objectsLists[OBJ_TAG]);
  999. tmp.addAll(objectsLists[OBJ_COMMIT]);
  1000. tmp.addAll(objectsLists[OBJ_TREE]);
  1001. tmp.addAll(objectsLists[OBJ_BLOB]);
  1002. searchForReuse(monitor, tmp);
  1003. if (pruneCurrentObjectList) {
  1004. // If the list was pruned, we need to re-prune the main lists.
  1005. pruneEdgesFromObjectList(objectsLists[OBJ_COMMIT]);
  1006. pruneEdgesFromObjectList(objectsLists[OBJ_TREE]);
  1007. pruneEdgesFromObjectList(objectsLists[OBJ_BLOB]);
  1008. pruneEdgesFromObjectList(objectsLists[OBJ_TAG]);
  1009. }
  1010. } else {
  1011. searchForReuse(monitor, objectsLists[OBJ_TAG]);
  1012. searchForReuse(monitor, objectsLists[OBJ_COMMIT]);
  1013. searchForReuse(monitor, objectsLists[OBJ_TREE]);
  1014. searchForReuse(monitor, objectsLists[OBJ_BLOB]);
  1015. }
  1016. endPhase(monitor);
  1017. stats.timeSearchingForReuse = System.currentTimeMillis() - start;
  1018. if (config.isReuseDeltas() && config.getCutDeltaChains()) {
  1019. cutDeltaChains(objectsLists[OBJ_TREE]);
  1020. cutDeltaChains(objectsLists[OBJ_BLOB]);
  1021. }
  1022. }
  1023. private void searchForReuse(ProgressMonitor monitor, List<ObjectToPack> list)
  1024. throws IOException, MissingObjectException {
  1025. pruneCurrentObjectList = false;
  1026. reuseSupport.selectObjectRepresentation(this, monitor, list);
  1027. if (pruneCurrentObjectList)
  1028. pruneEdgesFromObjectList(list);
  1029. }
  1030. private void cutDeltaChains(BlockList<ObjectToPack> list)
  1031. throws IOException {
  1032. int max = config.getMaxDeltaDepth();
  1033. for (int idx = list.size() - 1; idx >= 0; idx--) {
  1034. int d = 0;
  1035. ObjectToPack b = list.get(idx).getDeltaBase();
  1036. while (b != null) {
  1037. if (d < b.getChainLength())
  1038. break;
  1039. b.setChainLength(++d);
  1040. if (d >= max && b.isDeltaRepresentation()) {
  1041. reselectNonDelta(b);
  1042. break;
  1043. }
  1044. b = b.getDeltaBase();
  1045. }
  1046. }
  1047. if (config.isDeltaCompress()) {
  1048. for (ObjectToPack otp : list)
  1049. otp.clearChainLength();
  1050. }
  1051. }
  1052. private void searchForDeltas(ProgressMonitor monitor)
  1053. throws MissingObjectException, IncorrectObjectTypeException,
  1054. IOException {
  1055. // Commits and annotated tags tend to have too many differences to
  1056. // really benefit from delta compression. Consequently just don't
  1057. // bother examining those types here.
  1058. //
  1059. ObjectToPack[] list = new ObjectToPack[
  1060. objectsLists[OBJ_TREE].size()
  1061. + objectsLists[OBJ_BLOB].size()
  1062. + edgeObjects.size()];
  1063. int cnt = 0;
  1064. cnt = findObjectsNeedingDelta(list, cnt, OBJ_TREE);
  1065. cnt = findObjectsNeedingDelta(list, cnt, OBJ_BLOB);
  1066. if (cnt == 0)
  1067. return;
  1068. int nonEdgeCnt = cnt;
  1069. // Queue up any edge objects that we might delta against. We won't
  1070. // be sending these as we assume the other side has them, but we need
  1071. // them in the search phase below.
  1072. //
  1073. for (ObjectToPack eo : edgeObjects) {
  1074. eo.setWeight(0);
  1075. list[cnt++] = eo;
  1076. }
  1077. // Compute the sizes of the objects so we can do a proper sort.
  1078. // We let the reader skip missing objects if it chooses. For
  1079. // some readers this can be a huge win. We detect missing objects
  1080. // by having set the weights above to 0 and allowing the delta
  1081. // search code to discover the missing object and skip over it, or
  1082. // abort with an exception if we actually had to have it.
  1083. //
  1084. final long sizingStart = System.currentTimeMillis();
  1085. beginPhase(PackingPhase.GETTING_SIZES, monitor, cnt);
  1086. AsyncObjectSizeQueue<ObjectToPack> sizeQueue = reader.getObjectSize(
  1087. Arrays.<ObjectToPack> asList(list).subList(0, cnt), false);
  1088. try {
  1089. final long limit = Math.min(
  1090. config.getBigFileThreshold(),
  1091. Integer.MAX_VALUE);
  1092. for (;;) {
  1093. try {
  1094. if (!sizeQueue.next())
  1095. break;
  1096. } catch (MissingObjectException notFound) {
  1097. monitor.update(1);
  1098. if (ignoreMissingUninteresting) {
  1099. ObjectToPack otp = sizeQueue.getCurrent();
  1100. if (otp != null && otp.isEdge()) {
  1101. otp.setDoNotDelta();
  1102. continue;
  1103. }
  1104. otp = objectsMap.get(notFound.getObjectId());
  1105. if (otp != null && otp.isEdge()) {
  1106. otp.setDoNotDelta();
  1107. continue;
  1108. }
  1109. }
  1110. throw notFound;
  1111. }
  1112. ObjectToPack otp = sizeQueue.getCurrent();
  1113. if (otp == null)
  1114. otp = objectsMap.get(sizeQueue.getObjectId());
  1115. long sz = sizeQueue.getSize();
  1116. if (DeltaIndex.BLKSZ < sz && sz < limit)
  1117. otp.setWeight((int) sz);
  1118. else
  1119. otp.setDoNotDelta(); // too small, or too big
  1120. monitor.update(1);
  1121. }
  1122. } finally {
  1123. sizeQueue.release();
  1124. }
  1125. endPhase(monitor);
  1126. stats.timeSearchingForSizes = System.currentTimeMillis() - sizingStart;
  1127. // Sort the objects by path hash so like files are near each other,
  1128. // and then by size descending so that bigger files are first. This
  1129. // applies "Linus' Law" which states that newer files tend to be the
  1130. // bigger ones, because source files grow and hardly ever shrink.
  1131. //
  1132. Arrays.sort(list, 0, cnt, new Comparator<ObjectToPack>() {
  1133. public int compare(ObjectToPack a, ObjectToPack b) {
  1134. int cmp = (a.isDoNotDelta() ? 1 : 0)
  1135. - (b.isDoNotDelta() ? 1 : 0);
  1136. if (cmp != 0)
  1137. return cmp;
  1138. cmp = a.getType() - b.getType();
  1139. if (cmp != 0)
  1140. return cmp;
  1141. cmp = (a.getPathHash() >>> 1) - (b.getPathHash() >>> 1);
  1142. if (cmp != 0)
  1143. return cmp;
  1144. cmp = (a.getPathHash() & 1) - (b.getPathHash() & 1);
  1145. if (cmp != 0)
  1146. return cmp;
  1147. cmp = (a.isEdge() ? 0 : 1) - (b.isEdge() ? 0 : 1);
  1148. if (cmp != 0)
  1149. return cmp;
  1150. return b.getWeight() - a.getWeight();
  1151. }
  1152. });
  1153. // Above we stored the objects we cannot delta onto the end.
  1154. // Remove them from the list so we don't waste time on them.
  1155. while (0 < cnt && list[cnt - 1].isDoNotDelta()) {
  1156. if (!list[cnt - 1].isEdge())
  1157. nonEdgeCnt--;
  1158. cnt--;
  1159. }
  1160. if (cnt == 0)
  1161. return;
  1162. final long searchStart = System.currentTimeMillis();
  1163. searchForDeltas(monitor, list, cnt);
  1164. stats.deltaSearchNonEdgeObjects = nonEdgeCnt;
  1165. stats.timeCompressing = System.currentTimeMillis() - searchStart;
  1166. for (int i = 0; i < cnt; i++)
  1167. if (!list[i].isEdge() && list[i].isDeltaRepresentation())
  1168. stats.deltasFound++;
  1169. }
  1170. private int findObjectsNeedingDelta(ObjectToPack[] list, int cnt, int type) {
  1171. for (ObjectToPack otp : objectsLists[type]) {
  1172. if (otp.isDoNotDelta()) // delta is disabled for this path
  1173. continue;
  1174. if (otp.isDeltaRepresentation()) // already reusing a delta
  1175. continue;
  1176. otp.setWeight(0);
  1177. list[cnt++] = otp;
  1178. }
  1179. return cnt;
  1180. }
  1181. private void reselectNonDelta(ObjectToPack otp) throws IOException {
  1182. otp.clearDeltaBase();
  1183. otp.clearReuseAsIs();
  1184. boolean old = reuseDeltas;
  1185. reuseDeltas = false;
  1186. reuseSupport.selectObjectRepresentation(this,
  1187. NullProgressMonitor.INSTANCE,
  1188. Collections.singleton(otp));
  1189. reuseDeltas = old;
  1190. }
  1191. private void searchForDeltas(final ProgressMonitor monitor,
  1192. final ObjectToPack[] list, final int cnt)
  1193. throws MissingObjectException, IncorrectObjectTypeException,
  1194. LargeObjectException, IOException {
  1195. int threads = config.getThreads();
  1196. if (threads == 0)
  1197. threads = Runtime.getRuntime().availableProcessors();
  1198. if (threads <= 1 || cnt <= config.getDeltaSearchWindowSize())
  1199. singleThreadDeltaSearch(monitor, list, cnt);
  1200. else
  1201. parallelDeltaSearch(monitor, list, cnt, threads);
  1202. }
  1203. private void singleThreadDeltaSearch(ProgressMonitor monitor,
  1204. ObjectToPack[] list, int cnt) throws IOException {
  1205. long totalWeight = 0;
  1206. for (int i = 0; i < cnt; i++) {
  1207. ObjectToPack o = list[i];
  1208. if (!o.isEdge() && !o.doNotAttemptDelta())
  1209. totalWeight += o.getWeight();
  1210. }
  1211. long bytesPerUnit = 1;
  1212. while (DeltaTask.MAX_METER <= (totalWeight / bytesPerUnit))
  1213. bytesPerUnit <<= 10;
  1214. int cost = (int) (totalWeight / bytesPerUnit);
  1215. if (totalWeight % bytesPerUnit != 0)
  1216. cost++;
  1217. beginPhase(PackingPhase.COMPRESSING, monitor, cost);
  1218. new DeltaWindow(config, new DeltaCache(config), reader,
  1219. monitor, bytesPerUnit,
  1220. list, 0, cnt).search();
  1221. endPhase(monitor);
  1222. }
  1223. private void parallelDeltaSearch(ProgressMonitor monitor,
  1224. ObjectToPack[] list, int cnt, int threads) throws IOException {
  1225. DeltaCache dc = new ThreadSafeDeltaCache(config);
  1226. ThreadSafeProgressMonitor pm = new ThreadSafeProgressMonitor(monitor);
  1227. DeltaTask.Block taskBlock = new DeltaTask.Block(threads, config,
  1228. reader, dc, pm,
  1229. list, 0, cnt);
  1230. taskBlock.partitionTasks();
  1231. beginPhase(PackingPhase.COMPRESSING, monitor, taskBlock.cost());
  1232. pm.startWorkers(taskBlock.tasks.size());
  1233. Executor executor = config.getExecutor();
  1234. final List<Throwable> errors =
  1235. Collections.synchronizedList(new ArrayList<Throwable>(threads));
  1236. if (executor instanceof ExecutorService) {
  1237. // Caller supplied us a service, use it directly.
  1238. runTasks((ExecutorService) executor, pm, taskBlock, errors);
  1239. } else if (executor == null) {
  1240. // Caller didn't give us a way to run the tasks, spawn up a
  1241. // temporary thread pool and make sure it tears down cleanly.
  1242. ExecutorService pool = Executors.newFixedThreadPool(threads);
  1243. try {
  1244. runTasks(pool, pm, taskBlock, errors);
  1245. } finally {
  1246. pool.shutdown();
  1247. for (;;) {
  1248. try {
  1249. if (pool.awaitTermination(60, TimeUnit.SECONDS))
  1250. break;
  1251. } catch (InterruptedException e) {
  1252. throw new IOException(
  1253. JGitText.get().packingCancelledDuringObjectsWriting);
  1254. }
  1255. }
  1256. }
  1257. } else {
  1258. // The caller gave us an executor, but it might not do
  1259. // asynchronous execution. Wrap everything and hope it
  1260. // can schedule these for us.
  1261. for (final DeltaTask task : taskBlock.tasks) {
  1262. executor.execute(new Runnable() {
  1263. public void run() {
  1264. try {
  1265. task.call();
  1266. } catch (Throwable failure) {
  1267. errors.add(failure);
  1268. }
  1269. }
  1270. });
  1271. }
  1272. try {
  1273. pm.waitForCompletion();
  1274. } catch (InterruptedException ie) {
  1275. // We can't abort the other tasks as we have no handle.
  1276. // Cross our fingers and just break out anyway.
  1277. //
  1278. throw new IOException(
  1279. JGitText.get().packingCancelledDuringObjectsWriting);
  1280. }
  1281. }
  1282. // If any task threw an error, try to report it back as
  1283. // though we weren't using a threaded search algorithm.
  1284. //
  1285. if (!errors.isEmpty()) {
  1286. Throwable err = errors.get(0);
  1287. if (err instanceof Error)
  1288. throw (Error) err;
  1289. if (err instanceof RuntimeException)
  1290. throw (RuntimeException) err;
  1291. if (err instanceof IOException)
  1292. throw (IOException) err;
  1293. IOException fail = new IOException(err.getMessage());
  1294. fail.initCause(err);
  1295. throw fail;
  1296. }
  1297. endPhase(monitor);
  1298. }
  1299. private static void runTasks(ExecutorService pool,
  1300. ThreadSafeProgressMonitor pm,
  1301. DeltaTask.Block tb, List<Throwable> errors) throws IOException {
  1302. List<Future<?>> futures = new ArrayList<Future<?>>(tb.tasks.size());
  1303. for (DeltaTask task : tb.tasks)
  1304. futures.add(pool.submit(task));
  1305. try {
  1306. pm.waitForCompletion();
  1307. for (Future<?> f : futures) {
  1308. try {
  1309. f.get();
  1310. } catch (ExecutionException failed) {
  1311. errors.add(failed.getCause());
  1312. }
  1313. }
  1314. } catch (InterruptedException ie) {
  1315. for (Future<?> f : futures)
  1316. f.cancel(true);
  1317. throw new IOException(
  1318. JGitText.get().packingCancelledDuringObjectsWriting);
  1319. }
  1320. }
  1321. private void writeObjects(PackOutputStream out) throws IOException {
  1322. writeObjects(out, objectsLists[OBJ_COMMIT]);
  1323. writeObjects(out, objectsLists[OBJ_TAG]);
  1324. writeObjects(out, objectsLists[OBJ_TREE]);
  1325. writeObjects(out, objectsLists[OBJ_BLOB]);
  1326. }
  1327. private void writeObjects(PackOutputStream out, List<ObjectToPack> list)
  1328. throws IOException {
  1329. if (list.isEmpty())
  1330. return;
  1331. typeStats = stats.objectTypes[list.get(0).getType()];
  1332. long beginOffset = out.length();
  1333. if (reuseSupport != null) {
  1334. reuseSupport.writeObjects(out, list);
  1335. } else {
  1336. for (ObjectToPack otp : list)
  1337. out.writeObject(otp);
  1338. }
  1339. typeStats.bytes += out.length() - beginOffset;
  1340. typeStats.cntObjects = list.size();
  1341. }
  1342. void writeObject(PackOutputStream out, ObjectToPack otp) throws IOException {
  1343. if (!otp.isWritten())
  1344. writeObjectImpl(out, otp);
  1345. }
  1346. private void writeObjectImpl(PackOutputStream out, ObjectToPack otp)
  1347. throws IOException {
  1348. if (otp.wantWrite()) {
  1349. // A cycle exists in this delta chain. This should only occur if a
  1350. // selected object representation disappeared during writing
  1351. // (for example due to a concurrent repack) and a different base
  1352. // was chosen, forcing a cycle. Select something other than a
  1353. // delta, and write this object.
  1354. reselectNonDelta(otp);
  1355. }
  1356. otp.markWantWrite();
  1357. while (otp.isReuseAsIs()) {
  1358. writeBase(out, otp.getDeltaBase());
  1359. if (otp.isWritten())
  1360. return; // Delta chain cycle caused this to write already.
  1361. crc32.reset();
  1362. otp.setOffset(out.length());
  1363. try {
  1364. reuseSupport.copyObjectAsIs(out, otp, reuseValidate);
  1365. out.endObject();
  1366. otp.setCRC((int) crc32.getValue());
  1367. typeStats.reusedObjects++;
  1368. if (otp.isDeltaRepresentation()) {
  1369. typeStats.reusedDeltas++;
  1370. typeStats.deltaBytes += out.length() - otp.getOffset();
  1371. }
  1372. return;
  1373. } catch (StoredObjectRepresentationNotAvailableException gone) {
  1374. if (otp.getOffset() == out.length()) {
  1375. otp.setOffset(0);
  1376. otp.clearDeltaBase();
  1377. otp.clearReuseAsIs();
  1378. reuseSupport.selectObjectRepresentation(this,
  1379. NullProgressMonitor.INSTANCE,
  1380. Collections.singleton(otp));
  1381. continue;
  1382. } else {
  1383. // Object writing already started, we cannot recover.
  1384. //
  1385. CorruptObjectException coe;
  1386. coe = new CorruptObjectException(otp, ""); //$NON-NLS-1$
  1387. coe.initCause(gone);
  1388. throw coe;
  1389. }
  1390. }
  1391. }
  1392. // If we reached here, reuse wasn't possible.
  1393. //
  1394. if (otp.isDeltaRepresentation())
  1395. writeDeltaObjectDeflate(out, otp);
  1396. else
  1397. writeWholeObjectDeflate(out, otp);
  1398. out.endObject();
  1399. otp.setCRC((int) crc32.getValue());
  1400. }
  1401. private void writeBase(PackOutputStream out, ObjectToPack base)
  1402. throws IOException {
  1403. if (base != null && !base.isWritten() && !base.isEdge())
  1404. writeObjectImpl(out, base);
  1405. }
  1406. private void writeWholeObjectDeflate(PackOutputStream out,
  1407. final ObjectToPack otp) throws IOException {
  1408. final Deflater deflater = deflater();
  1409. final ObjectLoader ldr = reader.open(otp, otp.getType());
  1410. crc32.reset();
  1411. otp.setOffset(out.length());
  1412. out.writeHeader(otp, ldr.getSize());
  1413. deflater.reset();
  1414. DeflaterOutputStream dst = new DeflaterOutputStream(out, deflater);
  1415. ldr.copyTo(dst);
  1416. dst.finish();
  1417. }
  1418. private void writeDeltaObjectDeflate(PackOutputStream out,
  1419. final ObjectToPack otp) throws IOException {
  1420. writeBase(out, otp.getDeltaBase());
  1421. crc32.reset();
  1422. otp.setOffset(out.length());
  1423. DeltaCache.Ref ref = otp.popCachedDelta();
  1424. if (ref != null) {
  1425. byte[] zbuf = ref.get();
  1426. if (zbuf != null) {
  1427. out.writeHeader(otp, otp.getCachedSize());
  1428. out.write(zbuf);
  1429. return;
  1430. }
  1431. }
  1432. TemporaryBuffer.Heap delta = delta(otp);
  1433. out.writeHeader(otp, delta.length());
  1434. Deflater deflater = deflater();
  1435. deflater.reset();
  1436. DeflaterOutputStream dst = new DeflaterOutputStream(out, deflater);
  1437. delta.writeTo(dst, null);
  1438. dst.finish();
  1439. typeStats.cntDeltas++;
  1440. typeStats.deltaBytes += out.length() - otp.getOffset();
  1441. }
  1442. private TemporaryBuffer.Heap delta(final ObjectToPack otp)
  1443. throws IOException {
  1444. DeltaIndex index = new DeltaIndex(buffer(otp.getDeltaBaseId()));
  1445. byte[] res = buffer(otp);
  1446. // We never would have proposed this pair if the delta would be
  1447. // larger than the unpacked version of the object. So using it
  1448. // as our buffer limit is valid: we will never reach it.
  1449. //
  1450. TemporaryBuffer.Heap delta = new TemporaryBuffer.Heap(res.length);
  1451. index.encode(delta, res);
  1452. return delta;
  1453. }
  1454. private byte[] buffer(AnyObjectId objId) throws IOException {
  1455. return buffer(config, reader, objId);
  1456. }
  1457. static byte[] buffer(PackConfig config, ObjectReader or, AnyObjectId objId)
  1458. throws IOException {
  1459. // PackWriter should have already pruned objects that
  1460. // are above the big file threshold, so our chances of
  1461. // the object being below it are very good. We really
  1462. // shouldn't be here, unless the implementation is odd.
  1463. return or.open(objId).getCachedBytes(config.getBigFileThreshold());
  1464. }
  1465. private Deflater deflater() {
  1466. if (myDeflater == null)
  1467. myDeflater = new Deflater(config.getCompressionLevel());
  1468. return myDeflater;
  1469. }
  1470. private void writeChecksum(PackOutputStream out) throws IOException {
  1471. packcsum = out.getDigest();
  1472. out.write(packcsum);
  1473. }
  1474. private void findObjectsToPack(final ProgressMonitor countingMonitor,
  1475. final ObjectWalk walker, final Set<? extends ObjectId> want,
  1476. Set<? extends ObjectId> have)
  1477. throws MissingObjectException, IOException,
  1478. IncorrectObjectTypeException {
  1479. final long countingStart = System.currentTimeMillis();
  1480. beginPhase(PackingPhase.COUNTING, countingMonitor, ProgressMonitor.UNKNOWN);
  1481. if (have == null)
  1482. have = Collections.emptySet();
  1483. stats.interestingObjects = Collections.unmodifiableSet(new HashSet<ObjectId>(want));
  1484. stats.uninterestingObjects = Collections.unmodifiableSet(new HashSet<ObjectId>(have));
  1485. walker.setRetainBody(false);
  1486. canBuildBitmaps = config.isBuildBitmaps()
  1487. && !shallowPack
  1488. && have.isEmpty()
  1489. && (excludeInPacks == null || excludeInPacks.length == 0);
  1490. if (!shallowPack && useBitmaps) {
  1491. BitmapIndex bitmapIndex = reader.getBitmapIndex();
  1492. if (bitmapIndex != null) {
  1493. PackWriterBitmapWalker bitmapWalker = new PackWriterBitmapWalker(
  1494. walker, bitmapIndex, countingMonitor);
  1495. findObjectsToPackUsingBitmaps(bitmapWalker, want, have);
  1496. endPhase(countingMonitor);
  1497. stats.timeCounting = System.currentTimeMillis() - countingStart;
  1498. return;
  1499. }
  1500. }
  1501. List<ObjectId> all = new ArrayList<ObjectId>(want.size() + have.size());
  1502. all.addAll(want);
  1503. all.addAll(have);
  1504. final RevFlag include = walker.newFlag("include"); //$NON-NLS-1$
  1505. final RevFlag added = walker.newFlag("added"); //$NON-NLS-1$
  1506. walker.carry(include);
  1507. int haveEst = have.size();
  1508. if (have.isEmpty()) {
  1509. walker.sort(RevSort.COMMIT_TIME_DESC);
  1510. } else {
  1511. walker.sort(RevSort.TOPO);
  1512. if (thin)
  1513. walker.sort(RevSort.BOUNDARY, true);
  1514. }
  1515. List<RevObject> wantObjs = new ArrayList<RevObject>(want.size());
  1516. List<RevObject> haveObjs = new ArrayList<RevObject>(haveEst);
  1517. List<RevTag> wantTags = new ArrayList<RevTag>(want.size());
  1518. AsyncRevObjectQueue q = walker.parseAny(all, true);
  1519. try {
  1520. for (;;) {
  1521. try {
  1522. RevObject o = q.next();
  1523. if (o == null)
  1524. break;
  1525. if (have.contains(o))
  1526. haveObjs.add(o);
  1527. if (want.contains(o)) {
  1528. o.add(include);
  1529. wantObjs.add(o);
  1530. if (o instanceof RevTag)
  1531. wantTags.add((RevTag) o);
  1532. }
  1533. } catch (MissingObjectException e) {
  1534. if (ignoreMissingUninteresting
  1535. && have.contains(e.getObjectId()))
  1536. continue;
  1537. throw e;
  1538. }
  1539. }
  1540. } finally {
  1541. q.release();
  1542. }
  1543. if (!wantTags.isEmpty()) {
  1544. all = new ArrayList<ObjectId>(wantTags.size());
  1545. for (RevTag tag : wantTags)
  1546. all.add(tag.getObject());
  1547. q = walker.parseAny(all, true);
  1548. try {
  1549. while (q.next() != null) {
  1550. // Just need to pop the queue item to parse the object.
  1551. }
  1552. } finally {
  1553. q.release();
  1554. }
  1555. }
  1556. if (walker instanceof DepthWalk.ObjectWalk) {
  1557. DepthWalk.ObjectWalk depthWalk = (DepthWalk.ObjectWalk) walker;
  1558. for (RevObject obj : wantObjs)
  1559. depthWalk.markRoot(obj);
  1560. if (unshallowObjects != null) {
  1561. for (ObjectId id : unshallowObjects)
  1562. depthWalk.markUnshallow(walker.parseAny(id));
  1563. }
  1564. } else {
  1565. for (RevObject obj : wantObjs)
  1566. walker.markStart(obj);
  1567. }
  1568. for (RevObject obj : haveObjs)
  1569. walker.markUninteresting(obj);
  1570. final int maxBases = config.getDeltaSearchWindowSize();
  1571. Set<RevTree> baseTrees = new HashSet<RevTree>();
  1572. BlockList<RevCommit> commits = new BlockList<RevCommit>();
  1573. RevCommit c;
  1574. while ((c = walker.next()) != null) {
  1575. if (exclude(c))
  1576. continue;
  1577. if (c.has(RevFlag.UNINTERESTING)) {
  1578. if (baseTrees.size() <= maxBases)
  1579. baseTrees.add(c.getTree());
  1580. continue;
  1581. }
  1582. commits.add(c);
  1583. countingMonitor.update(1);
  1584. }
  1585. if (shallowPack) {
  1586. for (RevCommit cmit : commits) {
  1587. addObject(cmit, 0);
  1588. }
  1589. } else {
  1590. int commitCnt = 0;
  1591. boolean putTagTargets = false;
  1592. for (RevCommit cmit : commits) {
  1593. if (!cmit.has(added)) {
  1594. cmit.add(added);
  1595. addObject(cmit, 0);
  1596. commitCnt++;
  1597. }
  1598. for (int i = 0; i < cmit.getParentCount(); i++) {
  1599. RevCommit p = cmit.getParent(i);
  1600. if (!p.has(added) && !p.has(RevFlag.UNINTERESTING)
  1601. && !exclude(p)) {
  1602. p.add(added);
  1603. addObject(p, 0);
  1604. commitCnt++;
  1605. }
  1606. }
  1607. if (!putTagTargets && 4096 < commitCnt) {
  1608. for (ObjectId id : tagTargets) {
  1609. RevObject obj = walker.lookupOrNull(id);
  1610. if (obj instanceof RevCommit
  1611. && obj.has(include)
  1612. && !obj.has(RevFlag.UNINTERESTING)
  1613. && !obj.has(added)) {
  1614. obj.add(added);
  1615. addObject(obj, 0);
  1616. }
  1617. }
  1618. putTagTargets = true;
  1619. }
  1620. }
  1621. }
  1622. commits = null;
  1623. if (thin && !baseTrees.isEmpty()) {
  1624. BaseSearch bases = new BaseSearch(countingMonitor, baseTrees, //
  1625. objectsMap, edgeObjects, reader);
  1626. RevObject o;
  1627. while ((o = walker.nextObject()) != null) {
  1628. if (o.has(RevFlag.UNINTERESTING))
  1629. continue;
  1630. if (exclude(o))
  1631. continue;
  1632. int pathHash = walker.getPathHashCode();
  1633. byte[] pathBuf = walker.getPathBuffer();
  1634. int pathLen = walker.getPathLength();
  1635. bases.addBase(o.getType(), pathBuf, pathLen, pathHash);
  1636. addObject(o, pathHash);
  1637. countingMonitor.update(1);
  1638. }
  1639. } else {
  1640. RevObject o;
  1641. while ((o = walker.nextObject()) != null) {
  1642. if (o.has(RevFlag.UNINTERESTING))
  1643. continue;
  1644. if (exclude(o))
  1645. continue;
  1646. addObject(o, walker.getPathHashCode());
  1647. countingMonitor.update(1);
  1648. }
  1649. }
  1650. for (CachedPack pack : cachedPacks)
  1651. countingMonitor.update((int) pack.getObjectCount());
  1652. endPhase(countingMonitor);
  1653. stats.timeCounting = System.currentTimeMillis() - countingStart;
  1654. }
  1655. private void findObjectsToPackUsingBitmaps(
  1656. PackWriterBitmapWalker bitmapWalker, Set<? extends ObjectId> want,
  1657. Set<? extends ObjectId> have)
  1658. throws MissingObjectException, IncorrectObjectTypeException,
  1659. IOException {
  1660. BitmapBuilder haveBitmap = bitmapWalker.findObjects(have, null, true);
  1661. bitmapWalker.reset();
  1662. BitmapBuilder wantBitmap = bitmapWalker.findObjects(want, haveBitmap,
  1663. false);
  1664. BitmapBuilder needBitmap = wantBitmap.andNot(haveBitmap);
  1665. if (useCachedPacks && reuseSupport != null
  1666. && (excludeInPacks == null || excludeInPacks.length == 0))
  1667. cachedPacks.addAll(
  1668. reuseSupport.getCachedPacksAndUpdate(needBitmap));
  1669. for (BitmapObject obj : needBitmap) {
  1670. ObjectId objectId = obj.getObjectId();
  1671. if (exclude(objectId)) {
  1672. needBitmap.remove(objectId);
  1673. continue;
  1674. }
  1675. addObject(objectId, obj.getType(), 0);
  1676. }
  1677. if (thin)
  1678. haveObjects = haveBitmap;
  1679. }
  1680. private static void pruneEdgesFromObjectList(List<ObjectToPack> list) {
  1681. final int size = list.size();
  1682. int src = 0;
  1683. int dst = 0;
  1684. for (; src < size; src++) {
  1685. ObjectToPack obj = list.get(src);
  1686. if (obj.isEdge())
  1687. continue;
  1688. if (dst != src)
  1689. list.set(dst, obj);
  1690. dst++;
  1691. }
  1692. while (dst < list.size())
  1693. list.remove(list.size() - 1);
  1694. }
  1695. /**
  1696. * Include one object to the output file.
  1697. * <p>
  1698. * Objects are written in the order they are added. If the same object is
  1699. * added twice, it may be written twice, creating a larger than necessary
  1700. * file.
  1701. *
  1702. * @param object
  1703. * the object to add.
  1704. * @throws IncorrectObjectTypeException
  1705. * the object is an unsupported type.
  1706. */
  1707. public void addObject(final RevObject object)
  1708. throws IncorrectObjectTypeException {
  1709. if (!exclude(object))
  1710. addObject(object, 0);
  1711. }
  1712. private void addObject(final RevObject object, final int pathHashCode) {
  1713. addObject(object, object.getType(), pathHashCode);
  1714. }
  1715. private void addObject(
  1716. final AnyObjectId src, final int type, final int pathHashCode) {
  1717. final ObjectToPack otp;
  1718. if (reuseSupport != null)
  1719. otp = reuseSupport.newObjectToPack(src, type);
  1720. else
  1721. otp = new ObjectToPack(src, type);
  1722. otp.setPathHash(pathHashCode);
  1723. objectsLists[type].add(otp);
  1724. objectsMap.add(otp);
  1725. }
  1726. private boolean exclude(AnyObjectId objectId) {
  1727. if (excludeInPacks == null)
  1728. return false;
  1729. if (excludeInPackLast.contains(objectId))
  1730. return true;
  1731. for (ObjectIdSet idx : excludeInPacks) {
  1732. if (idx.contains(objectId)) {
  1733. excludeInPackLast = idx;
  1734. return true;
  1735. }
  1736. }
  1737. return false;
  1738. }
  1739. /**
  1740. * Select an object representation for this writer.
  1741. * <p>
  1742. * An {@link ObjectReader} implementation should invoke this method once for
  1743. * each representation available for an object, to allow the writer to find
  1744. * the most suitable one for the output.
  1745. *
  1746. * @param otp
  1747. * the object being packed.
  1748. * @param next
  1749. * the next available representation from the repository.
  1750. */
  1751. public void select(ObjectToPack otp, StoredObjectRepresentation next) {
  1752. int nFmt = next.getFormat();
  1753. if (!cachedPacks.isEmpty()) {
  1754. if (otp.isEdge())
  1755. return;
  1756. if ((nFmt == PACK_WHOLE) | (nFmt == PACK_DELTA)) {
  1757. for (CachedPack pack : cachedPacks) {
  1758. if (pack.hasObject(otp, next)) {
  1759. otp.setEdge();
  1760. otp.clearDeltaBase();
  1761. otp.clearReuseAsIs();
  1762. pruneCurrentObjectList = true;
  1763. return;
  1764. }
  1765. }
  1766. }
  1767. }
  1768. if (nFmt == PACK_DELTA && reuseDeltas && reuseDeltaFor(otp)) {
  1769. ObjectId baseId = next.getDeltaBase();
  1770. ObjectToPack ptr = objectsMap.get(baseId);
  1771. if (ptr != null && !ptr.isEdge()) {
  1772. otp.setDeltaBase(ptr);
  1773. otp.setReuseAsIs();
  1774. } else if (thin && have(ptr, baseId)) {
  1775. otp.setDeltaBase(baseId);
  1776. otp.setReuseAsIs();
  1777. } else {
  1778. otp.clearDeltaBase();
  1779. otp.clearReuseAsIs();
  1780. }
  1781. } else if (nFmt == PACK_WHOLE && config.isReuseObjects()) {
  1782. int nWeight = next.getWeight();
  1783. if (otp.isReuseAsIs() && !otp.isDeltaRepresentation()) {
  1784. // We've chosen another PACK_WHOLE format for this object,
  1785. // choose the one that has the smaller compressed size.
  1786. //
  1787. if (otp.getWeight() <= nWeight)
  1788. return;
  1789. }
  1790. otp.clearDeltaBase();
  1791. otp.setReuseAsIs();
  1792. otp.setWeight(nWeight);
  1793. } else {
  1794. otp.clearDeltaBase();
  1795. otp.clearReuseAsIs();
  1796. }
  1797. otp.setDeltaAttempted(reuseDeltas & next.wasDeltaAttempted());
  1798. otp.select(next);
  1799. }
  1800. private final boolean have(ObjectToPack ptr, AnyObjectId objectId) {
  1801. return (ptr != null && ptr.isEdge())
  1802. || (haveObjects != null && haveObjects.contains(objectId));
  1803. }
  1804. /**
  1805. * Prepares the bitmaps to be written to the pack index. Bitmaps can be used
  1806. * to speed up fetches and clones by storing the entire object graph at
  1807. * selected commits.
  1808. *
  1809. * This method can only be invoked after
  1810. * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)} has
  1811. * been invoked and completed successfully. Writing a corresponding bitmap
  1812. * index is an optional feature that not all pack users may require.
  1813. *
  1814. * @param pm
  1815. * progress monitor to report bitmap building work.
  1816. * @return whether a bitmap index may be written.
  1817. * @throws IOException
  1818. * when some I/O problem occur during reading objects.
  1819. */
  1820. public boolean prepareBitmapIndex(ProgressMonitor pm) throws IOException {
  1821. if (!canBuildBitmaps || getObjectCount() > Integer.MAX_VALUE
  1822. || !cachedPacks.isEmpty())
  1823. return false;
  1824. if (pm == null)
  1825. pm = NullProgressMonitor.INSTANCE;
  1826. writeBitmaps = new PackBitmapIndexBuilder(sortByName());
  1827. PackWriterBitmapPreparer bitmapPreparer = new PackWriterBitmapPreparer(
  1828. reader, writeBitmaps, pm, stats.interestingObjects);
  1829. int numCommits = objectsLists[OBJ_COMMIT].size();
  1830. Collection<PackWriterBitmapPreparer.BitmapCommit> selectedCommits =
  1831. bitmapPreparer.doCommitSelection(numCommits);
  1832. beginPhase(PackingPhase.BUILDING_BITMAPS, pm, selectedCommits.size());
  1833. PackWriterBitmapWalker walker = bitmapPreparer.newBitmapWalker();
  1834. AnyObjectId last = null;
  1835. for (PackWriterBitmapPreparer.BitmapCommit cmit : selectedCommits) {
  1836. if (cmit.isReuseWalker())
  1837. walker.reset();
  1838. else
  1839. walker = bitmapPreparer.newBitmapWalker();
  1840. BitmapBuilder bitmap = walker.findObjects(
  1841. Collections.singleton(cmit), null, false);
  1842. if (last != null && cmit.isReuseWalker() && !bitmap.contains(last))
  1843. throw new IllegalStateException(MessageFormat.format(
  1844. JGitText.get().bitmapMissingObject, cmit.name(),
  1845. last.name()));
  1846. last = cmit;
  1847. writeBitmaps.addBitmap(cmit, bitmap.build(), cmit.getFlags());
  1848. pm.update(1);
  1849. }
  1850. endPhase(pm);
  1851. return true;
  1852. }
  1853. private boolean reuseDeltaFor(ObjectToPack otp) {
  1854. int type = otp.getType();
  1855. if ((type & 2) != 0) // OBJ_TREE(2) or OBJ_BLOB(3)
  1856. return true;
  1857. if (type == OBJ_COMMIT)
  1858. return reuseDeltaCommits;
  1859. if (type == OBJ_TAG)
  1860. return false;
  1861. return true;
  1862. }
  1863. /** Summary of how PackWriter created the pack. */
  1864. public static class Statistics {
  1865. /** Statistics about a single class of object. */
  1866. public static class ObjectType {
  1867. long cntObjects;
  1868. long cntDeltas;
  1869. long reusedObjects;
  1870. long reusedDeltas;
  1871. long bytes;
  1872. long deltaBytes;
  1873. /**
  1874. * @return total number of objects output. This total includes the
  1875. * value of {@link #getDeltas()}.
  1876. */
  1877. public long getObjects() {
  1878. return cntObjects;
  1879. }
  1880. /**
  1881. * @return total number of deltas output. This may be lower than the
  1882. * actual number of deltas if a cached pack was reused.
  1883. */
  1884. public long getDeltas() {
  1885. return cntDeltas;
  1886. }
  1887. /**
  1888. * @return number of objects whose existing representation was
  1889. * reused in the output. This count includes
  1890. * {@link #getReusedDeltas()}.
  1891. */
  1892. public long getReusedObjects() {
  1893. return reusedObjects;
  1894. }
  1895. /**
  1896. * @return number of deltas whose existing representation was reused
  1897. * in the output, as their base object was also output or
  1898. * was assumed present for a thin pack. This may be lower
  1899. * than the actual number of reused deltas if a cached pack
  1900. * was reused.
  1901. */
  1902. public long getReusedDeltas() {
  1903. return reusedDeltas;
  1904. }
  1905. /**
  1906. * @return total number of bytes written. This size includes the
  1907. * object headers as well as the compressed data. This size
  1908. * also includes all of {@link #getDeltaBytes()}.
  1909. */
  1910. public long getBytes() {
  1911. return bytes;
  1912. }
  1913. /**
  1914. * @return number of delta bytes written. This size includes the
  1915. * object headers for the delta objects.
  1916. */
  1917. public long getDeltaBytes() {
  1918. return deltaBytes;
  1919. }
  1920. }
  1921. Set<ObjectId> interestingObjects;
  1922. Set<ObjectId> uninterestingObjects;
  1923. Collection<CachedPack> reusedPacks;
  1924. int depth;
  1925. int deltaSearchNonEdgeObjects;
  1926. int deltasFound;
  1927. long totalObjects;
  1928. long totalDeltas;
  1929. long reusedObjects;
  1930. long reusedDeltas;
  1931. long totalBytes;
  1932. long thinPackBytes;
  1933. long timeCounting;
  1934. long timeSearchingForReuse;
  1935. long timeSearchingForSizes;
  1936. long timeCompressing;
  1937. long timeWriting;
  1938. ObjectType[] objectTypes;
  1939. {
  1940. objectTypes = new ObjectType[5];
  1941. objectTypes[OBJ_COMMIT] = new ObjectType();
  1942. objectTypes[OBJ_TREE] = new ObjectType();
  1943. objectTypes[OBJ_BLOB] = new ObjectType();
  1944. objectTypes[OBJ_TAG] = new ObjectType();
  1945. }
  1946. /**
  1947. * @return unmodifiable collection of objects to be included in the
  1948. * pack. May be null if the pack was hand-crafted in a unit
  1949. * test.
  1950. */
  1951. public Set<ObjectId> getInterestingObjects() {
  1952. return interestingObjects;
  1953. }
  1954. /**
  1955. * @return unmodifiable collection of objects that should be excluded
  1956. * from the pack, as the peer that will receive the pack already
  1957. * has these objects.
  1958. */
  1959. public Set<ObjectId> getUninterestingObjects() {
  1960. return uninterestingObjects;
  1961. }
  1962. /**
  1963. * @return unmodifiable collection of the cached packs that were reused
  1964. * in the output, if any were selected for reuse.
  1965. */
  1966. public Collection<CachedPack> getReusedPacks() {
  1967. return reusedPacks;
  1968. }
  1969. /**
  1970. * @return number of objects in the output pack that went through the
  1971. * delta search process in order to find a potential delta base.
  1972. */
  1973. public int getDeltaSearchNonEdgeObjects() {
  1974. return deltaSearchNonEdgeObjects;
  1975. }
  1976. /**
  1977. * @return number of objects in the output pack that went through delta
  1978. * base search and found a suitable base. This is a subset of
  1979. * {@link #getDeltaSearchNonEdgeObjects()}.
  1980. */
  1981. public int getDeltasFound() {
  1982. return deltasFound;
  1983. }
  1984. /**
  1985. * @return total number of objects output. This total includes the value
  1986. * of {@link #getTotalDeltas()}.
  1987. */
  1988. public long getTotalObjects() {
  1989. return totalObjects;
  1990. }
  1991. /**
  1992. * @return total number of deltas output. This may be lower than the
  1993. * actual number of deltas if a cached pack was reused.
  1994. */
  1995. public long getTotalDeltas() {
  1996. return totalDeltas;
  1997. }
  1998. /**
  1999. * @return number of objects whose existing representation was reused in
  2000. * the output. This count includes {@link #getReusedDeltas()}.
  2001. */
  2002. public long getReusedObjects() {
  2003. return reusedObjects;
  2004. }
  2005. /**
  2006. * @return number of deltas whose existing representation was reused in
  2007. * the output, as their base object was also output or was
  2008. * assumed present for a thin pack. This may be lower than the
  2009. * actual number of reused deltas if a cached pack was reused.
  2010. */
  2011. public long getReusedDeltas() {
  2012. return reusedDeltas;
  2013. }
  2014. /**
  2015. * @return total number of bytes written. This size includes the pack
  2016. * header, trailer, thin pack, and reused cached pack(s).
  2017. */
  2018. public long getTotalBytes() {
  2019. return totalBytes;
  2020. }
  2021. /**
  2022. * @return size of the thin pack in bytes, if a thin pack was generated.
  2023. * A thin pack is created when the client already has objects
  2024. * and some deltas are created against those objects, or if a
  2025. * cached pack is being used and some deltas will reference
  2026. * objects in the cached pack. This size does not include the
  2027. * pack header or trailer.
  2028. */
  2029. public long getThinPackBytes() {
  2030. return thinPackBytes;
  2031. }
  2032. /**
  2033. * @param typeCode
  2034. * object type code, e.g. OBJ_COMMIT or OBJ_TREE.
  2035. * @return information about this type of object in the pack.
  2036. */
  2037. public ObjectType byObjectType(int typeCode) {
  2038. return objectTypes[typeCode];
  2039. }
  2040. /** @return true if the resulting pack file was a shallow pack. */
  2041. public boolean isShallow() {
  2042. return depth > 0;
  2043. }
  2044. /** @return depth (in commits) the pack includes if shallow. */
  2045. public int getDepth() {
  2046. return depth;
  2047. }
  2048. /**
  2049. * @return time in milliseconds spent enumerating the objects that need
  2050. * to be included in the output. This time includes any restarts
  2051. * that occur when a cached pack is selected for reuse.
  2052. */
  2053. public long getTimeCounting() {
  2054. return timeCounting;
  2055. }
  2056. /**
  2057. * @return time in milliseconds spent matching existing representations
  2058. * against objects that will be transmitted, or that the client
  2059. * can be assumed to already have.
  2060. */
  2061. public long getTimeSearchingForReuse() {
  2062. return timeSearchingForReuse;
  2063. }
  2064. /**
  2065. * @return time in milliseconds spent finding the sizes of all objects
  2066. * that will enter the delta compression search window. The
  2067. * sizes need to be known to better match similar objects
  2068. * together and improve delta compression ratios.
  2069. */
  2070. public long getTimeSearchingForSizes() {
  2071. return timeSearchingForSizes;
  2072. }
  2073. /**
  2074. * @return time in milliseconds spent on delta compression. This is
  2075. * observed wall-clock time and does not accurately track CPU
  2076. * time used when multiple threads were used to perform the
  2077. * delta compression.
  2078. */
  2079. public long getTimeCompressing() {
  2080. return timeCompressing;
  2081. }
  2082. /**
  2083. * @return time in milliseconds spent writing the pack output, from
  2084. * start of header until end of trailer. The transfer speed can
  2085. * be approximated by dividing {@link #getTotalBytes()} by this
  2086. * value.
  2087. */
  2088. public long getTimeWriting() {
  2089. return timeWriting;
  2090. }
  2091. /** @return total time spent processing this pack. */
  2092. public long getTimeTotal() {
  2093. return timeCounting
  2094. + timeSearchingForReuse
  2095. + timeSearchingForSizes
  2096. + timeCompressing
  2097. + timeWriting;
  2098. }
  2099. /**
  2100. * @return get the average output speed in terms of bytes-per-second.
  2101. * {@code getTotalBytes() / (getTimeWriting() / 1000.0)}.
  2102. */
  2103. public double getTransferRate() {
  2104. return getTotalBytes() / (getTimeWriting() / 1000.0);
  2105. }
  2106. /** @return formatted message string for display to clients. */
  2107. public String getMessage() {
  2108. return MessageFormat.format(JGitText.get().packWriterStatistics, //
  2109. Long.valueOf(totalObjects), Long.valueOf(totalDeltas), //
  2110. Long.valueOf(reusedObjects), Long.valueOf(reusedDeltas));
  2111. }
  2112. }
  2113. private class MutableState {
  2114. /** Estimated size of a single ObjectToPack instance. */
  2115. // Assume 64-bit pointers, since this is just an estimate.
  2116. private static final long OBJECT_TO_PACK_SIZE =
  2117. (2 * 8) // Object header
  2118. + (2 * 8) + (2 * 8) // ObjectToPack fields
  2119. + (8 + 8) // PackedObjectInfo fields
  2120. + 8 // ObjectIdOwnerMap fields
  2121. + 40 // AnyObjectId fields
  2122. + 8; // Reference in BlockList
  2123. private final long totalDeltaSearchBytes;
  2124. private volatile PackingPhase phase;
  2125. MutableState() {
  2126. phase = PackingPhase.COUNTING;
  2127. if (config.isDeltaCompress()) {
  2128. int threads = config.getThreads();
  2129. if (threads <= 0)
  2130. threads = Runtime.getRuntime().availableProcessors();
  2131. totalDeltaSearchBytes = (threads * config.getDeltaSearchMemoryLimit())
  2132. + config.getBigFileThreshold();
  2133. } else
  2134. totalDeltaSearchBytes = 0;
  2135. }
  2136. State snapshot() {
  2137. long objCnt = 0;
  2138. objCnt += objectsLists[OBJ_COMMIT].size();
  2139. objCnt += objectsLists[OBJ_TREE].size();
  2140. objCnt += objectsLists[OBJ_BLOB].size();
  2141. objCnt += objectsLists[OBJ_TAG].size();
  2142. // Exclude CachedPacks.
  2143. long bytesUsed = OBJECT_TO_PACK_SIZE * objCnt;
  2144. PackingPhase curr = phase;
  2145. if (curr == PackingPhase.COMPRESSING)
  2146. bytesUsed += totalDeltaSearchBytes;
  2147. return new State(curr, bytesUsed);
  2148. }
  2149. }
  2150. /** Possible states that a PackWriter can be in. */
  2151. public static enum PackingPhase {
  2152. /** Counting objects phase. */
  2153. COUNTING,
  2154. /** Getting sizes phase. */
  2155. GETTING_SIZES,
  2156. /** Finding sources phase. */
  2157. FINDING_SOURCES,
  2158. /** Compressing objects phase. */
  2159. COMPRESSING,
  2160. /** Writing objects phase. */
  2161. WRITING,
  2162. /** Building bitmaps phase. */
  2163. BUILDING_BITMAPS;
  2164. }
  2165. /** Summary of the current state of a PackWriter. */
  2166. public class State {
  2167. private final PackingPhase phase;
  2168. private final long bytesUsed;
  2169. State(PackingPhase phase, long bytesUsed) {
  2170. this.phase = phase;
  2171. this.bytesUsed = bytesUsed;
  2172. }
  2173. /** @return the PackConfig used to build the writer. */
  2174. public PackConfig getConfig() {
  2175. return config;
  2176. }
  2177. /** @return the current phase of the writer. */
  2178. public PackingPhase getPhase() {
  2179. return phase;
  2180. }
  2181. /** @return an estimate of the total memory used by the writer. */
  2182. public long estimateBytesUsed() {
  2183. return bytesUsed;
  2184. }
  2185. @SuppressWarnings("nls")
  2186. @Override
  2187. public String toString() {
  2188. return "PackWriter.State[" + phase + ", memory=" + bytesUsed + "]";
  2189. }
  2190. }
  2191. }