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

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