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

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