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

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