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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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 {
  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. * Tag an object using a lightweight tag.
  512. *
  513. * @param name
  514. * the tag name. The /refs/tags/ prefix will be added if the name
  515. * doesn't start with it
  516. * @param obj
  517. * the object to tag
  518. * @return the tagged object
  519. * @throws Exception
  520. */
  521. public ObjectId lightweightTag(String name, ObjectId obj) throws Exception {
  522. if (!name.startsWith(Constants.R_TAGS))
  523. name = Constants.R_TAGS + name;
  524. return update(name, obj);
  525. }
  526. /**
  527. * Run consistency checks against the object database.
  528. * <p>
  529. * This method completes silently if the checks pass. A temporary revision
  530. * pool is constructed during the checking.
  531. *
  532. * @param tips
  533. * the tips to start checking from; if not supplied the refs of
  534. * the repository are used instead.
  535. * @throws MissingObjectException
  536. * @throws IncorrectObjectTypeException
  537. * @throws IOException
  538. */
  539. public void fsck(RevObject... tips) throws MissingObjectException,
  540. IncorrectObjectTypeException, IOException {
  541. ObjectWalk ow = new ObjectWalk(db);
  542. if (tips.length != 0) {
  543. for (RevObject o : tips)
  544. ow.markStart(ow.parseAny(o));
  545. } else {
  546. for (Ref r : db.getAllRefs().values())
  547. ow.markStart(ow.parseAny(r.getObjectId()));
  548. }
  549. ObjectChecker oc = new ObjectChecker();
  550. for (;;) {
  551. final RevCommit o = ow.next();
  552. if (o == null)
  553. break;
  554. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  555. oc.checkCommit(bin);
  556. assertHash(o, bin);
  557. }
  558. for (;;) {
  559. final RevObject o = ow.nextObject();
  560. if (o == null)
  561. break;
  562. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  563. oc.check(o.getType(), bin);
  564. assertHash(o, bin);
  565. }
  566. }
  567. private static void assertHash(RevObject id, byte[] bin) {
  568. MessageDigest md = Constants.newMessageDigest();
  569. md.update(Constants.encodedTypeString(id.getType()));
  570. md.update((byte) ' ');
  571. md.update(Constants.encodeASCII(bin.length));
  572. md.update((byte) 0);
  573. md.update(bin);
  574. assertEquals(id, ObjectId.fromRaw(md.digest()));
  575. }
  576. /**
  577. * Pack all reachable objects in the repository into a single pack file.
  578. * <p>
  579. * All loose objects are automatically pruned. Existing packs however are
  580. * not removed.
  581. *
  582. * @throws Exception
  583. */
  584. public void packAndPrune() throws Exception {
  585. if (db.getObjectDatabase() instanceof ObjectDirectory) {
  586. ObjectDirectory odb = (ObjectDirectory) db.getObjectDatabase();
  587. NullProgressMonitor m = NullProgressMonitor.INSTANCE;
  588. final File pack, idx;
  589. PackWriter pw = new PackWriter(db);
  590. try {
  591. Set<ObjectId> all = new HashSet<ObjectId>();
  592. for (Ref r : db.getAllRefs().values())
  593. all.add(r.getObjectId());
  594. pw.preparePack(m, all, Collections.<ObjectId> emptySet());
  595. final ObjectId name = pw.computeName();
  596. OutputStream out;
  597. pack = nameFor(odb, name, ".pack");
  598. out = new SafeBufferedOutputStream(new FileOutputStream(pack));
  599. try {
  600. pw.writePack(m, m, out);
  601. } finally {
  602. out.close();
  603. }
  604. pack.setReadOnly();
  605. idx = nameFor(odb, name, ".idx");
  606. out = new SafeBufferedOutputStream(new FileOutputStream(idx));
  607. try {
  608. pw.writeIndex(out);
  609. } finally {
  610. out.close();
  611. }
  612. idx.setReadOnly();
  613. } finally {
  614. pw.release();
  615. }
  616. odb.openPack(pack);
  617. updateServerInfo();
  618. prunePacked(odb);
  619. }
  620. }
  621. private static void prunePacked(ObjectDirectory odb) throws IOException {
  622. for (PackFile p : odb.getPacks()) {
  623. for (MutableEntry e : p)
  624. FileUtils.delete(odb.fileFor(e.toObjectId()));
  625. }
  626. }
  627. private static File nameFor(ObjectDirectory odb, ObjectId name, String t) {
  628. File packdir = new File(odb.getDirectory(), "pack");
  629. return new File(packdir, "pack-" + name.name() + t);
  630. }
  631. private void writeFile(final File p, final byte[] bin) throws IOException,
  632. ObjectWritingException {
  633. final LockFile lck = new LockFile(p, db.getFS());
  634. if (!lck.lock())
  635. throw new ObjectWritingException("Can't write " + p);
  636. try {
  637. lck.write(bin);
  638. } catch (IOException ioe) {
  639. throw new ObjectWritingException("Can't write " + p);
  640. }
  641. if (!lck.commit())
  642. throw new ObjectWritingException("Can't write " + p);
  643. }
  644. /** Helper to build a branch with one or more commits */
  645. public class BranchBuilder {
  646. private final String ref;
  647. BranchBuilder(final String ref) {
  648. this.ref = ref;
  649. }
  650. /**
  651. * @return construct a new commit builder that updates this branch. If
  652. * the branch already exists, the commit builder will have its
  653. * first parent as the current commit and its tree will be
  654. * initialized to the current files.
  655. * @throws Exception
  656. * the commit builder can't read the current branch state
  657. */
  658. public CommitBuilder commit() throws Exception {
  659. return new CommitBuilder(this);
  660. }
  661. /**
  662. * Forcefully update this branch to a particular commit.
  663. *
  664. * @param to
  665. * the commit to update to.
  666. * @return {@code to}.
  667. * @throws Exception
  668. */
  669. public RevCommit update(CommitBuilder to) throws Exception {
  670. return update(to.create());
  671. }
  672. /**
  673. * Forcefully update this branch to a particular commit.
  674. *
  675. * @param to
  676. * the commit to update to.
  677. * @return {@code to}.
  678. * @throws Exception
  679. */
  680. public RevCommit update(RevCommit to) throws Exception {
  681. return TestRepository.this.update(ref, to);
  682. }
  683. }
  684. /** Helper to generate a commit. */
  685. public class CommitBuilder {
  686. private final BranchBuilder branch;
  687. private final DirCache tree = DirCache.newInCore();
  688. private ObjectId topLevelTree;
  689. private final List<RevCommit> parents = new ArrayList<RevCommit>(2);
  690. private int tick = 1;
  691. private String message = "";
  692. private RevCommit self;
  693. CommitBuilder() {
  694. branch = null;
  695. }
  696. CommitBuilder(BranchBuilder b) throws Exception {
  697. branch = b;
  698. Ref ref = db.getRef(branch.ref);
  699. if (ref != null) {
  700. parent(pool.parseCommit(ref.getObjectId()));
  701. }
  702. }
  703. CommitBuilder(CommitBuilder prior) throws Exception {
  704. branch = prior.branch;
  705. DirCacheBuilder b = tree.builder();
  706. for (int i = 0; i < prior.tree.getEntryCount(); i++)
  707. b.add(prior.tree.getEntry(i));
  708. b.finish();
  709. parents.add(prior.create());
  710. }
  711. public CommitBuilder parent(RevCommit p) throws Exception {
  712. if (parents.isEmpty()) {
  713. DirCacheBuilder b = tree.builder();
  714. parseBody(p);
  715. b.addTree(new byte[0], DirCacheEntry.STAGE_0, pool
  716. .getObjectReader(), p.getTree());
  717. b.finish();
  718. }
  719. parents.add(p);
  720. return this;
  721. }
  722. public CommitBuilder noParents() {
  723. parents.clear();
  724. return this;
  725. }
  726. public CommitBuilder noFiles() {
  727. tree.clear();
  728. return this;
  729. }
  730. public CommitBuilder setTopLevelTree(ObjectId treeId) {
  731. topLevelTree = treeId;
  732. return this;
  733. }
  734. public CommitBuilder add(String path, String content) throws Exception {
  735. return add(path, blob(content));
  736. }
  737. public CommitBuilder add(String path, final RevBlob id)
  738. throws Exception {
  739. return edit(new PathEdit(path) {
  740. @Override
  741. public void apply(DirCacheEntry ent) {
  742. ent.setFileMode(FileMode.REGULAR_FILE);
  743. ent.setObjectId(id);
  744. }
  745. });
  746. }
  747. public CommitBuilder edit(PathEdit edit) {
  748. DirCacheEditor e = tree.editor();
  749. e.add(edit);
  750. e.finish();
  751. return this;
  752. }
  753. public CommitBuilder rm(String path) {
  754. DirCacheEditor e = tree.editor();
  755. e.add(new DeletePath(path));
  756. e.add(new DeleteTree(path));
  757. e.finish();
  758. return this;
  759. }
  760. public CommitBuilder message(String m) {
  761. message = m;
  762. return this;
  763. }
  764. public CommitBuilder tick(int secs) {
  765. tick = secs;
  766. return this;
  767. }
  768. public RevCommit create() throws Exception {
  769. if (self == null) {
  770. TestRepository.this.tick(tick);
  771. final org.eclipse.jgit.lib.CommitBuilder c;
  772. c = new org.eclipse.jgit.lib.CommitBuilder();
  773. c.setParentIds(parents);
  774. setAuthorAndCommitter(c);
  775. c.setMessage(message);
  776. ObjectId commitId;
  777. try {
  778. if (topLevelTree != null)
  779. c.setTreeId(topLevelTree);
  780. else
  781. c.setTreeId(tree.writeTree(inserter));
  782. commitId = inserter.insert(c);
  783. inserter.flush();
  784. } finally {
  785. inserter.release();
  786. }
  787. self = pool.lookupCommit(commitId);
  788. if (branch != null)
  789. branch.update(self);
  790. }
  791. return self;
  792. }
  793. public CommitBuilder child() throws Exception {
  794. return new CommitBuilder(this);
  795. }
  796. }
  797. }