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

PackWriter.java 74KB

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