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

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