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 72KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410
  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, Set, Set)}, and finally producing the
  135. * 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 implements AutoCloseable {
  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, Set, Set)}.
  250. *
  251. * @param repo
  252. * repository where objects are stored.
  253. */
  254. public PackWriter(final Repository repo) {
  255. this(repo, repo.newObjectReader());
  256. }
  257. /**
  258. * Create a writer to load objects from the specified reader.
  259. * <p>
  260. * Objects for packing are specified in {@link #preparePack(Iterator)} or
  261. * {@link #preparePack(ProgressMonitor, Set, Set)}.
  262. *
  263. * @param reader
  264. * reader to read from the repository with.
  265. */
  266. public PackWriter(final ObjectReader reader) {
  267. this(new PackConfig(), reader);
  268. }
  269. /**
  270. * Create writer for specified repository.
  271. * <p>
  272. * Objects for packing are specified in {@link #preparePack(Iterator)} or
  273. * {@link #preparePack(ProgressMonitor, Set, Set)}.
  274. *
  275. * @param repo
  276. * repository where objects are stored.
  277. * @param reader
  278. * reader to read from the repository with.
  279. */
  280. public PackWriter(final Repository repo, final ObjectReader reader) {
  281. this(new PackConfig(repo), reader);
  282. }
  283. /**
  284. * Create writer with a specified configuration.
  285. * <p>
  286. * Objects for packing are specified in {@link #preparePack(Iterator)} or
  287. * {@link #preparePack(ProgressMonitor, Set, Set)}.
  288. *
  289. * @param config
  290. * configuration for the pack writer.
  291. * @param reader
  292. * reader to read from the repository with.
  293. */
  294. public PackWriter(final PackConfig config, final ObjectReader reader) {
  295. this.config = config;
  296. this.reader = reader;
  297. if (reader instanceof ObjectReuseAsIs)
  298. reuseSupport = ((ObjectReuseAsIs) reader);
  299. else
  300. reuseSupport = null;
  301. deltaBaseAsOffset = config.isDeltaBaseAsOffset();
  302. reuseDeltas = config.isReuseDeltas();
  303. reuseValidate = true; // be paranoid by default
  304. stats = new 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, Set, Set)} 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. */
  597. public void preparePack(ProgressMonitor countingMonitor,
  598. Set<? extends ObjectId> want,
  599. Set<? extends ObjectId> have) throws IOException {
  600. ObjectWalk ow;
  601. if (shallowPack)
  602. ow = new DepthWalk.ObjectWalk(reader, depth);
  603. else
  604. ow = new ObjectWalk(reader);
  605. preparePack(countingMonitor, ow, want, have);
  606. }
  607. /**
  608. * Prepare the list of objects to be written to the pack stream.
  609. * <p>
  610. * Basing on these 2 sets, another set of objects to put in a pack file is
  611. * created: this set consists of all objects reachable (ancestors) from
  612. * interesting objects, except uninteresting objects and their ancestors.
  613. * This method uses class {@link ObjectWalk} extensively to find out that
  614. * appropriate set of output objects and their optimal order in output pack.
  615. * Order is consistent with general git in-pack rules: sort by object type,
  616. * recency, path and delta-base first.
  617. * </p>
  618. *
  619. * @param countingMonitor
  620. * progress during object enumeration.
  621. * @param walk
  622. * ObjectWalk to perform enumeration.
  623. * @param interestingObjects
  624. * collection of objects to be marked as interesting (start
  625. * points of graph traversal).
  626. * @param uninterestingObjects
  627. * collection of objects to be marked as uninteresting (end
  628. * points of graph traversal).
  629. * @throws IOException
  630. * when some I/O problem occur during reading objects.
  631. */
  632. public void preparePack(ProgressMonitor countingMonitor,
  633. ObjectWalk walk,
  634. final Set<? extends ObjectId> interestingObjects,
  635. final Set<? extends ObjectId> uninterestingObjects)
  636. throws IOException {
  637. if (countingMonitor == null)
  638. countingMonitor = NullProgressMonitor.INSTANCE;
  639. if (shallowPack && !(walk instanceof DepthWalk.ObjectWalk))
  640. walk = new DepthWalk.ObjectWalk(reader, depth);
  641. findObjectsToPack(countingMonitor, walk, interestingObjects,
  642. uninterestingObjects);
  643. }
  644. /**
  645. * Determine if the pack file will contain the requested object.
  646. *
  647. * @param id
  648. * the object to test the existence of.
  649. * @return true if the object will appear in the output pack file.
  650. * @throws IOException
  651. * a cached pack cannot be examined.
  652. */
  653. public boolean willInclude(final AnyObjectId id) throws IOException {
  654. ObjectToPack obj = objectsMap.get(id);
  655. return obj != null && !obj.isEdge();
  656. }
  657. /**
  658. * Lookup the ObjectToPack object for a given ObjectId.
  659. *
  660. * @param id
  661. * the object to find in the pack.
  662. * @return the object we are packing, or null.
  663. */
  664. public ObjectToPack get(AnyObjectId id) {
  665. ObjectToPack obj = objectsMap.get(id);
  666. return obj != null && !obj.isEdge() ? obj : null;
  667. }
  668. /**
  669. * Computes SHA-1 of lexicographically sorted objects ids written in this
  670. * pack, as used to name a pack file in repository.
  671. *
  672. * @return ObjectId representing SHA-1 name of a pack that was created.
  673. */
  674. public ObjectId computeName() {
  675. final byte[] buf = new byte[OBJECT_ID_LENGTH];
  676. final MessageDigest md = Constants.newMessageDigest();
  677. for (ObjectToPack otp : sortByName()) {
  678. otp.copyRawTo(buf, 0);
  679. md.update(buf, 0, OBJECT_ID_LENGTH);
  680. }
  681. return ObjectId.fromRaw(md.digest());
  682. }
  683. /**
  684. * Returns the index format version that will be written.
  685. * <p>
  686. * This method can only be invoked after
  687. * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)} has
  688. * been invoked and completed successfully.
  689. *
  690. * @return the index format version.
  691. */
  692. public int getIndexVersion() {
  693. int indexVersion = config.getIndexVersion();
  694. if (indexVersion <= 0) {
  695. for (BlockList<ObjectToPack> objs : objectsLists)
  696. indexVersion = Math.max(indexVersion,
  697. PackIndexWriter.oldestPossibleFormat(objs));
  698. }
  699. return indexVersion;
  700. }
  701. /**
  702. * Create an index file to match the pack file just written.
  703. * <p>
  704. * This method can only be invoked after
  705. * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)} has
  706. * been invoked and completed successfully. Writing a corresponding index is
  707. * an optional feature that not all pack users may require.
  708. *
  709. * @param indexStream
  710. * output for the index data. Caller is responsible for closing
  711. * this stream.
  712. * @throws IOException
  713. * the index data could not be written to the supplied stream.
  714. */
  715. public void writeIndex(final OutputStream indexStream) throws IOException {
  716. if (isIndexDisabled())
  717. throw new IOException(JGitText.get().cachedPacksPreventsIndexCreation);
  718. long writeStart = System.currentTimeMillis();
  719. final PackIndexWriter iw = PackIndexWriter.createVersion(
  720. indexStream, getIndexVersion());
  721. iw.write(sortByName(), packcsum);
  722. stats.timeWriting += System.currentTimeMillis() - writeStart;
  723. }
  724. /**
  725. * Create a bitmap index file to match the pack file just written.
  726. * <p>
  727. * This method can only be invoked after
  728. * {@link #prepareBitmapIndex(ProgressMonitor)} has been invoked and
  729. * completed successfully. Writing a corresponding bitmap index is an
  730. * optional feature that not all pack users may require.
  731. *
  732. * @param bitmapIndexStream
  733. * output for the bitmap index data. Caller is responsible for
  734. * closing this stream.
  735. * @throws IOException
  736. * the index data could not be written to the supplied stream.
  737. */
  738. public void writeBitmapIndex(final OutputStream bitmapIndexStream)
  739. throws IOException {
  740. if (writeBitmaps == null)
  741. throw new IOException(JGitText.get().bitmapsMustBePrepared);
  742. long writeStart = System.currentTimeMillis();
  743. final PackBitmapIndexWriterV1 iw = new PackBitmapIndexWriterV1(bitmapIndexStream);
  744. iw.write(writeBitmaps, packcsum);
  745. stats.timeWriting += System.currentTimeMillis() - writeStart;
  746. }
  747. private List<ObjectToPack> sortByName() {
  748. if (sortedByName == null) {
  749. int cnt = 0;
  750. cnt += objectsLists[OBJ_COMMIT].size();
  751. cnt += objectsLists[OBJ_TREE].size();
  752. cnt += objectsLists[OBJ_BLOB].size();
  753. cnt += objectsLists[OBJ_TAG].size();
  754. sortedByName = new BlockList<ObjectToPack>(cnt);
  755. sortedByName.addAll(objectsLists[OBJ_COMMIT]);
  756. sortedByName.addAll(objectsLists[OBJ_TREE]);
  757. sortedByName.addAll(objectsLists[OBJ_BLOB]);
  758. sortedByName.addAll(objectsLists[OBJ_TAG]);
  759. Collections.sort(sortedByName);
  760. }
  761. return sortedByName;
  762. }
  763. private void beginPhase(PackingPhase phase, ProgressMonitor monitor,
  764. long cnt) {
  765. state.phase = phase;
  766. String task;
  767. switch (phase) {
  768. case COUNTING:
  769. task = JGitText.get().countingObjects;
  770. break;
  771. case GETTING_SIZES:
  772. task = JGitText.get().searchForSizes;
  773. break;
  774. case FINDING_SOURCES:
  775. task = JGitText.get().searchForReuse;
  776. break;
  777. case COMPRESSING:
  778. task = JGitText.get().compressingObjects;
  779. break;
  780. case WRITING:
  781. task = JGitText.get().writingObjects;
  782. break;
  783. case BUILDING_BITMAPS:
  784. task = JGitText.get().buildingBitmaps;
  785. break;
  786. default:
  787. throw new IllegalArgumentException(
  788. MessageFormat.format(JGitText.get().illegalPackingPhase, phase));
  789. }
  790. monitor.beginTask(task, (int) cnt);
  791. }
  792. private void endPhase(ProgressMonitor monitor) {
  793. monitor.endTask();
  794. }
  795. /**
  796. * Write the prepared pack to the supplied stream.
  797. * <p>
  798. * At first, this method collects and sorts objects to pack, then deltas
  799. * search is performed if set up accordingly, finally pack stream is
  800. * written.
  801. * </p>
  802. * <p>
  803. * All reused objects data checksum (Adler32/CRC32) is computed and
  804. * validated against existing checksum.
  805. * </p>
  806. *
  807. * @param compressMonitor
  808. * progress monitor to report object compression work.
  809. * @param writeMonitor
  810. * progress monitor to report the number of objects written.
  811. * @param packStream
  812. * output stream of pack data. The stream should be buffered by
  813. * the caller. The caller is responsible for closing the stream.
  814. * @throws IOException
  815. * an error occurred reading a local object's data to include in
  816. * the pack, or writing compressed object data to the output
  817. * stream.
  818. */
  819. public void writePack(ProgressMonitor compressMonitor,
  820. ProgressMonitor writeMonitor, OutputStream packStream)
  821. throws IOException {
  822. if (compressMonitor == null)
  823. compressMonitor = NullProgressMonitor.INSTANCE;
  824. if (writeMonitor == null)
  825. writeMonitor = NullProgressMonitor.INSTANCE;
  826. excludeInPacks = null;
  827. excludeInPackLast = null;
  828. boolean needSearchForReuse = reuseSupport != null && (
  829. reuseDeltas
  830. || config.isReuseObjects()
  831. || !cachedPacks.isEmpty());
  832. if (compressMonitor instanceof BatchingProgressMonitor) {
  833. long delay = 1000;
  834. if (needSearchForReuse && config.isDeltaCompress())
  835. delay = 500;
  836. ((BatchingProgressMonitor) compressMonitor).setDelayStart(
  837. delay,
  838. TimeUnit.MILLISECONDS);
  839. }
  840. if (needSearchForReuse)
  841. searchForReuse(compressMonitor);
  842. if (config.isDeltaCompress())
  843. searchForDeltas(compressMonitor);
  844. crc32 = new CRC32();
  845. final PackOutputStream out = new PackOutputStream(
  846. writeMonitor,
  847. isIndexDisabled()
  848. ? packStream
  849. : new CheckedOutputStream(packStream, crc32),
  850. this);
  851. long objCnt = getObjectCount();
  852. stats.totalObjects = objCnt;
  853. beginPhase(PackingPhase.WRITING, writeMonitor, objCnt);
  854. long writeStart = System.currentTimeMillis();
  855. try {
  856. out.writeFileHeader(PACK_VERSION_GENERATED, objCnt);
  857. out.flush();
  858. writeObjects(out);
  859. if (!edgeObjects.isEmpty() || !cachedPacks.isEmpty()) {
  860. for (Statistics.ObjectType typeStat : stats.objectTypes) {
  861. if (typeStat == null)
  862. continue;
  863. stats.thinPackBytes += typeStat.bytes;
  864. }
  865. }
  866. stats.reusedPacks = Collections.unmodifiableList(cachedPacks);
  867. for (CachedPack pack : cachedPacks) {
  868. long deltaCnt = pack.getDeltaCount();
  869. stats.reusedObjects += pack.getObjectCount();
  870. stats.reusedDeltas += deltaCnt;
  871. stats.totalDeltas += deltaCnt;
  872. reuseSupport.copyPackAsIs(out, pack);
  873. }
  874. writeChecksum(out);
  875. out.flush();
  876. } finally {
  877. stats.timeWriting = System.currentTimeMillis() - writeStart;
  878. stats.depth = depth;
  879. for (Statistics.ObjectType typeStat : stats.objectTypes) {
  880. if (typeStat == null)
  881. continue;
  882. typeStat.cntDeltas += typeStat.reusedDeltas;
  883. stats.reusedObjects += typeStat.reusedObjects;
  884. stats.reusedDeltas += typeStat.reusedDeltas;
  885. stats.totalDeltas += typeStat.cntDeltas;
  886. }
  887. }
  888. stats.totalBytes = out.length();
  889. reader.close();
  890. endPhase(writeMonitor);
  891. }
  892. /**
  893. * @return description of what this PackWriter did in order to create the
  894. * final pack stream. The object is only available to callers after
  895. * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)}
  896. */
  897. public Statistics getStatistics() {
  898. return stats;
  899. }
  900. /** @return snapshot of the current state of this PackWriter. */
  901. public State getState() {
  902. return state.snapshot();
  903. }
  904. /**
  905. * Release all resources used by this writer. Use {@link #close()} instead.
  906. */
  907. @Deprecated
  908. public void release() {
  909. close();
  910. }
  911. /**
  912. * Release all resources used by this writer.
  913. *
  914. * @since 4.0
  915. */
  916. @Override
  917. public void close() {
  918. reader.close();
  919. if (myDeflater != null) {
  920. myDeflater.end();
  921. myDeflater = null;
  922. }
  923. instances.remove(selfRef);
  924. }
  925. private void searchForReuse(ProgressMonitor monitor) throws IOException {
  926. long cnt = 0;
  927. cnt += objectsLists[OBJ_COMMIT].size();
  928. cnt += objectsLists[OBJ_TREE].size();
  929. cnt += objectsLists[OBJ_BLOB].size();
  930. cnt += objectsLists[OBJ_TAG].size();
  931. long start = System.currentTimeMillis();
  932. beginPhase(PackingPhase.FINDING_SOURCES, monitor, cnt);
  933. if (cnt <= 4096) {
  934. // For small object counts, do everything as one list.
  935. BlockList<ObjectToPack> tmp = new BlockList<ObjectToPack>((int) cnt);
  936. tmp.addAll(objectsLists[OBJ_TAG]);
  937. tmp.addAll(objectsLists[OBJ_COMMIT]);
  938. tmp.addAll(objectsLists[OBJ_TREE]);
  939. tmp.addAll(objectsLists[OBJ_BLOB]);
  940. searchForReuse(monitor, tmp);
  941. if (pruneCurrentObjectList) {
  942. // If the list was pruned, we need to re-prune the main lists.
  943. pruneEdgesFromObjectList(objectsLists[OBJ_COMMIT]);
  944. pruneEdgesFromObjectList(objectsLists[OBJ_TREE]);
  945. pruneEdgesFromObjectList(objectsLists[OBJ_BLOB]);
  946. pruneEdgesFromObjectList(objectsLists[OBJ_TAG]);
  947. }
  948. } else {
  949. searchForReuse(monitor, objectsLists[OBJ_TAG]);
  950. searchForReuse(monitor, objectsLists[OBJ_COMMIT]);
  951. searchForReuse(monitor, objectsLists[OBJ_TREE]);
  952. searchForReuse(monitor, objectsLists[OBJ_BLOB]);
  953. }
  954. endPhase(monitor);
  955. stats.timeSearchingForReuse = System.currentTimeMillis() - start;
  956. if (config.isReuseDeltas() && config.getCutDeltaChains()) {
  957. cutDeltaChains(objectsLists[OBJ_TREE]);
  958. cutDeltaChains(objectsLists[OBJ_BLOB]);
  959. }
  960. }
  961. private void searchForReuse(ProgressMonitor monitor, List<ObjectToPack> list)
  962. throws IOException, MissingObjectException {
  963. pruneCurrentObjectList = false;
  964. reuseSupport.selectObjectRepresentation(this, monitor, list);
  965. if (pruneCurrentObjectList)
  966. pruneEdgesFromObjectList(list);
  967. }
  968. private void cutDeltaChains(BlockList<ObjectToPack> list)
  969. throws IOException {
  970. int max = config.getMaxDeltaDepth();
  971. for (int idx = list.size() - 1; idx >= 0; idx--) {
  972. int d = 0;
  973. ObjectToPack b = list.get(idx).getDeltaBase();
  974. while (b != null) {
  975. if (d < b.getChainLength())
  976. break;
  977. b.setChainLength(++d);
  978. if (d >= max && b.isDeltaRepresentation()) {
  979. reselectNonDelta(b);
  980. break;
  981. }
  982. b = b.getDeltaBase();
  983. }
  984. }
  985. if (config.isDeltaCompress()) {
  986. for (ObjectToPack otp : list)
  987. otp.clearChainLength();
  988. }
  989. }
  990. private void searchForDeltas(ProgressMonitor monitor)
  991. throws MissingObjectException, IncorrectObjectTypeException,
  992. IOException {
  993. // Commits and annotated tags tend to have too many differences to
  994. // really benefit from delta compression. Consequently just don't
  995. // bother examining those types here.
  996. //
  997. ObjectToPack[] list = new ObjectToPack[
  998. objectsLists[OBJ_TREE].size()
  999. + objectsLists[OBJ_BLOB].size()
  1000. + edgeObjects.size()];
  1001. int cnt = 0;
  1002. cnt = findObjectsNeedingDelta(list, cnt, OBJ_TREE);
  1003. cnt = findObjectsNeedingDelta(list, cnt, OBJ_BLOB);
  1004. if (cnt == 0)
  1005. return;
  1006. int nonEdgeCnt = cnt;
  1007. // Queue up any edge objects that we might delta against. We won't
  1008. // be sending these as we assume the other side has them, but we need
  1009. // them in the search phase below.
  1010. //
  1011. for (ObjectToPack eo : edgeObjects) {
  1012. eo.setWeight(0);
  1013. list[cnt++] = eo;
  1014. }
  1015. // Compute the sizes of the objects so we can do a proper sort.
  1016. // We let the reader skip missing objects if it chooses. For
  1017. // some readers this can be a huge win. We detect missing objects
  1018. // by having set the weights above to 0 and allowing the delta
  1019. // search code to discover the missing object and skip over it, or
  1020. // abort with an exception if we actually had to have it.
  1021. //
  1022. final long sizingStart = System.currentTimeMillis();
  1023. beginPhase(PackingPhase.GETTING_SIZES, monitor, cnt);
  1024. AsyncObjectSizeQueue<ObjectToPack> sizeQueue = reader.getObjectSize(
  1025. Arrays.<ObjectToPack> asList(list).subList(0, cnt), false);
  1026. try {
  1027. final long limit = Math.min(
  1028. config.getBigFileThreshold(),
  1029. Integer.MAX_VALUE);
  1030. for (;;) {
  1031. try {
  1032. if (!sizeQueue.next())
  1033. break;
  1034. } catch (MissingObjectException notFound) {
  1035. monitor.update(1);
  1036. if (ignoreMissingUninteresting) {
  1037. ObjectToPack otp = sizeQueue.getCurrent();
  1038. if (otp != null && otp.isEdge()) {
  1039. otp.setDoNotDelta();
  1040. continue;
  1041. }
  1042. otp = objectsMap.get(notFound.getObjectId());
  1043. if (otp != null && otp.isEdge()) {
  1044. otp.setDoNotDelta();
  1045. continue;
  1046. }
  1047. }
  1048. throw notFound;
  1049. }
  1050. ObjectToPack otp = sizeQueue.getCurrent();
  1051. if (otp == null)
  1052. otp = objectsMap.get(sizeQueue.getObjectId());
  1053. long sz = sizeQueue.getSize();
  1054. if (DeltaIndex.BLKSZ < sz && sz < limit)
  1055. otp.setWeight((int) sz);
  1056. else
  1057. otp.setDoNotDelta(); // too small, or too big
  1058. monitor.update(1);
  1059. }
  1060. } finally {
  1061. sizeQueue.release();
  1062. }
  1063. endPhase(monitor);
  1064. stats.timeSearchingForSizes = System.currentTimeMillis() - sizingStart;
  1065. // Sort the objects by path hash so like files are near each other,
  1066. // and then by size descending so that bigger files are first. This
  1067. // applies "Linus' Law" which states that newer files tend to be the
  1068. // bigger ones, because source files grow and hardly ever shrink.
  1069. //
  1070. Arrays.sort(list, 0, cnt, new Comparator<ObjectToPack>() {
  1071. public int compare(ObjectToPack a, ObjectToPack b) {
  1072. int cmp = (a.isDoNotDelta() ? 1 : 0)
  1073. - (b.isDoNotDelta() ? 1 : 0);
  1074. if (cmp != 0)
  1075. return cmp;
  1076. cmp = a.getType() - b.getType();
  1077. if (cmp != 0)
  1078. return cmp;
  1079. cmp = (a.getPathHash() >>> 1) - (b.getPathHash() >>> 1);
  1080. if (cmp != 0)
  1081. return cmp;
  1082. cmp = (a.getPathHash() & 1) - (b.getPathHash() & 1);
  1083. if (cmp != 0)
  1084. return cmp;
  1085. cmp = (a.isEdge() ? 0 : 1) - (b.isEdge() ? 0 : 1);
  1086. if (cmp != 0)
  1087. return cmp;
  1088. return b.getWeight() - a.getWeight();
  1089. }
  1090. });
  1091. // Above we stored the objects we cannot delta onto the end.
  1092. // Remove them from the list so we don't waste time on them.
  1093. while (0 < cnt && list[cnt - 1].isDoNotDelta()) {
  1094. if (!list[cnt - 1].isEdge())
  1095. nonEdgeCnt--;
  1096. cnt--;
  1097. }
  1098. if (cnt == 0)
  1099. return;
  1100. final long searchStart = System.currentTimeMillis();
  1101. searchForDeltas(monitor, list, cnt);
  1102. stats.deltaSearchNonEdgeObjects = nonEdgeCnt;
  1103. stats.timeCompressing = System.currentTimeMillis() - searchStart;
  1104. for (int i = 0; i < cnt; i++)
  1105. if (!list[i].isEdge() && list[i].isDeltaRepresentation())
  1106. stats.deltasFound++;
  1107. }
  1108. private int findObjectsNeedingDelta(ObjectToPack[] list, int cnt, int type) {
  1109. for (ObjectToPack otp : objectsLists[type]) {
  1110. if (otp.isDoNotDelta()) // delta is disabled for this path
  1111. continue;
  1112. if (otp.isDeltaRepresentation()) // already reusing a delta
  1113. continue;
  1114. otp.setWeight(0);
  1115. list[cnt++] = otp;
  1116. }
  1117. return cnt;
  1118. }
  1119. private void reselectNonDelta(ObjectToPack otp) throws IOException {
  1120. otp.clearDeltaBase();
  1121. otp.clearReuseAsIs();
  1122. boolean old = reuseDeltas;
  1123. reuseDeltas = false;
  1124. reuseSupport.selectObjectRepresentation(this,
  1125. NullProgressMonitor.INSTANCE,
  1126. Collections.singleton(otp));
  1127. reuseDeltas = old;
  1128. }
  1129. private void searchForDeltas(final ProgressMonitor monitor,
  1130. final ObjectToPack[] list, final int cnt)
  1131. throws MissingObjectException, IncorrectObjectTypeException,
  1132. LargeObjectException, IOException {
  1133. int threads = config.getThreads();
  1134. if (threads == 0)
  1135. threads = Runtime.getRuntime().availableProcessors();
  1136. if (threads <= 1 || cnt <= config.getDeltaSearchWindowSize())
  1137. singleThreadDeltaSearch(monitor, list, cnt);
  1138. else
  1139. parallelDeltaSearch(monitor, list, cnt, threads);
  1140. }
  1141. private void singleThreadDeltaSearch(ProgressMonitor monitor,
  1142. ObjectToPack[] list, int cnt) throws IOException {
  1143. long totalWeight = 0;
  1144. for (int i = 0; i < cnt; i++) {
  1145. ObjectToPack o = list[i];
  1146. if (!o.isEdge() && !o.doNotAttemptDelta())
  1147. totalWeight += o.getWeight();
  1148. }
  1149. long bytesPerUnit = 1;
  1150. while (DeltaTask.MAX_METER <= (totalWeight / bytesPerUnit))
  1151. bytesPerUnit <<= 10;
  1152. int cost = (int) (totalWeight / bytesPerUnit);
  1153. if (totalWeight % bytesPerUnit != 0)
  1154. cost++;
  1155. beginPhase(PackingPhase.COMPRESSING, monitor, cost);
  1156. new DeltaWindow(config, new DeltaCache(config), reader,
  1157. monitor, bytesPerUnit,
  1158. list, 0, cnt).search();
  1159. endPhase(monitor);
  1160. }
  1161. private void parallelDeltaSearch(ProgressMonitor monitor,
  1162. ObjectToPack[] list, int cnt, int threads) throws IOException {
  1163. DeltaCache dc = new ThreadSafeDeltaCache(config);
  1164. ThreadSafeProgressMonitor pm = new ThreadSafeProgressMonitor(monitor);
  1165. DeltaTask.Block taskBlock = new DeltaTask.Block(threads, config,
  1166. reader, dc, pm,
  1167. list, 0, cnt);
  1168. taskBlock.partitionTasks();
  1169. beginPhase(PackingPhase.COMPRESSING, monitor, taskBlock.cost());
  1170. pm.startWorkers(taskBlock.tasks.size());
  1171. Executor executor = config.getExecutor();
  1172. final List<Throwable> errors =
  1173. Collections.synchronizedList(new ArrayList<Throwable>(threads));
  1174. if (executor instanceof ExecutorService) {
  1175. // Caller supplied us a service, use it directly.
  1176. runTasks((ExecutorService) executor, pm, taskBlock, errors);
  1177. } else if (executor == null) {
  1178. // Caller didn't give us a way to run the tasks, spawn up a
  1179. // temporary thread pool and make sure it tears down cleanly.
  1180. ExecutorService pool = Executors.newFixedThreadPool(threads);
  1181. try {
  1182. runTasks(pool, pm, taskBlock, errors);
  1183. } finally {
  1184. pool.shutdown();
  1185. for (;;) {
  1186. try {
  1187. if (pool.awaitTermination(60, TimeUnit.SECONDS))
  1188. break;
  1189. } catch (InterruptedException e) {
  1190. throw new IOException(
  1191. JGitText.get().packingCancelledDuringObjectsWriting);
  1192. }
  1193. }
  1194. }
  1195. } else {
  1196. // The caller gave us an executor, but it might not do
  1197. // asynchronous execution. Wrap everything and hope it
  1198. // can schedule these for us.
  1199. for (final DeltaTask task : taskBlock.tasks) {
  1200. executor.execute(new Runnable() {
  1201. public void run() {
  1202. try {
  1203. task.call();
  1204. } catch (Throwable failure) {
  1205. errors.add(failure);
  1206. }
  1207. }
  1208. });
  1209. }
  1210. try {
  1211. pm.waitForCompletion();
  1212. } catch (InterruptedException ie) {
  1213. // We can't abort the other tasks as we have no handle.
  1214. // Cross our fingers and just break out anyway.
  1215. //
  1216. throw new IOException(
  1217. JGitText.get().packingCancelledDuringObjectsWriting);
  1218. }
  1219. }
  1220. // If any task threw an error, try to report it back as
  1221. // though we weren't using a threaded search algorithm.
  1222. //
  1223. if (!errors.isEmpty()) {
  1224. Throwable err = errors.get(0);
  1225. if (err instanceof Error)
  1226. throw (Error) err;
  1227. if (err instanceof RuntimeException)
  1228. throw (RuntimeException) err;
  1229. if (err instanceof IOException)
  1230. throw (IOException) err;
  1231. IOException fail = new IOException(err.getMessage());
  1232. fail.initCause(err);
  1233. throw fail;
  1234. }
  1235. endPhase(monitor);
  1236. }
  1237. private static void runTasks(ExecutorService pool,
  1238. ThreadSafeProgressMonitor pm,
  1239. DeltaTask.Block tb, List<Throwable> errors) throws IOException {
  1240. List<Future<?>> futures = new ArrayList<Future<?>>(tb.tasks.size());
  1241. for (DeltaTask task : tb.tasks)
  1242. futures.add(pool.submit(task));
  1243. try {
  1244. pm.waitForCompletion();
  1245. for (Future<?> f : futures) {
  1246. try {
  1247. f.get();
  1248. } catch (ExecutionException failed) {
  1249. errors.add(failed.getCause());
  1250. }
  1251. }
  1252. } catch (InterruptedException ie) {
  1253. for (Future<?> f : futures)
  1254. f.cancel(true);
  1255. throw new IOException(
  1256. JGitText.get().packingCancelledDuringObjectsWriting);
  1257. }
  1258. }
  1259. private void writeObjects(PackOutputStream out) throws IOException {
  1260. writeObjects(out, objectsLists[OBJ_COMMIT]);
  1261. writeObjects(out, objectsLists[OBJ_TAG]);
  1262. writeObjects(out, objectsLists[OBJ_TREE]);
  1263. writeObjects(out, objectsLists[OBJ_BLOB]);
  1264. }
  1265. private void writeObjects(PackOutputStream out, List<ObjectToPack> list)
  1266. throws IOException {
  1267. if (list.isEmpty())
  1268. return;
  1269. typeStats = stats.objectTypes[list.get(0).getType()];
  1270. long beginOffset = out.length();
  1271. if (reuseSupport != null) {
  1272. reuseSupport.writeObjects(out, list);
  1273. } else {
  1274. for (ObjectToPack otp : list)
  1275. out.writeObject(otp);
  1276. }
  1277. typeStats.bytes += out.length() - beginOffset;
  1278. typeStats.cntObjects = list.size();
  1279. }
  1280. void writeObject(PackOutputStream out, ObjectToPack otp) throws IOException {
  1281. if (!otp.isWritten())
  1282. writeObjectImpl(out, otp);
  1283. }
  1284. private void writeObjectImpl(PackOutputStream out, ObjectToPack otp)
  1285. throws IOException {
  1286. if (otp.wantWrite()) {
  1287. // A cycle exists in this delta chain. This should only occur if a
  1288. // selected object representation disappeared during writing
  1289. // (for example due to a concurrent repack) and a different base
  1290. // was chosen, forcing a cycle. Select something other than a
  1291. // delta, and write this object.
  1292. reselectNonDelta(otp);
  1293. }
  1294. otp.markWantWrite();
  1295. while (otp.isReuseAsIs()) {
  1296. writeBase(out, otp.getDeltaBase());
  1297. if (otp.isWritten())
  1298. return; // Delta chain cycle caused this to write already.
  1299. crc32.reset();
  1300. otp.setOffset(out.length());
  1301. try {
  1302. reuseSupport.copyObjectAsIs(out, otp, reuseValidate);
  1303. out.endObject();
  1304. otp.setCRC((int) crc32.getValue());
  1305. typeStats.reusedObjects++;
  1306. if (otp.isDeltaRepresentation()) {
  1307. typeStats.reusedDeltas++;
  1308. typeStats.deltaBytes += out.length() - otp.getOffset();
  1309. }
  1310. return;
  1311. } catch (StoredObjectRepresentationNotAvailableException gone) {
  1312. if (otp.getOffset() == out.length()) {
  1313. otp.setOffset(0);
  1314. otp.clearDeltaBase();
  1315. otp.clearReuseAsIs();
  1316. reuseSupport.selectObjectRepresentation(this,
  1317. NullProgressMonitor.INSTANCE,
  1318. Collections.singleton(otp));
  1319. continue;
  1320. } else {
  1321. // Object writing already started, we cannot recover.
  1322. //
  1323. CorruptObjectException coe;
  1324. coe = new CorruptObjectException(otp, ""); //$NON-NLS-1$
  1325. coe.initCause(gone);
  1326. throw coe;
  1327. }
  1328. }
  1329. }
  1330. // If we reached here, reuse wasn't possible.
  1331. //
  1332. if (otp.isDeltaRepresentation())
  1333. writeDeltaObjectDeflate(out, otp);
  1334. else
  1335. writeWholeObjectDeflate(out, otp);
  1336. out.endObject();
  1337. otp.setCRC((int) crc32.getValue());
  1338. }
  1339. private void writeBase(PackOutputStream out, ObjectToPack base)
  1340. throws IOException {
  1341. if (base != null && !base.isWritten() && !base.isEdge())
  1342. writeObjectImpl(out, base);
  1343. }
  1344. private void writeWholeObjectDeflate(PackOutputStream out,
  1345. final ObjectToPack otp) throws IOException {
  1346. final Deflater deflater = deflater();
  1347. final ObjectLoader ldr = reader.open(otp, otp.getType());
  1348. crc32.reset();
  1349. otp.setOffset(out.length());
  1350. out.writeHeader(otp, ldr.getSize());
  1351. deflater.reset();
  1352. DeflaterOutputStream dst = new DeflaterOutputStream(out, deflater);
  1353. ldr.copyTo(dst);
  1354. dst.finish();
  1355. }
  1356. private void writeDeltaObjectDeflate(PackOutputStream out,
  1357. final ObjectToPack otp) throws IOException {
  1358. writeBase(out, otp.getDeltaBase());
  1359. crc32.reset();
  1360. otp.setOffset(out.length());
  1361. DeltaCache.Ref ref = otp.popCachedDelta();
  1362. if (ref != null) {
  1363. byte[] zbuf = ref.get();
  1364. if (zbuf != null) {
  1365. out.writeHeader(otp, otp.getCachedSize());
  1366. out.write(zbuf);
  1367. return;
  1368. }
  1369. }
  1370. TemporaryBuffer.Heap delta = delta(otp);
  1371. out.writeHeader(otp, delta.length());
  1372. Deflater deflater = deflater();
  1373. deflater.reset();
  1374. DeflaterOutputStream dst = new DeflaterOutputStream(out, deflater);
  1375. delta.writeTo(dst, null);
  1376. dst.finish();
  1377. typeStats.cntDeltas++;
  1378. typeStats.deltaBytes += out.length() - otp.getOffset();
  1379. }
  1380. private TemporaryBuffer.Heap delta(final ObjectToPack otp)
  1381. throws IOException {
  1382. DeltaIndex index = new DeltaIndex(buffer(otp.getDeltaBaseId()));
  1383. byte[] res = buffer(otp);
  1384. // We never would have proposed this pair if the delta would be
  1385. // larger than the unpacked version of the object. So using it
  1386. // as our buffer limit is valid: we will never reach it.
  1387. //
  1388. TemporaryBuffer.Heap delta = new TemporaryBuffer.Heap(res.length);
  1389. index.encode(delta, res);
  1390. return delta;
  1391. }
  1392. private byte[] buffer(AnyObjectId objId) throws IOException {
  1393. return buffer(config, reader, objId);
  1394. }
  1395. static byte[] buffer(PackConfig config, ObjectReader or, AnyObjectId objId)
  1396. throws IOException {
  1397. // PackWriter should have already pruned objects that
  1398. // are above the big file threshold, so our chances of
  1399. // the object being below it are very good. We really
  1400. // shouldn't be here, unless the implementation is odd.
  1401. return or.open(objId).getCachedBytes(config.getBigFileThreshold());
  1402. }
  1403. private Deflater deflater() {
  1404. if (myDeflater == null)
  1405. myDeflater = new Deflater(config.getCompressionLevel());
  1406. return myDeflater;
  1407. }
  1408. private void writeChecksum(PackOutputStream out) throws IOException {
  1409. packcsum = out.getDigest();
  1410. out.write(packcsum);
  1411. }
  1412. private void findObjectsToPack(final ProgressMonitor countingMonitor,
  1413. final ObjectWalk walker, final Set<? extends ObjectId> want,
  1414. Set<? extends ObjectId> have)
  1415. throws MissingObjectException, IOException,
  1416. IncorrectObjectTypeException {
  1417. final long countingStart = System.currentTimeMillis();
  1418. beginPhase(PackingPhase.COUNTING, countingMonitor, ProgressMonitor.UNKNOWN);
  1419. if (have == null)
  1420. have = Collections.emptySet();
  1421. stats.interestingObjects = Collections.unmodifiableSet(new HashSet<ObjectId>(want));
  1422. stats.uninterestingObjects = Collections.unmodifiableSet(new HashSet<ObjectId>(have));
  1423. canBuildBitmaps = config.isBuildBitmaps()
  1424. && !shallowPack
  1425. && have.isEmpty()
  1426. && (excludeInPacks == null || excludeInPacks.length == 0);
  1427. if (!shallowPack && useBitmaps) {
  1428. BitmapIndex bitmapIndex = reader.getBitmapIndex();
  1429. if (bitmapIndex != null) {
  1430. PackWriterBitmapWalker bitmapWalker = new PackWriterBitmapWalker(
  1431. walker, bitmapIndex, countingMonitor);
  1432. findObjectsToPackUsingBitmaps(bitmapWalker, want, have);
  1433. endPhase(countingMonitor);
  1434. stats.timeCounting = System.currentTimeMillis() - countingStart;
  1435. return;
  1436. }
  1437. }
  1438. List<ObjectId> all = new ArrayList<ObjectId>(want.size() + have.size());
  1439. all.addAll(want);
  1440. all.addAll(have);
  1441. final RevFlag include = walker.newFlag("include"); //$NON-NLS-1$
  1442. final RevFlag added = walker.newFlag("added"); //$NON-NLS-1$
  1443. walker.carry(include);
  1444. int haveEst = have.size();
  1445. if (have.isEmpty()) {
  1446. walker.sort(RevSort.COMMIT_TIME_DESC);
  1447. } else {
  1448. walker.sort(RevSort.TOPO);
  1449. if (thin)
  1450. walker.sort(RevSort.BOUNDARY, true);
  1451. }
  1452. List<RevObject> wantObjs = new ArrayList<RevObject>(want.size());
  1453. List<RevObject> haveObjs = new ArrayList<RevObject>(haveEst);
  1454. List<RevTag> wantTags = new ArrayList<RevTag>(want.size());
  1455. AsyncRevObjectQueue q = walker.parseAny(all, true);
  1456. try {
  1457. for (;;) {
  1458. try {
  1459. RevObject o = q.next();
  1460. if (o == null)
  1461. break;
  1462. if (have.contains(o))
  1463. haveObjs.add(o);
  1464. if (want.contains(o)) {
  1465. o.add(include);
  1466. wantObjs.add(o);
  1467. if (o instanceof RevTag)
  1468. wantTags.add((RevTag) o);
  1469. }
  1470. } catch (MissingObjectException e) {
  1471. if (ignoreMissingUninteresting
  1472. && have.contains(e.getObjectId()))
  1473. continue;
  1474. throw e;
  1475. }
  1476. }
  1477. } finally {
  1478. q.release();
  1479. }
  1480. if (!wantTags.isEmpty()) {
  1481. all = new ArrayList<ObjectId>(wantTags.size());
  1482. for (RevTag tag : wantTags)
  1483. all.add(tag.getObject());
  1484. q = walker.parseAny(all, true);
  1485. try {
  1486. while (q.next() != null) {
  1487. // Just need to pop the queue item to parse the object.
  1488. }
  1489. } finally {
  1490. q.release();
  1491. }
  1492. }
  1493. if (walker instanceof DepthWalk.ObjectWalk) {
  1494. DepthWalk.ObjectWalk depthWalk = (DepthWalk.ObjectWalk) walker;
  1495. for (RevObject obj : wantObjs)
  1496. depthWalk.markRoot(obj);
  1497. if (unshallowObjects != null) {
  1498. for (ObjectId id : unshallowObjects)
  1499. depthWalk.markUnshallow(walker.parseAny(id));
  1500. }
  1501. } else {
  1502. for (RevObject obj : wantObjs)
  1503. walker.markStart(obj);
  1504. }
  1505. for (RevObject obj : haveObjs)
  1506. walker.markUninteresting(obj);
  1507. final int maxBases = config.getDeltaSearchWindowSize();
  1508. Set<RevTree> baseTrees = new HashSet<RevTree>();
  1509. BlockList<RevCommit> commits = new BlockList<RevCommit>();
  1510. RevCommit c;
  1511. while ((c = walker.next()) != null) {
  1512. if (exclude(c))
  1513. continue;
  1514. if (c.has(RevFlag.UNINTERESTING)) {
  1515. if (baseTrees.size() <= maxBases)
  1516. baseTrees.add(c.getTree());
  1517. continue;
  1518. }
  1519. commits.add(c);
  1520. countingMonitor.update(1);
  1521. }
  1522. if (shallowPack) {
  1523. for (RevCommit cmit : commits) {
  1524. addObject(cmit, 0);
  1525. }
  1526. } else {
  1527. int commitCnt = 0;
  1528. boolean putTagTargets = false;
  1529. for (RevCommit cmit : commits) {
  1530. if (!cmit.has(added)) {
  1531. cmit.add(added);
  1532. addObject(cmit, 0);
  1533. commitCnt++;
  1534. }
  1535. for (int i = 0; i < cmit.getParentCount(); i++) {
  1536. RevCommit p = cmit.getParent(i);
  1537. if (!p.has(added) && !p.has(RevFlag.UNINTERESTING)
  1538. && !exclude(p)) {
  1539. p.add(added);
  1540. addObject(p, 0);
  1541. commitCnt++;
  1542. }
  1543. }
  1544. if (!putTagTargets && 4096 < commitCnt) {
  1545. for (ObjectId id : tagTargets) {
  1546. RevObject obj = walker.lookupOrNull(id);
  1547. if (obj instanceof RevCommit
  1548. && obj.has(include)
  1549. && !obj.has(RevFlag.UNINTERESTING)
  1550. && !obj.has(added)) {
  1551. obj.add(added);
  1552. addObject(obj, 0);
  1553. }
  1554. }
  1555. putTagTargets = true;
  1556. }
  1557. }
  1558. }
  1559. commits = null;
  1560. if (thin && !baseTrees.isEmpty()) {
  1561. BaseSearch bases = new BaseSearch(countingMonitor, baseTrees, //
  1562. objectsMap, edgeObjects, reader);
  1563. RevObject o;
  1564. while ((o = walker.nextObject()) != null) {
  1565. if (o.has(RevFlag.UNINTERESTING))
  1566. continue;
  1567. if (exclude(o))
  1568. continue;
  1569. int pathHash = walker.getPathHashCode();
  1570. byte[] pathBuf = walker.getPathBuffer();
  1571. int pathLen = walker.getPathLength();
  1572. bases.addBase(o.getType(), pathBuf, pathLen, pathHash);
  1573. addObject(o, pathHash);
  1574. countingMonitor.update(1);
  1575. }
  1576. } else {
  1577. RevObject o;
  1578. while ((o = walker.nextObject()) != null) {
  1579. if (o.has(RevFlag.UNINTERESTING))
  1580. continue;
  1581. if (exclude(o))
  1582. continue;
  1583. addObject(o, walker.getPathHashCode());
  1584. countingMonitor.update(1);
  1585. }
  1586. }
  1587. for (CachedPack pack : cachedPacks)
  1588. countingMonitor.update((int) pack.getObjectCount());
  1589. endPhase(countingMonitor);
  1590. stats.timeCounting = System.currentTimeMillis() - countingStart;
  1591. }
  1592. private void findObjectsToPackUsingBitmaps(
  1593. PackWriterBitmapWalker bitmapWalker, Set<? extends ObjectId> want,
  1594. Set<? extends ObjectId> have)
  1595. throws MissingObjectException, IncorrectObjectTypeException,
  1596. IOException {
  1597. BitmapBuilder haveBitmap = bitmapWalker.findObjects(have, null, true);
  1598. bitmapWalker.reset();
  1599. BitmapBuilder wantBitmap = bitmapWalker.findObjects(want, haveBitmap,
  1600. false);
  1601. BitmapBuilder needBitmap = wantBitmap.andNot(haveBitmap);
  1602. if (useCachedPacks && reuseSupport != null && !reuseValidate
  1603. && (excludeInPacks == null || excludeInPacks.length == 0))
  1604. cachedPacks.addAll(
  1605. reuseSupport.getCachedPacksAndUpdate(needBitmap));
  1606. for (BitmapObject obj : needBitmap) {
  1607. ObjectId objectId = obj.getObjectId();
  1608. if (exclude(objectId)) {
  1609. needBitmap.remove(objectId);
  1610. continue;
  1611. }
  1612. addObject(objectId, obj.getType(), 0);
  1613. }
  1614. if (thin)
  1615. haveObjects = haveBitmap;
  1616. }
  1617. private static void pruneEdgesFromObjectList(List<ObjectToPack> list) {
  1618. final int size = list.size();
  1619. int src = 0;
  1620. int dst = 0;
  1621. for (; src < size; src++) {
  1622. ObjectToPack obj = list.get(src);
  1623. if (obj.isEdge())
  1624. continue;
  1625. if (dst != src)
  1626. list.set(dst, obj);
  1627. dst++;
  1628. }
  1629. while (dst < list.size())
  1630. list.remove(list.size() - 1);
  1631. }
  1632. /**
  1633. * Include one object to the output file.
  1634. * <p>
  1635. * Objects are written in the order they are added. If the same object is
  1636. * added twice, it may be written twice, creating a larger than necessary
  1637. * file.
  1638. *
  1639. * @param object
  1640. * the object to add.
  1641. * @throws IncorrectObjectTypeException
  1642. * the object is an unsupported type.
  1643. */
  1644. public void addObject(final RevObject object)
  1645. throws IncorrectObjectTypeException {
  1646. if (!exclude(object))
  1647. addObject(object, 0);
  1648. }
  1649. private void addObject(final RevObject object, final int pathHashCode) {
  1650. addObject(object, object.getType(), pathHashCode);
  1651. }
  1652. private void addObject(
  1653. final AnyObjectId src, final int type, final int pathHashCode) {
  1654. final ObjectToPack otp;
  1655. if (reuseSupport != null)
  1656. otp = reuseSupport.newObjectToPack(src, type);
  1657. else
  1658. otp = new ObjectToPack(src, type);
  1659. otp.setPathHash(pathHashCode);
  1660. objectsLists[type].add(otp);
  1661. objectsMap.add(otp);
  1662. }
  1663. private boolean exclude(AnyObjectId objectId) {
  1664. if (excludeInPacks == null)
  1665. return false;
  1666. if (excludeInPackLast.contains(objectId))
  1667. return true;
  1668. for (ObjectIdSet idx : excludeInPacks) {
  1669. if (idx.contains(objectId)) {
  1670. excludeInPackLast = idx;
  1671. return true;
  1672. }
  1673. }
  1674. return false;
  1675. }
  1676. /**
  1677. * Select an object representation for this writer.
  1678. * <p>
  1679. * An {@link ObjectReader} implementation should invoke this method once for
  1680. * each representation available for an object, to allow the writer to find
  1681. * the most suitable one for the output.
  1682. *
  1683. * @param otp
  1684. * the object being packed.
  1685. * @param next
  1686. * the next available representation from the repository.
  1687. */
  1688. public void select(ObjectToPack otp, StoredObjectRepresentation next) {
  1689. int nFmt = next.getFormat();
  1690. if (!cachedPacks.isEmpty()) {
  1691. if (otp.isEdge())
  1692. return;
  1693. if ((nFmt == PACK_WHOLE) | (nFmt == PACK_DELTA)) {
  1694. for (CachedPack pack : cachedPacks) {
  1695. if (pack.hasObject(otp, next)) {
  1696. otp.setEdge();
  1697. otp.clearDeltaBase();
  1698. otp.clearReuseAsIs();
  1699. pruneCurrentObjectList = true;
  1700. return;
  1701. }
  1702. }
  1703. }
  1704. }
  1705. if (nFmt == PACK_DELTA && reuseDeltas && reuseDeltaFor(otp)) {
  1706. ObjectId baseId = next.getDeltaBase();
  1707. ObjectToPack ptr = objectsMap.get(baseId);
  1708. if (ptr != null && !ptr.isEdge()) {
  1709. otp.setDeltaBase(ptr);
  1710. otp.setReuseAsIs();
  1711. } else if (thin && have(ptr, baseId)) {
  1712. otp.setDeltaBase(baseId);
  1713. otp.setReuseAsIs();
  1714. } else {
  1715. otp.clearDeltaBase();
  1716. otp.clearReuseAsIs();
  1717. }
  1718. } else if (nFmt == PACK_WHOLE && config.isReuseObjects()) {
  1719. int nWeight = next.getWeight();
  1720. if (otp.isReuseAsIs() && !otp.isDeltaRepresentation()) {
  1721. // We've chosen another PACK_WHOLE format for this object,
  1722. // choose the one that has the smaller compressed size.
  1723. //
  1724. if (otp.getWeight() <= nWeight)
  1725. return;
  1726. }
  1727. otp.clearDeltaBase();
  1728. otp.setReuseAsIs();
  1729. otp.setWeight(nWeight);
  1730. } else {
  1731. otp.clearDeltaBase();
  1732. otp.clearReuseAsIs();
  1733. }
  1734. otp.setDeltaAttempted(reuseDeltas & next.wasDeltaAttempted());
  1735. otp.select(next);
  1736. }
  1737. private final boolean have(ObjectToPack ptr, AnyObjectId objectId) {
  1738. return (ptr != null && ptr.isEdge())
  1739. || (haveObjects != null && haveObjects.contains(objectId));
  1740. }
  1741. /**
  1742. * Prepares the bitmaps to be written to the pack index. Bitmaps can be used
  1743. * to speed up fetches and clones by storing the entire object graph at
  1744. * selected commits.
  1745. *
  1746. * This method can only be invoked after
  1747. * {@link #writePack(ProgressMonitor, ProgressMonitor, OutputStream)} has
  1748. * been invoked and completed successfully. Writing a corresponding bitmap
  1749. * index is an optional feature that not all pack users may require.
  1750. *
  1751. * @param pm
  1752. * progress monitor to report bitmap building work.
  1753. * @return whether a bitmap index may be written.
  1754. * @throws IOException
  1755. * when some I/O problem occur during reading objects.
  1756. */
  1757. public boolean prepareBitmapIndex(ProgressMonitor pm) throws IOException {
  1758. if (!canBuildBitmaps || getObjectCount() > Integer.MAX_VALUE
  1759. || !cachedPacks.isEmpty())
  1760. return false;
  1761. if (pm == null)
  1762. pm = NullProgressMonitor.INSTANCE;
  1763. writeBitmaps = new PackBitmapIndexBuilder(sortByName());
  1764. PackWriterBitmapPreparer bitmapPreparer = new PackWriterBitmapPreparer(
  1765. reader, writeBitmaps, pm, stats.interestingObjects);
  1766. int numCommits = objectsLists[OBJ_COMMIT].size();
  1767. Collection<PackWriterBitmapPreparer.BitmapCommit> selectedCommits =
  1768. bitmapPreparer.doCommitSelection(numCommits);
  1769. beginPhase(PackingPhase.BUILDING_BITMAPS, pm, selectedCommits.size());
  1770. PackWriterBitmapWalker walker = bitmapPreparer.newBitmapWalker();
  1771. AnyObjectId last = null;
  1772. for (PackWriterBitmapPreparer.BitmapCommit cmit : selectedCommits) {
  1773. if (cmit.isReuseWalker())
  1774. walker.reset();
  1775. else
  1776. walker = bitmapPreparer.newBitmapWalker();
  1777. BitmapBuilder bitmap = walker.findObjects(
  1778. Collections.singleton(cmit), null, false);
  1779. if (last != null && cmit.isReuseWalker() && !bitmap.contains(last))
  1780. throw new IllegalStateException(MessageFormat.format(
  1781. JGitText.get().bitmapMissingObject, cmit.name(),
  1782. last.name()));
  1783. last = cmit;
  1784. writeBitmaps.addBitmap(cmit, bitmap.build(), cmit.getFlags());
  1785. pm.update(1);
  1786. }
  1787. endPhase(pm);
  1788. return true;
  1789. }
  1790. private boolean reuseDeltaFor(ObjectToPack otp) {
  1791. int type = otp.getType();
  1792. if ((type & 2) != 0) // OBJ_TREE(2) or OBJ_BLOB(3)
  1793. return true;
  1794. if (type == OBJ_COMMIT)
  1795. return reuseDeltaCommits;
  1796. if (type == OBJ_TAG)
  1797. return false;
  1798. return true;
  1799. }
  1800. /** Summary of how PackWriter created the pack. */
  1801. public static class Statistics {
  1802. /** Statistics about a single class of object. */
  1803. public static class ObjectType {
  1804. long cntObjects;
  1805. long cntDeltas;
  1806. long reusedObjects;
  1807. long reusedDeltas;
  1808. long bytes;
  1809. long deltaBytes;
  1810. /**
  1811. * @return total number of objects output. This total includes the
  1812. * value of {@link #getDeltas()}.
  1813. */
  1814. public long getObjects() {
  1815. return cntObjects;
  1816. }
  1817. /**
  1818. * @return total number of deltas output. This may be lower than the
  1819. * actual number of deltas if a cached pack was reused.
  1820. */
  1821. public long getDeltas() {
  1822. return cntDeltas;
  1823. }
  1824. /**
  1825. * @return number of objects whose existing representation was
  1826. * reused in the output. This count includes
  1827. * {@link #getReusedDeltas()}.
  1828. */
  1829. public long getReusedObjects() {
  1830. return reusedObjects;
  1831. }
  1832. /**
  1833. * @return number of deltas whose existing representation was reused
  1834. * in the output, as their base object was also output or
  1835. * was assumed present for a thin pack. This may be lower
  1836. * than the actual number of reused deltas if a cached pack
  1837. * was reused.
  1838. */
  1839. public long getReusedDeltas() {
  1840. return reusedDeltas;
  1841. }
  1842. /**
  1843. * @return total number of bytes written. This size includes the
  1844. * object headers as well as the compressed data. This size
  1845. * also includes all of {@link #getDeltaBytes()}.
  1846. */
  1847. public long getBytes() {
  1848. return bytes;
  1849. }
  1850. /**
  1851. * @return number of delta bytes written. This size includes the
  1852. * object headers for the delta objects.
  1853. */
  1854. public long getDeltaBytes() {
  1855. return deltaBytes;
  1856. }
  1857. }
  1858. Set<ObjectId> interestingObjects;
  1859. Set<ObjectId> uninterestingObjects;
  1860. Collection<CachedPack> reusedPacks;
  1861. int depth;
  1862. int deltaSearchNonEdgeObjects;
  1863. int deltasFound;
  1864. long totalObjects;
  1865. long totalDeltas;
  1866. long reusedObjects;
  1867. long reusedDeltas;
  1868. long totalBytes;
  1869. long thinPackBytes;
  1870. long timeCounting;
  1871. long timeSearchingForReuse;
  1872. long timeSearchingForSizes;
  1873. long timeCompressing;
  1874. long timeWriting;
  1875. ObjectType[] objectTypes;
  1876. {
  1877. objectTypes = new ObjectType[5];
  1878. objectTypes[OBJ_COMMIT] = new ObjectType();
  1879. objectTypes[OBJ_TREE] = new ObjectType();
  1880. objectTypes[OBJ_BLOB] = new ObjectType();
  1881. objectTypes[OBJ_TAG] = new ObjectType();
  1882. }
  1883. /**
  1884. * @return unmodifiable collection of objects to be included in the
  1885. * pack. May be null if the pack was hand-crafted in a unit
  1886. * test.
  1887. */
  1888. public Set<ObjectId> getInterestingObjects() {
  1889. return interestingObjects;
  1890. }
  1891. /**
  1892. * @return unmodifiable collection of objects that should be excluded
  1893. * from the pack, as the peer that will receive the pack already
  1894. * has these objects.
  1895. */
  1896. public Set<ObjectId> getUninterestingObjects() {
  1897. return uninterestingObjects;
  1898. }
  1899. /**
  1900. * @return unmodifiable collection of the cached packs that were reused
  1901. * in the output, if any were selected for reuse.
  1902. */
  1903. public Collection<CachedPack> getReusedPacks() {
  1904. return reusedPacks;
  1905. }
  1906. /**
  1907. * @return number of objects in the output pack that went through the
  1908. * delta search process in order to find a potential delta base.
  1909. */
  1910. public int getDeltaSearchNonEdgeObjects() {
  1911. return deltaSearchNonEdgeObjects;
  1912. }
  1913. /**
  1914. * @return number of objects in the output pack that went through delta
  1915. * base search and found a suitable base. This is a subset of
  1916. * {@link #getDeltaSearchNonEdgeObjects()}.
  1917. */
  1918. public int getDeltasFound() {
  1919. return deltasFound;
  1920. }
  1921. /**
  1922. * @return total number of objects output. This total includes the value
  1923. * of {@link #getTotalDeltas()}.
  1924. */
  1925. public long getTotalObjects() {
  1926. return totalObjects;
  1927. }
  1928. /**
  1929. * @return total number of deltas output. This may be lower than the
  1930. * actual number of deltas if a cached pack was reused.
  1931. */
  1932. public long getTotalDeltas() {
  1933. return totalDeltas;
  1934. }
  1935. /**
  1936. * @return number of objects whose existing representation was reused in
  1937. * the output. This count includes {@link #getReusedDeltas()}.
  1938. */
  1939. public long getReusedObjects() {
  1940. return reusedObjects;
  1941. }
  1942. /**
  1943. * @return number of deltas whose existing representation was reused in
  1944. * the output, as their base object was also output or was
  1945. * assumed present for a thin pack. This may be lower than the
  1946. * actual number of reused deltas if a cached pack was reused.
  1947. */
  1948. public long getReusedDeltas() {
  1949. return reusedDeltas;
  1950. }
  1951. /**
  1952. * @return total number of bytes written. This size includes the pack
  1953. * header, trailer, thin pack, and reused cached pack(s).
  1954. */
  1955. public long getTotalBytes() {
  1956. return totalBytes;
  1957. }
  1958. /**
  1959. * @return size of the thin pack in bytes, if a thin pack was generated.
  1960. * A thin pack is created when the client already has objects
  1961. * and some deltas are created against those objects, or if a
  1962. * cached pack is being used and some deltas will reference
  1963. * objects in the cached pack. This size does not include the
  1964. * pack header or trailer.
  1965. */
  1966. public long getThinPackBytes() {
  1967. return thinPackBytes;
  1968. }
  1969. /**
  1970. * @param typeCode
  1971. * object type code, e.g. OBJ_COMMIT or OBJ_TREE.
  1972. * @return information about this type of object in the pack.
  1973. */
  1974. public ObjectType byObjectType(int typeCode) {
  1975. return objectTypes[typeCode];
  1976. }
  1977. /** @return true if the resulting pack file was a shallow pack. */
  1978. public boolean isShallow() {
  1979. return depth > 0;
  1980. }
  1981. /** @return depth (in commits) the pack includes if shallow. */
  1982. public int getDepth() {
  1983. return depth;
  1984. }
  1985. /**
  1986. * @return time in milliseconds spent enumerating the objects that need
  1987. * to be included in the output. This time includes any restarts
  1988. * that occur when a cached pack is selected for reuse.
  1989. */
  1990. public long getTimeCounting() {
  1991. return timeCounting;
  1992. }
  1993. /**
  1994. * @return time in milliseconds spent matching existing representations
  1995. * against objects that will be transmitted, or that the client
  1996. * can be assumed to already have.
  1997. */
  1998. public long getTimeSearchingForReuse() {
  1999. return timeSearchingForReuse;
  2000. }
  2001. /**
  2002. * @return time in milliseconds spent finding the sizes of all objects
  2003. * that will enter the delta compression search window. The
  2004. * sizes need to be known to better match similar objects
  2005. * together and improve delta compression ratios.
  2006. */
  2007. public long getTimeSearchingForSizes() {
  2008. return timeSearchingForSizes;
  2009. }
  2010. /**
  2011. * @return time in milliseconds spent on delta compression. This is
  2012. * observed wall-clock time and does not accurately track CPU
  2013. * time used when multiple threads were used to perform the
  2014. * delta compression.
  2015. */
  2016. public long getTimeCompressing() {
  2017. return timeCompressing;
  2018. }
  2019. /**
  2020. * @return time in milliseconds spent writing the pack output, from
  2021. * start of header until end of trailer. The transfer speed can
  2022. * be approximated by dividing {@link #getTotalBytes()} by this
  2023. * value.
  2024. */
  2025. public long getTimeWriting() {
  2026. return timeWriting;
  2027. }
  2028. /** @return total time spent processing this pack. */
  2029. public long getTimeTotal() {
  2030. return timeCounting
  2031. + timeSearchingForReuse
  2032. + timeSearchingForSizes
  2033. + timeCompressing
  2034. + timeWriting;
  2035. }
  2036. /**
  2037. * @return get the average output speed in terms of bytes-per-second.
  2038. * {@code getTotalBytes() / (getTimeWriting() / 1000.0)}.
  2039. */
  2040. public double getTransferRate() {
  2041. return getTotalBytes() / (getTimeWriting() / 1000.0);
  2042. }
  2043. /** @return formatted message string for display to clients. */
  2044. public String getMessage() {
  2045. return MessageFormat.format(JGitText.get().packWriterStatistics, //
  2046. Long.valueOf(totalObjects), Long.valueOf(totalDeltas), //
  2047. Long.valueOf(reusedObjects), Long.valueOf(reusedDeltas));
  2048. }
  2049. }
  2050. private class MutableState {
  2051. /** Estimated size of a single ObjectToPack instance. */
  2052. // Assume 64-bit pointers, since this is just an estimate.
  2053. private static final long OBJECT_TO_PACK_SIZE =
  2054. (2 * 8) // Object header
  2055. + (2 * 8) + (2 * 8) // ObjectToPack fields
  2056. + (8 + 8) // PackedObjectInfo fields
  2057. + 8 // ObjectIdOwnerMap fields
  2058. + 40 // AnyObjectId fields
  2059. + 8; // Reference in BlockList
  2060. private final long totalDeltaSearchBytes;
  2061. private volatile PackingPhase phase;
  2062. MutableState() {
  2063. phase = PackingPhase.COUNTING;
  2064. if (config.isDeltaCompress()) {
  2065. int threads = config.getThreads();
  2066. if (threads <= 0)
  2067. threads = Runtime.getRuntime().availableProcessors();
  2068. totalDeltaSearchBytes = (threads * config.getDeltaSearchMemoryLimit())
  2069. + config.getBigFileThreshold();
  2070. } else
  2071. totalDeltaSearchBytes = 0;
  2072. }
  2073. State snapshot() {
  2074. long objCnt = 0;
  2075. objCnt += objectsLists[OBJ_COMMIT].size();
  2076. objCnt += objectsLists[OBJ_TREE].size();
  2077. objCnt += objectsLists[OBJ_BLOB].size();
  2078. objCnt += objectsLists[OBJ_TAG].size();
  2079. // Exclude CachedPacks.
  2080. long bytesUsed = OBJECT_TO_PACK_SIZE * objCnt;
  2081. PackingPhase curr = phase;
  2082. if (curr == PackingPhase.COMPRESSING)
  2083. bytesUsed += totalDeltaSearchBytes;
  2084. return new State(curr, bytesUsed);
  2085. }
  2086. }
  2087. /** Possible states that a PackWriter can be in. */
  2088. public static enum PackingPhase {
  2089. /** Counting objects phase. */
  2090. COUNTING,
  2091. /** Getting sizes phase. */
  2092. GETTING_SIZES,
  2093. /** Finding sources phase. */
  2094. FINDING_SOURCES,
  2095. /** Compressing objects phase. */
  2096. COMPRESSING,
  2097. /** Writing objects phase. */
  2098. WRITING,
  2099. /** Building bitmaps phase. */
  2100. BUILDING_BITMAPS;
  2101. }
  2102. /** Summary of the current state of a PackWriter. */
  2103. public class State {
  2104. private final PackingPhase phase;
  2105. private final long bytesUsed;
  2106. State(PackingPhase phase, long bytesUsed) {
  2107. this.phase = phase;
  2108. this.bytesUsed = bytesUsed;
  2109. }
  2110. /** @return the PackConfig used to build the writer. */
  2111. public PackConfig getConfig() {
  2112. return config;
  2113. }
  2114. /** @return the current phase of the writer. */
  2115. public PackingPhase getPhase() {
  2116. return phase;
  2117. }
  2118. /** @return an estimate of the total memory used by the writer. */
  2119. public long estimateBytesUsed() {
  2120. return bytesUsed;
  2121. }
  2122. @SuppressWarnings("nls")
  2123. @Override
  2124. public String toString() {
  2125. return "PackWriter.State[" + phase + ", memory=" + bytesUsed + "]";
  2126. }
  2127. }
  2128. }