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

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