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

PackWriter.java 76KB

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