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

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