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

PackWriter.java 72KB

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