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.

TestRepository.java 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. /*
  2. * Copyright (C) 2009-2010, Google Inc.
  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.junit;
  44. import static org.junit.Assert.assertEquals;
  45. import static org.junit.Assert.fail;
  46. import java.io.File;
  47. import java.io.FileOutputStream;
  48. import java.io.IOException;
  49. import java.io.OutputStream;
  50. import java.security.MessageDigest;
  51. import java.util.ArrayList;
  52. import java.util.Collections;
  53. import java.util.Date;
  54. import java.util.HashSet;
  55. import java.util.List;
  56. import java.util.Set;
  57. import org.eclipse.jgit.dircache.DirCache;
  58. import org.eclipse.jgit.dircache.DirCacheBuilder;
  59. import org.eclipse.jgit.dircache.DirCacheEditor;
  60. import org.eclipse.jgit.dircache.DirCacheEditor.DeletePath;
  61. import org.eclipse.jgit.dircache.DirCacheEditor.DeleteTree;
  62. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  63. import org.eclipse.jgit.dircache.DirCacheEntry;
  64. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  65. import org.eclipse.jgit.errors.MissingObjectException;
  66. import org.eclipse.jgit.errors.ObjectWritingException;
  67. import org.eclipse.jgit.internal.storage.file.FileRepository;
  68. import org.eclipse.jgit.internal.storage.file.LockFile;
  69. import org.eclipse.jgit.internal.storage.file.ObjectDirectory;
  70. import org.eclipse.jgit.internal.storage.file.PackFile;
  71. import org.eclipse.jgit.internal.storage.file.PackIndex.MutableEntry;
  72. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  73. import org.eclipse.jgit.lib.AnyObjectId;
  74. import org.eclipse.jgit.lib.Constants;
  75. import org.eclipse.jgit.lib.FileMode;
  76. import org.eclipse.jgit.lib.NullProgressMonitor;
  77. import org.eclipse.jgit.lib.ObjectChecker;
  78. import org.eclipse.jgit.lib.ObjectId;
  79. import org.eclipse.jgit.lib.ObjectInserter;
  80. import org.eclipse.jgit.lib.PersonIdent;
  81. import org.eclipse.jgit.lib.Ref;
  82. import org.eclipse.jgit.lib.RefUpdate;
  83. import org.eclipse.jgit.lib.RefWriter;
  84. import org.eclipse.jgit.lib.Repository;
  85. import org.eclipse.jgit.lib.TagBuilder;
  86. import org.eclipse.jgit.revwalk.ObjectWalk;
  87. import org.eclipse.jgit.revwalk.RevBlob;
  88. import org.eclipse.jgit.revwalk.RevCommit;
  89. import org.eclipse.jgit.revwalk.RevObject;
  90. import org.eclipse.jgit.revwalk.RevTag;
  91. import org.eclipse.jgit.revwalk.RevTree;
  92. import org.eclipse.jgit.revwalk.RevWalk;
  93. import org.eclipse.jgit.treewalk.TreeWalk;
  94. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  95. import org.eclipse.jgit.util.FileUtils;
  96. import org.eclipse.jgit.util.io.SafeBufferedOutputStream;
  97. /**
  98. * Wrapper to make creating test data easier.
  99. *
  100. * @param <R>
  101. * type of Repository the test data is stored on.
  102. */
  103. public class TestRepository<R extends Repository> {
  104. private static final PersonIdent author;
  105. private static final PersonIdent committer;
  106. static {
  107. final MockSystemReader m = new MockSystemReader();
  108. final long now = m.getCurrentTime();
  109. final int tz = m.getTimezone(now);
  110. final String an = "J. Author";
  111. final String ae = "jauthor@example.com";
  112. author = new PersonIdent(an, ae, now, tz);
  113. final String cn = "J. Committer";
  114. final String ce = "jcommitter@example.com";
  115. committer = new PersonIdent(cn, ce, now, tz);
  116. }
  117. private final R db;
  118. private final RevWalk pool;
  119. private final ObjectInserter inserter;
  120. private long now;
  121. /**
  122. * Wrap a repository with test building tools.
  123. *
  124. * @param db
  125. * the test repository to write into.
  126. * @throws IOException
  127. */
  128. public TestRepository(R db) throws IOException {
  129. this(db, new RevWalk(db));
  130. }
  131. /**
  132. * Wrap a repository with test building tools.
  133. *
  134. * @param db
  135. * the test repository to write into.
  136. * @param rw
  137. * the RevObject pool to use for object lookup.
  138. * @throws IOException
  139. */
  140. public TestRepository(R db, RevWalk rw) throws IOException {
  141. this.db = db;
  142. this.pool = rw;
  143. this.inserter = db.newObjectInserter();
  144. this.now = 1236977987000L;
  145. }
  146. /** @return the repository this helper class operates against. */
  147. public R getRepository() {
  148. return db;
  149. }
  150. /** @return get the RevWalk pool all objects are allocated through. */
  151. public RevWalk getRevWalk() {
  152. return pool;
  153. }
  154. /** @return current time adjusted by {@link #tick(int)}. */
  155. public Date getClock() {
  156. return new Date(now);
  157. }
  158. /**
  159. * Adjust the current time that will used by the next commit.
  160. *
  161. * @param secDelta
  162. * number of seconds to add to the current time.
  163. */
  164. public void tick(final int secDelta) {
  165. now += secDelta * 1000L;
  166. }
  167. /**
  168. * Set the author and committer using {@link #getClock()}.
  169. *
  170. * @param c
  171. * the commit builder to store.
  172. */
  173. public void setAuthorAndCommitter(org.eclipse.jgit.lib.CommitBuilder c) {
  174. c.setAuthor(new PersonIdent(author, new Date(now)));
  175. c.setCommitter(new PersonIdent(committer, new Date(now)));
  176. }
  177. /**
  178. * Create a new blob object in the repository.
  179. *
  180. * @param content
  181. * file content, will be UTF-8 encoded.
  182. * @return reference to the blob.
  183. * @throws Exception
  184. */
  185. public RevBlob blob(final String content) throws Exception {
  186. return blob(content.getBytes("UTF-8"));
  187. }
  188. /**
  189. * Create a new blob object in the repository.
  190. *
  191. * @param content
  192. * binary file content.
  193. * @return reference to the blob.
  194. * @throws Exception
  195. */
  196. public RevBlob blob(final byte[] content) throws Exception {
  197. ObjectId id;
  198. try (ObjectInserter ins = inserter) {
  199. id = ins.insert(Constants.OBJ_BLOB, content);
  200. ins.flush();
  201. }
  202. return pool.lookupBlob(id);
  203. }
  204. /**
  205. * Construct a regular file mode tree entry.
  206. *
  207. * @param path
  208. * path of the file.
  209. * @param blob
  210. * a blob, previously constructed in the repository.
  211. * @return the entry.
  212. * @throws Exception
  213. */
  214. public DirCacheEntry file(final String path, final RevBlob blob)
  215. throws Exception {
  216. final DirCacheEntry e = new DirCacheEntry(path);
  217. e.setFileMode(FileMode.REGULAR_FILE);
  218. e.setObjectId(blob);
  219. return e;
  220. }
  221. /**
  222. * Construct a tree from a specific listing of file entries.
  223. *
  224. * @param entries
  225. * the files to include in the tree. The collection does not need
  226. * to be sorted properly and may be empty.
  227. * @return reference to the tree specified by the entry list.
  228. * @throws Exception
  229. */
  230. public RevTree tree(final DirCacheEntry... entries) throws Exception {
  231. final DirCache dc = DirCache.newInCore();
  232. final DirCacheBuilder b = dc.builder();
  233. for (final DirCacheEntry e : entries)
  234. b.add(e);
  235. b.finish();
  236. ObjectId root;
  237. try (ObjectInserter ins = inserter) {
  238. root = dc.writeTree(ins);
  239. ins.flush();
  240. }
  241. return pool.lookupTree(root);
  242. }
  243. /**
  244. * Lookup an entry stored in a tree, failing if not present.
  245. *
  246. * @param tree
  247. * the tree to search.
  248. * @param path
  249. * the path to find the entry of.
  250. * @return the parsed object entry at this path, never null.
  251. * @throws Exception
  252. */
  253. public RevObject get(final RevTree tree, final String path)
  254. throws Exception {
  255. try (TreeWalk tw = new TreeWalk(pool.getObjectReader())) {
  256. tw.setFilter(PathFilterGroup.createFromStrings(Collections
  257. .singleton(path)));
  258. tw.reset(tree);
  259. while (tw.next()) {
  260. if (tw.isSubtree() && !path.equals(tw.getPathString())) {
  261. tw.enterSubtree();
  262. continue;
  263. }
  264. final ObjectId entid = tw.getObjectId(0);
  265. final FileMode entmode = tw.getFileMode(0);
  266. return pool.lookupAny(entid, entmode.getObjectType());
  267. }
  268. }
  269. fail("Can't find " + path + " in tree " + tree.name());
  270. return null; // never reached.
  271. }
  272. /**
  273. * Create a new commit.
  274. * <p>
  275. * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
  276. * tree (no files or subdirectories).
  277. *
  278. * @param parents
  279. * zero or more parents of the commit.
  280. * @return the new commit.
  281. * @throws Exception
  282. */
  283. public RevCommit commit(final RevCommit... parents) throws Exception {
  284. return commit(1, tree(), parents);
  285. }
  286. /**
  287. * Create a new commit.
  288. * <p>
  289. * See {@link #commit(int, RevTree, RevCommit...)}.
  290. *
  291. * @param tree
  292. * the root tree for the commit.
  293. * @param parents
  294. * zero or more parents of the commit.
  295. * @return the new commit.
  296. * @throws Exception
  297. */
  298. public RevCommit commit(final RevTree tree, final RevCommit... parents)
  299. throws Exception {
  300. return commit(1, tree, parents);
  301. }
  302. /**
  303. * Create a new commit.
  304. * <p>
  305. * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
  306. * tree (no files or subdirectories).
  307. *
  308. * @param secDelta
  309. * number of seconds to advance {@link #tick(int)} by.
  310. * @param parents
  311. * zero or more parents of the commit.
  312. * @return the new commit.
  313. * @throws Exception
  314. */
  315. public RevCommit commit(final int secDelta, final RevCommit... parents)
  316. throws Exception {
  317. return commit(secDelta, tree(), parents);
  318. }
  319. /**
  320. * Create a new commit.
  321. * <p>
  322. * The author and committer identities are stored using the current
  323. * timestamp, after being incremented by {@code secDelta}. The message body
  324. * is empty.
  325. *
  326. * @param secDelta
  327. * number of seconds to advance {@link #tick(int)} by.
  328. * @param tree
  329. * the root tree for the commit.
  330. * @param parents
  331. * zero or more parents of the commit.
  332. * @return the new commit.
  333. * @throws Exception
  334. */
  335. public RevCommit commit(final int secDelta, final RevTree tree,
  336. final RevCommit... parents) throws Exception {
  337. tick(secDelta);
  338. final org.eclipse.jgit.lib.CommitBuilder c;
  339. c = new org.eclipse.jgit.lib.CommitBuilder();
  340. c.setTreeId(tree);
  341. c.setParentIds(parents);
  342. c.setAuthor(new PersonIdent(author, new Date(now)));
  343. c.setCommitter(new PersonIdent(committer, new Date(now)));
  344. c.setMessage("");
  345. ObjectId id;
  346. try (ObjectInserter ins = inserter) {
  347. id = ins.insert(c);
  348. ins.flush();
  349. }
  350. return pool.lookupCommit(id);
  351. }
  352. /** @return a new commit builder. */
  353. public CommitBuilder commit() {
  354. return new CommitBuilder();
  355. }
  356. /**
  357. * Construct an annotated tag object pointing at another object.
  358. * <p>
  359. * The tagger is the committer identity, at the current time as specified by
  360. * {@link #tick(int)}. The time is not increased.
  361. * <p>
  362. * The tag message is empty.
  363. *
  364. * @param name
  365. * name of the tag. Traditionally a tag name should not start
  366. * with {@code refs/tags/}.
  367. * @param dst
  368. * object the tag should be pointed at.
  369. * @return the annotated tag object.
  370. * @throws Exception
  371. */
  372. public RevTag tag(final String name, final RevObject dst) throws Exception {
  373. final TagBuilder t = new TagBuilder();
  374. t.setObjectId(dst);
  375. t.setTag(name);
  376. t.setTagger(new PersonIdent(committer, new Date(now)));
  377. t.setMessage("");
  378. ObjectId id;
  379. try (ObjectInserter ins = inserter) {
  380. id = ins.insert(t);
  381. ins.flush();
  382. }
  383. return (RevTag) pool.lookupAny(id, Constants.OBJ_TAG);
  384. }
  385. /**
  386. * Update a reference to point to an object.
  387. *
  388. * @param ref
  389. * the name of the reference to update to. If {@code ref} does
  390. * not start with {@code refs/} and is not the magic names
  391. * {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
  392. * {@code refs/heads/} will be prefixed in front of the given
  393. * name, thereby assuming it is a branch.
  394. * @param to
  395. * the target object.
  396. * @return the target object.
  397. * @throws Exception
  398. */
  399. public RevCommit update(String ref, CommitBuilder to) throws Exception {
  400. return update(ref, to.create());
  401. }
  402. /**
  403. * Update a reference to point to an object.
  404. *
  405. * @param <T>
  406. * type of the target object.
  407. * @param ref
  408. * the name of the reference to update to. If {@code ref} does
  409. * not start with {@code refs/} and is not the magic names
  410. * {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
  411. * {@code refs/heads/} will be prefixed in front of the given
  412. * name, thereby assuming it is a branch.
  413. * @param obj
  414. * the target object.
  415. * @return the target object.
  416. * @throws Exception
  417. */
  418. public <T extends AnyObjectId> T update(String ref, T obj) throws Exception {
  419. if (Constants.HEAD.equals(ref)) {
  420. // nothing
  421. } else if ("FETCH_HEAD".equals(ref)) {
  422. // nothing
  423. } else if ("MERGE_HEAD".equals(ref)) {
  424. // nothing
  425. } else if (ref.startsWith(Constants.R_REFS)) {
  426. // nothing
  427. } else
  428. ref = Constants.R_HEADS + ref;
  429. RefUpdate u = db.updateRef(ref);
  430. u.setNewObjectId(obj);
  431. switch (u.forceUpdate()) {
  432. case FAST_FORWARD:
  433. case FORCED:
  434. case NEW:
  435. case NO_CHANGE:
  436. updateServerInfo();
  437. return obj;
  438. default:
  439. throw new IOException("Cannot write " + ref + " " + u.getResult());
  440. }
  441. }
  442. /**
  443. * Update the dumb client server info files.
  444. *
  445. * @throws Exception
  446. */
  447. public void updateServerInfo() throws Exception {
  448. if (db instanceof FileRepository) {
  449. final FileRepository fr = (FileRepository) db;
  450. RefWriter rw = new RefWriter(fr.getAllRefs().values()) {
  451. @Override
  452. protected void writeFile(final String name, final byte[] bin)
  453. throws IOException {
  454. File path = new File(fr.getDirectory(), name);
  455. TestRepository.this.writeFile(path, bin);
  456. }
  457. };
  458. rw.writePackedRefs();
  459. rw.writeInfoRefs();
  460. final StringBuilder w = new StringBuilder();
  461. for (PackFile p : fr.getObjectDatabase().getPacks()) {
  462. w.append("P ");
  463. w.append(p.getPackFile().getName());
  464. w.append('\n');
  465. }
  466. writeFile(new File(new File(fr.getObjectDatabase().getDirectory(),
  467. "info"), "packs"), Constants.encodeASCII(w.toString()));
  468. }
  469. }
  470. /**
  471. * Ensure the body of the given object has been parsed.
  472. *
  473. * @param <T>
  474. * type of object, e.g. {@link RevTag} or {@link RevCommit}.
  475. * @param object
  476. * reference to the (possibly unparsed) object to force body
  477. * parsing of.
  478. * @return {@code object}
  479. * @throws Exception
  480. */
  481. public <T extends RevObject> T parseBody(final T object) throws Exception {
  482. pool.parseBody(object);
  483. return object;
  484. }
  485. /**
  486. * Create a new branch builder for this repository.
  487. *
  488. * @param ref
  489. * name of the branch to be constructed. If {@code ref} does not
  490. * start with {@code refs/} the prefix {@code refs/heads/} will
  491. * be added.
  492. * @return builder for the named branch.
  493. */
  494. public BranchBuilder branch(String ref) {
  495. if (Constants.HEAD.equals(ref)) {
  496. // nothing
  497. } else if (ref.startsWith(Constants.R_REFS)) {
  498. // nothing
  499. } else
  500. ref = Constants.R_HEADS + ref;
  501. return new BranchBuilder(ref);
  502. }
  503. /**
  504. * Tag an object using a lightweight tag.
  505. *
  506. * @param name
  507. * the tag name. The /refs/tags/ prefix will be added if the name
  508. * doesn't start with it
  509. * @param obj
  510. * the object to tag
  511. * @return the tagged object
  512. * @throws Exception
  513. */
  514. public ObjectId lightweightTag(String name, ObjectId obj) throws Exception {
  515. if (!name.startsWith(Constants.R_TAGS))
  516. name = Constants.R_TAGS + name;
  517. return update(name, obj);
  518. }
  519. /**
  520. * Run consistency checks against the object database.
  521. * <p>
  522. * This method completes silently if the checks pass. A temporary revision
  523. * pool is constructed during the checking.
  524. *
  525. * @param tips
  526. * the tips to start checking from; if not supplied the refs of
  527. * the repository are used instead.
  528. * @throws MissingObjectException
  529. * @throws IncorrectObjectTypeException
  530. * @throws IOException
  531. */
  532. public void fsck(RevObject... tips) throws MissingObjectException,
  533. IncorrectObjectTypeException, IOException {
  534. try (ObjectWalk ow = new ObjectWalk(db)) {
  535. if (tips.length != 0) {
  536. for (RevObject o : tips)
  537. ow.markStart(ow.parseAny(o));
  538. } else {
  539. for (Ref r : db.getAllRefs().values())
  540. ow.markStart(ow.parseAny(r.getObjectId()));
  541. }
  542. ObjectChecker oc = new ObjectChecker();
  543. for (;;) {
  544. final RevCommit o = ow.next();
  545. if (o == null)
  546. break;
  547. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  548. oc.checkCommit(bin);
  549. assertHash(o, bin);
  550. }
  551. for (;;) {
  552. final RevObject o = ow.nextObject();
  553. if (o == null)
  554. break;
  555. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  556. oc.check(o.getType(), bin);
  557. assertHash(o, bin);
  558. }
  559. }
  560. }
  561. private static void assertHash(RevObject id, byte[] bin) {
  562. MessageDigest md = Constants.newMessageDigest();
  563. md.update(Constants.encodedTypeString(id.getType()));
  564. md.update((byte) ' ');
  565. md.update(Constants.encodeASCII(bin.length));
  566. md.update((byte) 0);
  567. md.update(bin);
  568. assertEquals(id, ObjectId.fromRaw(md.digest()));
  569. }
  570. /**
  571. * Pack all reachable objects in the repository into a single pack file.
  572. * <p>
  573. * All loose objects are automatically pruned. Existing packs however are
  574. * not removed.
  575. *
  576. * @throws Exception
  577. */
  578. public void packAndPrune() throws Exception {
  579. if (db.getObjectDatabase() instanceof ObjectDirectory) {
  580. ObjectDirectory odb = (ObjectDirectory) db.getObjectDatabase();
  581. NullProgressMonitor m = NullProgressMonitor.INSTANCE;
  582. final File pack, idx;
  583. try (PackWriter pw = new PackWriter(db)) {
  584. Set<ObjectId> all = new HashSet<ObjectId>();
  585. for (Ref r : db.getAllRefs().values())
  586. all.add(r.getObjectId());
  587. pw.preparePack(m, all, Collections.<ObjectId> emptySet());
  588. final ObjectId name = pw.computeName();
  589. pack = nameFor(odb, name, ".pack");
  590. try (OutputStream out =
  591. new SafeBufferedOutputStream(new FileOutputStream(pack))) {
  592. pw.writePack(m, m, out);
  593. }
  594. pack.setReadOnly();
  595. idx = nameFor(odb, name, ".idx");
  596. try (OutputStream out =
  597. new SafeBufferedOutputStream(new FileOutputStream(idx))) {
  598. pw.writeIndex(out);
  599. }
  600. idx.setReadOnly();
  601. }
  602. odb.openPack(pack);
  603. updateServerInfo();
  604. prunePacked(odb);
  605. }
  606. }
  607. private static void prunePacked(ObjectDirectory odb) throws IOException {
  608. for (PackFile p : odb.getPacks()) {
  609. for (MutableEntry e : p)
  610. FileUtils.delete(odb.fileFor(e.toObjectId()));
  611. }
  612. }
  613. private static File nameFor(ObjectDirectory odb, ObjectId name, String t) {
  614. File packdir = new File(odb.getDirectory(), "pack");
  615. return new File(packdir, "pack-" + name.name() + t);
  616. }
  617. private void writeFile(final File p, final byte[] bin) throws IOException,
  618. ObjectWritingException {
  619. final LockFile lck = new LockFile(p, db.getFS());
  620. if (!lck.lock())
  621. throw new ObjectWritingException("Can't write " + p);
  622. try {
  623. lck.write(bin);
  624. } catch (IOException ioe) {
  625. throw new ObjectWritingException("Can't write " + p);
  626. }
  627. if (!lck.commit())
  628. throw new ObjectWritingException("Can't write " + p);
  629. }
  630. /** Helper to build a branch with one or more commits */
  631. public class BranchBuilder {
  632. private final String ref;
  633. BranchBuilder(final String ref) {
  634. this.ref = ref;
  635. }
  636. /**
  637. * @return construct a new commit builder that updates this branch. If
  638. * the branch already exists, the commit builder will have its
  639. * first parent as the current commit and its tree will be
  640. * initialized to the current files.
  641. * @throws Exception
  642. * the commit builder can't read the current branch state
  643. */
  644. public CommitBuilder commit() throws Exception {
  645. return new CommitBuilder(this);
  646. }
  647. /**
  648. * Forcefully update this branch to a particular commit.
  649. *
  650. * @param to
  651. * the commit to update to.
  652. * @return {@code to}.
  653. * @throws Exception
  654. */
  655. public RevCommit update(CommitBuilder to) throws Exception {
  656. return update(to.create());
  657. }
  658. /**
  659. * Forcefully update this branch to a particular commit.
  660. *
  661. * @param to
  662. * the commit to update to.
  663. * @return {@code to}.
  664. * @throws Exception
  665. */
  666. public RevCommit update(RevCommit to) throws Exception {
  667. return TestRepository.this.update(ref, to);
  668. }
  669. }
  670. /** Helper to generate a commit. */
  671. public class CommitBuilder {
  672. private final BranchBuilder branch;
  673. private final DirCache tree = DirCache.newInCore();
  674. private ObjectId topLevelTree;
  675. private final List<RevCommit> parents = new ArrayList<RevCommit>(2);
  676. private int tick = 1;
  677. private String message = "";
  678. private RevCommit self;
  679. CommitBuilder() {
  680. branch = null;
  681. }
  682. CommitBuilder(BranchBuilder b) throws Exception {
  683. branch = b;
  684. Ref ref = db.getRef(branch.ref);
  685. if (ref != null) {
  686. parent(pool.parseCommit(ref.getObjectId()));
  687. }
  688. }
  689. CommitBuilder(CommitBuilder prior) throws Exception {
  690. branch = prior.branch;
  691. DirCacheBuilder b = tree.builder();
  692. for (int i = 0; i < prior.tree.getEntryCount(); i++)
  693. b.add(prior.tree.getEntry(i));
  694. b.finish();
  695. parents.add(prior.create());
  696. }
  697. public CommitBuilder parent(RevCommit p) throws Exception {
  698. if (parents.isEmpty()) {
  699. DirCacheBuilder b = tree.builder();
  700. parseBody(p);
  701. b.addTree(new byte[0], DirCacheEntry.STAGE_0, pool
  702. .getObjectReader(), p.getTree());
  703. b.finish();
  704. }
  705. parents.add(p);
  706. return this;
  707. }
  708. public CommitBuilder noParents() {
  709. parents.clear();
  710. return this;
  711. }
  712. public CommitBuilder noFiles() {
  713. tree.clear();
  714. return this;
  715. }
  716. public CommitBuilder setTopLevelTree(ObjectId treeId) {
  717. topLevelTree = treeId;
  718. return this;
  719. }
  720. public CommitBuilder add(String path, String content) throws Exception {
  721. return add(path, blob(content));
  722. }
  723. public CommitBuilder add(String path, final RevBlob id)
  724. throws Exception {
  725. return edit(new PathEdit(path) {
  726. @Override
  727. public void apply(DirCacheEntry ent) {
  728. ent.setFileMode(FileMode.REGULAR_FILE);
  729. ent.setObjectId(id);
  730. }
  731. });
  732. }
  733. public CommitBuilder edit(PathEdit edit) {
  734. DirCacheEditor e = tree.editor();
  735. e.add(edit);
  736. e.finish();
  737. return this;
  738. }
  739. public CommitBuilder rm(String path) {
  740. DirCacheEditor e = tree.editor();
  741. e.add(new DeletePath(path));
  742. e.add(new DeleteTree(path));
  743. e.finish();
  744. return this;
  745. }
  746. public CommitBuilder message(String m) {
  747. message = m;
  748. return this;
  749. }
  750. public CommitBuilder tick(int secs) {
  751. tick = secs;
  752. return this;
  753. }
  754. public RevCommit create() throws Exception {
  755. if (self == null) {
  756. TestRepository.this.tick(tick);
  757. final org.eclipse.jgit.lib.CommitBuilder c;
  758. c = new org.eclipse.jgit.lib.CommitBuilder();
  759. c.setParentIds(parents);
  760. setAuthorAndCommitter(c);
  761. c.setMessage(message);
  762. ObjectId commitId;
  763. try (ObjectInserter ins = inserter) {
  764. if (topLevelTree != null)
  765. c.setTreeId(topLevelTree);
  766. else
  767. c.setTreeId(tree.writeTree(ins));
  768. commitId = ins.insert(c);
  769. ins.flush();
  770. }
  771. self = pool.lookupCommit(commitId);
  772. if (branch != null)
  773. branch.update(self);
  774. }
  775. return self;
  776. }
  777. public CommitBuilder child() throws Exception {
  778. return new CommitBuilder(this);
  779. }
  780. }
  781. }