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

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