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

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