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

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