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

PackWriter.java 77KB

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