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

PackWriter.java 78KB

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