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

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