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

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