Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

PackWriter.java 75KB

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