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

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