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.

PackWriterTest.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. /*
  2. * Copyright (C) 2008, Marek Zawirski <marek.zawirski@gmail.com>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.internal.storage.file;
  44. import static org.eclipse.jgit.internal.storage.pack.PackWriter.NONE;
  45. import static org.eclipse.jgit.lib.Constants.OBJ_BLOB;
  46. import static org.junit.Assert.assertEquals;
  47. import static org.junit.Assert.assertFalse;
  48. import static org.junit.Assert.assertNotNull;
  49. import static org.junit.Assert.assertTrue;
  50. import static org.junit.Assert.fail;
  51. import java.io.ByteArrayInputStream;
  52. import java.io.ByteArrayOutputStream;
  53. import java.io.File;
  54. import java.io.FileOutputStream;
  55. import java.io.IOException;
  56. import java.text.ParseException;
  57. import java.util.ArrayList;
  58. import java.util.Arrays;
  59. import java.util.Collections;
  60. import java.util.Comparator;
  61. import java.util.HashSet;
  62. import java.util.List;
  63. import java.util.Set;
  64. import org.eclipse.jgit.errors.MissingObjectException;
  65. import org.eclipse.jgit.internal.storage.file.PackIndex.MutableEntry;
  66. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  67. import org.eclipse.jgit.junit.JGitTestUtil;
  68. import org.eclipse.jgit.junit.TestRepository;
  69. import org.eclipse.jgit.junit.TestRepository.BranchBuilder;
  70. import org.eclipse.jgit.lib.NullProgressMonitor;
  71. import org.eclipse.jgit.lib.ObjectId;
  72. import org.eclipse.jgit.lib.ObjectIdSet;
  73. import org.eclipse.jgit.lib.ObjectInserter;
  74. import org.eclipse.jgit.lib.Repository;
  75. import org.eclipse.jgit.lib.Sets;
  76. import org.eclipse.jgit.revwalk.DepthWalk;
  77. import org.eclipse.jgit.revwalk.ObjectWalk;
  78. import org.eclipse.jgit.revwalk.RevBlob;
  79. import org.eclipse.jgit.revwalk.RevCommit;
  80. import org.eclipse.jgit.revwalk.RevObject;
  81. import org.eclipse.jgit.revwalk.RevWalk;
  82. import org.eclipse.jgit.storage.pack.PackConfig;
  83. import org.eclipse.jgit.storage.pack.PackStatistics;
  84. import org.eclipse.jgit.test.resources.SampleDataRepositoryTestCase;
  85. import org.eclipse.jgit.transport.PackParser;
  86. import org.junit.After;
  87. import org.junit.Before;
  88. import org.junit.Test;
  89. public class PackWriterTest extends SampleDataRepositoryTestCase {
  90. private static final List<RevObject> EMPTY_LIST_REVS = Collections
  91. .<RevObject> emptyList();
  92. private static final Set<ObjectIdSet> EMPTY_ID_SET = Collections
  93. .<ObjectIdSet> emptySet();
  94. private PackConfig config;
  95. private PackWriter writer;
  96. private ByteArrayOutputStream os;
  97. private PackFile pack;
  98. private ObjectInserter inserter;
  99. private FileRepository dst;
  100. private RevBlob contentA;
  101. private RevBlob contentB;
  102. private RevBlob contentC;
  103. private RevBlob contentD;
  104. private RevBlob contentE;
  105. private RevCommit c1;
  106. private RevCommit c2;
  107. private RevCommit c3;
  108. private RevCommit c4;
  109. private RevCommit c5;
  110. @Override
  111. @Before
  112. public void setUp() throws Exception {
  113. super.setUp();
  114. os = new ByteArrayOutputStream();
  115. config = new PackConfig(db);
  116. dst = createBareRepository();
  117. File alt = new File(dst.getObjectDatabase().getDirectory(), "info/alternates");
  118. alt.getParentFile().mkdirs();
  119. write(alt, db.getObjectDatabase().getDirectory().getAbsolutePath() + "\n");
  120. }
  121. @Override
  122. @After
  123. public void tearDown() throws Exception {
  124. if (writer != null) {
  125. writer.close();
  126. writer = null;
  127. }
  128. if (inserter != null) {
  129. inserter.close();
  130. inserter = null;
  131. }
  132. super.tearDown();
  133. }
  134. /**
  135. * Test constructor for exceptions, default settings, initialization.
  136. *
  137. * @throws IOException
  138. */
  139. @Test
  140. public void testContructor() throws IOException {
  141. writer = new PackWriter(config, db.newObjectReader());
  142. assertFalse(writer.isDeltaBaseAsOffset());
  143. assertTrue(config.isReuseDeltas());
  144. assertTrue(config.isReuseObjects());
  145. assertEquals(0, writer.getObjectCount());
  146. }
  147. /**
  148. * Change default settings and verify them.
  149. */
  150. @Test
  151. public void testModifySettings() {
  152. config.setReuseDeltas(false);
  153. config.setReuseObjects(false);
  154. config.setDeltaBaseAsOffset(false);
  155. assertFalse(config.isReuseDeltas());
  156. assertFalse(config.isReuseObjects());
  157. assertFalse(config.isDeltaBaseAsOffset());
  158. writer = new PackWriter(config, db.newObjectReader());
  159. writer.setDeltaBaseAsOffset(true);
  160. assertTrue(writer.isDeltaBaseAsOffset());
  161. assertFalse(config.isDeltaBaseAsOffset());
  162. }
  163. /**
  164. * Write empty pack by providing empty sets of interesting/uninteresting
  165. * objects and check for correct format.
  166. *
  167. * @throws IOException
  168. */
  169. @Test
  170. public void testWriteEmptyPack1() throws IOException {
  171. createVerifyOpenPack(NONE, NONE, false, false);
  172. assertEquals(0, writer.getObjectCount());
  173. assertEquals(0, pack.getObjectCount());
  174. assertEquals("da39a3ee5e6b4b0d3255bfef95601890afd80709", writer
  175. .computeName().name());
  176. }
  177. /**
  178. * Write empty pack by providing empty iterator of objects to write and
  179. * check for correct format.
  180. *
  181. * @throws IOException
  182. */
  183. @Test
  184. public void testWriteEmptyPack2() throws IOException {
  185. createVerifyOpenPack(EMPTY_LIST_REVS);
  186. assertEquals(0, writer.getObjectCount());
  187. assertEquals(0, pack.getObjectCount());
  188. }
  189. /**
  190. * Try to pass non-existing object as uninteresting, with non-ignoring
  191. * setting.
  192. *
  193. * @throws IOException
  194. */
  195. @Test
  196. public void testNotIgnoreNonExistingObjects() throws IOException {
  197. final ObjectId nonExisting = ObjectId
  198. .fromString("0000000000000000000000000000000000000001");
  199. try {
  200. createVerifyOpenPack(NONE, haves(nonExisting), false, false);
  201. fail("Should have thrown MissingObjectException");
  202. } catch (MissingObjectException x) {
  203. // expected
  204. }
  205. }
  206. /**
  207. * Try to pass non-existing object as uninteresting, with ignoring setting.
  208. *
  209. * @throws IOException
  210. */
  211. @Test
  212. public void testIgnoreNonExistingObjects() throws IOException {
  213. final ObjectId nonExisting = ObjectId
  214. .fromString("0000000000000000000000000000000000000001");
  215. createVerifyOpenPack(NONE, haves(nonExisting), false, true);
  216. // shouldn't throw anything
  217. }
  218. /**
  219. * Try to pass non-existing object as uninteresting, with ignoring setting.
  220. * Use a repo with bitmap indexes because then PackWriter will use
  221. * PackWriterBitmapWalker which had problems with this situation.
  222. *
  223. * @throws IOException
  224. * @throws ParseException
  225. */
  226. @Test
  227. public void testIgnoreNonExistingObjectsWithBitmaps() throws IOException,
  228. ParseException {
  229. final ObjectId nonExisting = ObjectId
  230. .fromString("0000000000000000000000000000000000000001");
  231. new GC(db).gc();
  232. createVerifyOpenPack(NONE, haves(nonExisting), false, true, true);
  233. // shouldn't throw anything
  234. }
  235. /**
  236. * Create pack basing on only interesting objects, then precisely verify
  237. * content. No delta reuse here.
  238. *
  239. * @throws IOException
  240. */
  241. @Test
  242. public void testWritePack1() throws IOException {
  243. config.setReuseDeltas(false);
  244. writeVerifyPack1();
  245. }
  246. /**
  247. * Test writing pack without object reuse. Pack content/preparation as in
  248. * {@link #testWritePack1()}.
  249. *
  250. * @throws IOException
  251. */
  252. @Test
  253. public void testWritePack1NoObjectReuse() throws IOException {
  254. config.setReuseDeltas(false);
  255. config.setReuseObjects(false);
  256. writeVerifyPack1();
  257. }
  258. /**
  259. * Create pack basing on both interesting and uninteresting objects, then
  260. * precisely verify content. No delta reuse here.
  261. *
  262. * @throws IOException
  263. */
  264. @Test
  265. public void testWritePack2() throws IOException {
  266. writeVerifyPack2(false);
  267. }
  268. /**
  269. * Test pack writing with deltas reuse, delta-base first rule. Pack
  270. * content/preparation as in {@link #testWritePack2()}.
  271. *
  272. * @throws IOException
  273. */
  274. @Test
  275. public void testWritePack2DeltasReuseRefs() throws IOException {
  276. writeVerifyPack2(true);
  277. }
  278. /**
  279. * Test pack writing with delta reuse. Delta bases referred as offsets. Pack
  280. * configuration as in {@link #testWritePack2DeltasReuseRefs()}.
  281. *
  282. * @throws IOException
  283. */
  284. @Test
  285. public void testWritePack2DeltasReuseOffsets() throws IOException {
  286. config.setDeltaBaseAsOffset(true);
  287. writeVerifyPack2(true);
  288. }
  289. /**
  290. * Test pack writing with delta reuse. Raw-data copy (reuse) is made on a
  291. * pack with CRC32 index. Pack configuration as in
  292. * {@link #testWritePack2DeltasReuseRefs()}.
  293. *
  294. * @throws IOException
  295. */
  296. @Test
  297. public void testWritePack2DeltasCRC32Copy() throws IOException {
  298. final File packDir = new File(db.getObjectDatabase().getDirectory(), "pack");
  299. final File crc32Pack = new File(packDir,
  300. "pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.pack");
  301. final File crc32Idx = new File(packDir,
  302. "pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.idx");
  303. copyFile(JGitTestUtil.getTestResourceFile(
  304. "pack-34be9032ac282b11fa9babdc2b2a93ca996c9c2f.idxV2"),
  305. crc32Idx);
  306. db.openPack(crc32Pack);
  307. writeVerifyPack2(true);
  308. }
  309. /**
  310. * Create pack basing on fixed objects list, then precisely verify content.
  311. * No delta reuse here.
  312. *
  313. * @throws IOException
  314. * @throws MissingObjectException
  315. *
  316. */
  317. @Test
  318. public void testWritePack3() throws MissingObjectException, IOException {
  319. config.setReuseDeltas(false);
  320. final ObjectId forcedOrder[] = new ObjectId[] {
  321. ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"),
  322. ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799"),
  323. ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"),
  324. ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327"),
  325. ObjectId.fromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3") ,
  326. ObjectId.fromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259") };
  327. try (final RevWalk parser = new RevWalk(db)) {
  328. final RevObject forcedOrderRevs[] = new RevObject[forcedOrder.length];
  329. for (int i = 0; i < forcedOrder.length; i++)
  330. forcedOrderRevs[i] = parser.parseAny(forcedOrder[i]);
  331. createVerifyOpenPack(Arrays.asList(forcedOrderRevs));
  332. }
  333. assertEquals(forcedOrder.length, writer.getObjectCount());
  334. verifyObjectsOrder(forcedOrder);
  335. assertEquals("ed3f96b8327c7c66b0f8f70056129f0769323d86", writer
  336. .computeName().name());
  337. }
  338. /**
  339. * Another pack creation: basing on both interesting and uninteresting
  340. * objects. No delta reuse possible here, as this is a specific case when we
  341. * write only 1 commit, associated with 1 tree, 1 blob.
  342. *
  343. * @throws IOException
  344. */
  345. @Test
  346. public void testWritePack4() throws IOException {
  347. writeVerifyPack4(false);
  348. }
  349. /**
  350. * Test thin pack writing: 1 blob delta base is on objects edge. Pack
  351. * configuration as in {@link #testWritePack4()}.
  352. *
  353. * @throws IOException
  354. */
  355. @Test
  356. public void testWritePack4ThinPack() throws IOException {
  357. writeVerifyPack4(true);
  358. }
  359. /**
  360. * Compare sizes of packs created using {@link #testWritePack2()} and
  361. * {@link #testWritePack2DeltasReuseRefs()}. The pack using deltas should
  362. * be smaller.
  363. *
  364. * @throws Exception
  365. */
  366. @Test
  367. public void testWritePack2SizeDeltasVsNoDeltas() throws Exception {
  368. config.setReuseDeltas(false);
  369. config.setDeltaCompress(false);
  370. testWritePack2();
  371. final long sizePack2NoDeltas = os.size();
  372. tearDown();
  373. setUp();
  374. testWritePack2DeltasReuseRefs();
  375. final long sizePack2DeltasRefs = os.size();
  376. assertTrue(sizePack2NoDeltas > sizePack2DeltasRefs);
  377. }
  378. /**
  379. * Compare sizes of packs created using
  380. * {@link #testWritePack2DeltasReuseRefs()} and
  381. * {@link #testWritePack2DeltasReuseOffsets()}. The pack with delta bases
  382. * written as offsets should be smaller.
  383. *
  384. * @throws Exception
  385. */
  386. @Test
  387. public void testWritePack2SizeOffsetsVsRefs() throws Exception {
  388. testWritePack2DeltasReuseRefs();
  389. final long sizePack2DeltasRefs = os.size();
  390. tearDown();
  391. setUp();
  392. testWritePack2DeltasReuseOffsets();
  393. final long sizePack2DeltasOffsets = os.size();
  394. assertTrue(sizePack2DeltasRefs > sizePack2DeltasOffsets);
  395. }
  396. /**
  397. * Compare sizes of packs created using {@link #testWritePack4()} and
  398. * {@link #testWritePack4ThinPack()}. Obviously, the thin pack should be
  399. * smaller.
  400. *
  401. * @throws Exception
  402. */
  403. @Test
  404. public void testWritePack4SizeThinVsNoThin() throws Exception {
  405. testWritePack4();
  406. final long sizePack4 = os.size();
  407. tearDown();
  408. setUp();
  409. testWritePack4ThinPack();
  410. final long sizePack4Thin = os.size();
  411. assertTrue(sizePack4 > sizePack4Thin);
  412. }
  413. @Test
  414. public void testDeltaStatistics() throws Exception {
  415. config.setDeltaCompress(true);
  416. FileRepository repo = createBareRepository();
  417. TestRepository<FileRepository> testRepo = new TestRepository<>(repo);
  418. ArrayList<RevObject> blobs = new ArrayList<>();
  419. blobs.add(testRepo.blob(genDeltableData(1000)));
  420. blobs.add(testRepo.blob(genDeltableData(1005)));
  421. try (PackWriter pw = new PackWriter(repo)) {
  422. NullProgressMonitor m = NullProgressMonitor.INSTANCE;
  423. pw.preparePack(blobs.iterator());
  424. pw.writePack(m, m, os);
  425. PackStatistics stats = pw.getStatistics();
  426. assertEquals(1, stats.getTotalDeltas());
  427. assertTrue("Delta bytes not set.",
  428. stats.byObjectType(OBJ_BLOB).getDeltaBytes() > 0);
  429. }
  430. }
  431. // Generate consistent junk data for building files that delta well
  432. private String genDeltableData(int length) {
  433. assertTrue("Generated data must have a length > 0", length > 0);
  434. char[] data = {'a', 'b', 'c', '\n'};
  435. StringBuilder builder = new StringBuilder(length);
  436. for (int i = 0; i < length; i++) {
  437. builder.append(data[i % 4]);
  438. }
  439. return builder.toString();
  440. }
  441. @Test
  442. public void testWriteIndex() throws Exception {
  443. config.setIndexVersion(2);
  444. writeVerifyPack4(false);
  445. File packFile = pack.getPackFile();
  446. String name = packFile.getName();
  447. String base = name.substring(0, name.lastIndexOf('.'));
  448. File indexFile = new File(packFile.getParentFile(), base + ".idx");
  449. // Validate that IndexPack came up with the right CRC32 value.
  450. final PackIndex idx1 = PackIndex.open(indexFile);
  451. assertTrue(idx1 instanceof PackIndexV2);
  452. assertEquals(0x4743F1E4L, idx1.findCRC32(ObjectId
  453. .fromString("82c6b885ff600be425b4ea96dee75dca255b69e7")));
  454. // Validate that an index written by PackWriter is the same.
  455. final File idx2File = new File(indexFile.getAbsolutePath() + ".2");
  456. final FileOutputStream is = new FileOutputStream(idx2File);
  457. try {
  458. writer.writeIndex(is);
  459. } finally {
  460. is.close();
  461. }
  462. final PackIndex idx2 = PackIndex.open(idx2File);
  463. assertTrue(idx2 instanceof PackIndexV2);
  464. assertEquals(idx1.getObjectCount(), idx2.getObjectCount());
  465. assertEquals(idx1.getOffset64Count(), idx2.getOffset64Count());
  466. for (int i = 0; i < idx1.getObjectCount(); i++) {
  467. final ObjectId id = idx1.getObjectId(i);
  468. assertEquals(id, idx2.getObjectId(i));
  469. assertEquals(idx1.findOffset(id), idx2.findOffset(id));
  470. assertEquals(idx1.findCRC32(id), idx2.findCRC32(id));
  471. }
  472. }
  473. @Test
  474. public void testExclude() throws Exception {
  475. FileRepository repo = createBareRepository();
  476. TestRepository<FileRepository> testRepo = new TestRepository<>(
  477. repo);
  478. BranchBuilder bb = testRepo.branch("refs/heads/master");
  479. contentA = testRepo.blob("A");
  480. c1 = bb.commit().add("f", contentA).create();
  481. testRepo.getRevWalk().parseHeaders(c1);
  482. PackIndex pf1 = writePack(repo, wants(c1), EMPTY_ID_SET);
  483. assertContent(
  484. pf1,
  485. Arrays.asList(c1.getId(), c1.getTree().getId(),
  486. contentA.getId()));
  487. contentB = testRepo.blob("B");
  488. c2 = bb.commit().add("f", contentB).create();
  489. testRepo.getRevWalk().parseHeaders(c2);
  490. PackIndex pf2 = writePack(repo, wants(c2), Sets.of((ObjectIdSet) pf1));
  491. assertContent(
  492. pf2,
  493. Arrays.asList(c2.getId(), c2.getTree().getId(),
  494. contentB.getId()));
  495. }
  496. private static void assertContent(PackIndex pi, List<ObjectId> expected) {
  497. assertEquals("Pack index has wrong size.", expected.size(),
  498. pi.getObjectCount());
  499. for (int i = 0; i < pi.getObjectCount(); i++)
  500. assertTrue(
  501. "Pack index didn't contain the expected id "
  502. + pi.getObjectId(i),
  503. expected.contains(pi.getObjectId(i)));
  504. }
  505. @Test
  506. public void testShallowIsMinimalDepth1() throws Exception {
  507. FileRepository repo = setupRepoForShallowFetch();
  508. PackIndex idx = writeShallowPack(repo, 1, wants(c2), NONE, NONE);
  509. assertContent(idx, Arrays.asList(c2.getId(), c2.getTree().getId(),
  510. contentA.getId(), contentB.getId()));
  511. // Client already has blobs A and B, verify those are not packed.
  512. idx = writeShallowPack(repo, 1, wants(c5), haves(c2), shallows(c2));
  513. assertContent(idx, Arrays.asList(c5.getId(), c5.getTree().getId(),
  514. contentC.getId(), contentD.getId(), contentE.getId()));
  515. }
  516. @Test
  517. public void testShallowIsMinimalDepth2() throws Exception {
  518. FileRepository repo = setupRepoForShallowFetch();
  519. PackIndex idx = writeShallowPack(repo, 2, wants(c2), NONE, NONE);
  520. assertContent(idx,
  521. Arrays.asList(c1.getId(), c2.getId(), c1.getTree().getId(),
  522. c2.getTree().getId(), contentA.getId(),
  523. contentB.getId()));
  524. // Client already has blobs A and B, verify those are not packed.
  525. idx = writeShallowPack(repo, 2, wants(c5), haves(c1, c2), shallows(c1));
  526. assertContent(idx,
  527. Arrays.asList(c4.getId(), c5.getId(), c4.getTree().getId(),
  528. c5.getTree().getId(), contentC.getId(),
  529. contentD.getId(), contentE.getId()));
  530. }
  531. @Test
  532. public void testShallowFetchShallowParentDepth1() throws Exception {
  533. FileRepository repo = setupRepoForShallowFetch();
  534. PackIndex idx = writeShallowPack(repo, 1, wants(c5), NONE, NONE);
  535. assertContent(idx,
  536. Arrays.asList(c5.getId(), c5.getTree().getId(),
  537. contentA.getId(), contentB.getId(), contentC.getId(),
  538. contentD.getId(), contentE.getId()));
  539. idx = writeShallowPack(repo, 1, wants(c4), haves(c5), shallows(c5));
  540. assertContent(idx, Arrays.asList(c4.getId(), c4.getTree().getId()));
  541. }
  542. @Test
  543. public void testShallowFetchShallowParentDepth2() throws Exception {
  544. FileRepository repo = setupRepoForShallowFetch();
  545. PackIndex idx = writeShallowPack(repo, 2, wants(c5), NONE, NONE);
  546. assertContent(idx,
  547. Arrays.asList(c4.getId(), c5.getId(), c4.getTree().getId(),
  548. c5.getTree().getId(), contentA.getId(),
  549. contentB.getId(), contentC.getId(), contentD.getId(),
  550. contentE.getId()));
  551. idx = writeShallowPack(repo, 2, wants(c3), haves(c4, c5), shallows(c4));
  552. assertContent(idx, Arrays.asList(c2.getId(), c3.getId(),
  553. c2.getTree().getId(), c3.getTree().getId()));
  554. }
  555. @Test
  556. public void testShallowFetchShallowAncestorDepth1() throws Exception {
  557. FileRepository repo = setupRepoForShallowFetch();
  558. PackIndex idx = writeShallowPack(repo, 1, wants(c5), NONE, NONE);
  559. assertContent(idx,
  560. Arrays.asList(c5.getId(), c5.getTree().getId(),
  561. contentA.getId(), contentB.getId(), contentC.getId(),
  562. contentD.getId(), contentE.getId()));
  563. idx = writeShallowPack(repo, 1, wants(c3), haves(c5), shallows(c5));
  564. assertContent(idx, Arrays.asList(c3.getId(), c3.getTree().getId()));
  565. }
  566. @Test
  567. public void testShallowFetchShallowAncestorDepth2() throws Exception {
  568. FileRepository repo = setupRepoForShallowFetch();
  569. PackIndex idx = writeShallowPack(repo, 2, wants(c5), NONE, NONE);
  570. assertContent(idx,
  571. Arrays.asList(c4.getId(), c5.getId(), c4.getTree().getId(),
  572. c5.getTree().getId(), contentA.getId(),
  573. contentB.getId(), contentC.getId(), contentD.getId(),
  574. contentE.getId()));
  575. idx = writeShallowPack(repo, 2, wants(c2), haves(c4, c5), shallows(c4));
  576. assertContent(idx, Arrays.asList(c1.getId(), c2.getId(),
  577. c1.getTree().getId(), c2.getTree().getId()));
  578. }
  579. private FileRepository setupRepoForShallowFetch() throws Exception {
  580. FileRepository repo = createBareRepository();
  581. TestRepository<Repository> r = new TestRepository<>(repo);
  582. BranchBuilder bb = r.branch("refs/heads/master");
  583. contentA = r.blob("A");
  584. contentB = r.blob("B");
  585. contentC = r.blob("C");
  586. contentD = r.blob("D");
  587. contentE = r.blob("E");
  588. c1 = bb.commit().add("a", contentA).create();
  589. c2 = bb.commit().add("b", contentB).create();
  590. c3 = bb.commit().add("c", contentC).create();
  591. c4 = bb.commit().add("d", contentD).create();
  592. c5 = bb.commit().add("e", contentE).create();
  593. r.getRevWalk().parseHeaders(c5); // fully initialize the tip RevCommit
  594. return repo;
  595. }
  596. private static PackIndex writePack(FileRepository repo,
  597. Set<? extends ObjectId> want, Set<ObjectIdSet> excludeObjects)
  598. throws IOException {
  599. RevWalk walk = new RevWalk(repo);
  600. return writePack(repo, walk, 0, want, NONE, excludeObjects);
  601. }
  602. private static PackIndex writeShallowPack(FileRepository repo, int depth,
  603. Set<? extends ObjectId> want, Set<? extends ObjectId> have,
  604. Set<? extends ObjectId> shallow) throws IOException {
  605. // During negotiation, UploadPack would have set up a DepthWalk and
  606. // marked the client's "shallow" commits. Emulate that here.
  607. DepthWalk.RevWalk walk = new DepthWalk.RevWalk(repo, depth - 1);
  608. walk.assumeShallow(shallow);
  609. return writePack(repo, walk, depth, want, have, EMPTY_ID_SET);
  610. }
  611. private static PackIndex writePack(FileRepository repo, RevWalk walk,
  612. int depth, Set<? extends ObjectId> want,
  613. Set<? extends ObjectId> have, Set<ObjectIdSet> excludeObjects)
  614. throws IOException {
  615. try (PackWriter pw = new PackWriter(repo)) {
  616. pw.setDeltaBaseAsOffset(true);
  617. pw.setReuseDeltaCommits(false);
  618. for (ObjectIdSet idx : excludeObjects) {
  619. pw.excludeObjects(idx);
  620. }
  621. if (depth > 0) {
  622. pw.setShallowPack(depth, null);
  623. }
  624. ObjectWalk ow = walk.toObjectWalkWithSameObjects();
  625. pw.preparePack(NullProgressMonitor.INSTANCE, ow, want, have, NONE);
  626. String id = pw.computeName().getName();
  627. File packdir = new File(repo.getObjectsDirectory(), "pack");
  628. File packFile = new File(packdir, "pack-" + id + ".pack");
  629. FileOutputStream packOS = new FileOutputStream(packFile);
  630. pw.writePack(NullProgressMonitor.INSTANCE,
  631. NullProgressMonitor.INSTANCE, packOS);
  632. packOS.close();
  633. File idxFile = new File(packdir, "pack-" + id + ".idx");
  634. FileOutputStream idxOS = new FileOutputStream(idxFile);
  635. pw.writeIndex(idxOS);
  636. idxOS.close();
  637. return PackIndex.open(idxFile);
  638. }
  639. }
  640. // TODO: testWritePackDeltasCycle()
  641. // TODO: testWritePackDeltasDepth()
  642. private void writeVerifyPack1() throws IOException {
  643. final HashSet<ObjectId> interestings = new HashSet<>();
  644. interestings.add(ObjectId
  645. .fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"));
  646. createVerifyOpenPack(interestings, NONE, false, false);
  647. final ObjectId expectedOrder[] = new ObjectId[] {
  648. ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"),
  649. ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799"),
  650. ObjectId.fromString("540a36d136cf413e4b064c2b0e0a4db60f77feab"),
  651. ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"),
  652. ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327"),
  653. ObjectId.fromString("4b825dc642cb6eb9a060e54bf8d69288fbee4904"),
  654. ObjectId.fromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3"),
  655. ObjectId.fromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259") };
  656. assertEquals(expectedOrder.length, writer.getObjectCount());
  657. verifyObjectsOrder(expectedOrder);
  658. assertEquals("34be9032ac282b11fa9babdc2b2a93ca996c9c2f", writer
  659. .computeName().name());
  660. }
  661. private void writeVerifyPack2(boolean deltaReuse) throws IOException {
  662. config.setReuseDeltas(deltaReuse);
  663. final HashSet<ObjectId> interestings = new HashSet<>();
  664. interestings.add(ObjectId
  665. .fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"));
  666. final HashSet<ObjectId> uninterestings = new HashSet<>();
  667. uninterestings.add(ObjectId
  668. .fromString("540a36d136cf413e4b064c2b0e0a4db60f77feab"));
  669. createVerifyOpenPack(interestings, uninterestings, false, false);
  670. final ObjectId expectedOrder[] = new ObjectId[] {
  671. ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"),
  672. ObjectId.fromString("c59759f143fb1fe21c197981df75a7ee00290799"),
  673. ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"),
  674. ObjectId.fromString("902d5476fa249b7abc9d84c611577a81381f0327"),
  675. ObjectId.fromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3") ,
  676. ObjectId.fromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259") };
  677. if (!config.isReuseDeltas() && !config.isDeltaCompress()) {
  678. // If no deltas are in the file the final two entries swap places.
  679. swap(expectedOrder, 4, 5);
  680. }
  681. assertEquals(expectedOrder.length, writer.getObjectCount());
  682. verifyObjectsOrder(expectedOrder);
  683. assertEquals("ed3f96b8327c7c66b0f8f70056129f0769323d86", writer
  684. .computeName().name());
  685. }
  686. private static void swap(ObjectId[] arr, int a, int b) {
  687. ObjectId tmp = arr[a];
  688. arr[a] = arr[b];
  689. arr[b] = tmp;
  690. }
  691. private void writeVerifyPack4(final boolean thin) throws IOException {
  692. final HashSet<ObjectId> interestings = new HashSet<>();
  693. interestings.add(ObjectId
  694. .fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"));
  695. final HashSet<ObjectId> uninterestings = new HashSet<>();
  696. uninterestings.add(ObjectId
  697. .fromString("c59759f143fb1fe21c197981df75a7ee00290799"));
  698. createVerifyOpenPack(interestings, uninterestings, thin, false);
  699. final ObjectId writtenObjects[] = new ObjectId[] {
  700. ObjectId.fromString("82c6b885ff600be425b4ea96dee75dca255b69e7"),
  701. ObjectId.fromString("aabf2ffaec9b497f0950352b3e582d73035c2035"),
  702. ObjectId.fromString("5b6e7c66c276e7610d4a73c70ec1a1f7c1003259") };
  703. assertEquals(writtenObjects.length, writer.getObjectCount());
  704. ObjectId expectedObjects[];
  705. if (thin) {
  706. expectedObjects = new ObjectId[4];
  707. System.arraycopy(writtenObjects, 0, expectedObjects, 0,
  708. writtenObjects.length);
  709. expectedObjects[3] = ObjectId
  710. .fromString("6ff87c4664981e4397625791c8ea3bbb5f2279a3");
  711. } else {
  712. expectedObjects = writtenObjects;
  713. }
  714. verifyObjectsOrder(expectedObjects);
  715. assertEquals("cded4b74176b4456afa456768b2b5aafb41c44fc", writer
  716. .computeName().name());
  717. }
  718. private void createVerifyOpenPack(final Set<ObjectId> interestings,
  719. final Set<ObjectId> uninterestings, final boolean thin,
  720. final boolean ignoreMissingUninteresting)
  721. throws MissingObjectException, IOException {
  722. createVerifyOpenPack(interestings, uninterestings, thin,
  723. ignoreMissingUninteresting, false);
  724. }
  725. private void createVerifyOpenPack(final Set<ObjectId> interestings,
  726. final Set<ObjectId> uninterestings, final boolean thin,
  727. final boolean ignoreMissingUninteresting, boolean useBitmaps)
  728. throws MissingObjectException, IOException {
  729. NullProgressMonitor m = NullProgressMonitor.INSTANCE;
  730. writer = new PackWriter(config, db.newObjectReader());
  731. writer.setUseBitmaps(useBitmaps);
  732. writer.setThin(thin);
  733. writer.setIgnoreMissingUninteresting(ignoreMissingUninteresting);
  734. writer.preparePack(m, interestings, uninterestings);
  735. writer.writePack(m, m, os);
  736. writer.close();
  737. verifyOpenPack(thin);
  738. }
  739. private void createVerifyOpenPack(final List<RevObject> objectSource)
  740. throws MissingObjectException, IOException {
  741. NullProgressMonitor m = NullProgressMonitor.INSTANCE;
  742. writer = new PackWriter(config, db.newObjectReader());
  743. writer.preparePack(objectSource.iterator());
  744. assertEquals(objectSource.size(), writer.getObjectCount());
  745. writer.writePack(m, m, os);
  746. writer.close();
  747. verifyOpenPack(false);
  748. }
  749. private void verifyOpenPack(final boolean thin) throws IOException {
  750. final byte[] packData = os.toByteArray();
  751. if (thin) {
  752. PackParser p = index(packData);
  753. try {
  754. p.parse(NullProgressMonitor.INSTANCE);
  755. fail("indexer should grumble about missing object");
  756. } catch (IOException x) {
  757. // expected
  758. }
  759. }
  760. ObjectDirectoryPackParser p = (ObjectDirectoryPackParser) index(packData);
  761. p.setKeepEmpty(true);
  762. p.setAllowThin(thin);
  763. p.setIndexVersion(2);
  764. p.parse(NullProgressMonitor.INSTANCE);
  765. pack = p.getPackFile();
  766. assertNotNull("have PackFile after parsing", pack);
  767. }
  768. private PackParser index(final byte[] packData) throws IOException {
  769. if (inserter == null)
  770. inserter = dst.newObjectInserter();
  771. return inserter.newPackParser(new ByteArrayInputStream(packData));
  772. }
  773. private void verifyObjectsOrder(final ObjectId objectsOrder[]) {
  774. final List<PackIndex.MutableEntry> entries = new ArrayList<>();
  775. for (MutableEntry me : pack) {
  776. entries.add(me.cloneEntry());
  777. }
  778. Collections.sort(entries, new Comparator<PackIndex.MutableEntry>() {
  779. @Override
  780. public int compare(MutableEntry o1, MutableEntry o2) {
  781. return Long.signum(o1.getOffset() - o2.getOffset());
  782. }
  783. });
  784. int i = 0;
  785. for (MutableEntry me : entries) {
  786. assertEquals(objectsOrder[i++].toObjectId(), me.toObjectId());
  787. }
  788. }
  789. private static Set<ObjectId> haves(ObjectId... objects) {
  790. return Sets.of(objects);
  791. }
  792. private static Set<ObjectId> wants(ObjectId... objects) {
  793. return Sets.of(objects);
  794. }
  795. private static Set<ObjectId> shallows(ObjectId... objects) {
  796. return Sets.of(objects);
  797. }
  798. }