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

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