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

PackWriter.java 75KB

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