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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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.Arrays;
  53. import java.util.Collections;
  54. import java.util.Date;
  55. import java.util.HashSet;
  56. import java.util.List;
  57. import java.util.Set;
  58. import java.util.TimeZone;
  59. import org.eclipse.jgit.api.Git;
  60. import org.eclipse.jgit.dircache.DirCache;
  61. import org.eclipse.jgit.dircache.DirCacheBuilder;
  62. import org.eclipse.jgit.dircache.DirCacheEditor;
  63. import org.eclipse.jgit.dircache.DirCacheEditor.DeletePath;
  64. import org.eclipse.jgit.dircache.DirCacheEditor.DeleteTree;
  65. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  66. import org.eclipse.jgit.dircache.DirCacheEntry;
  67. import org.eclipse.jgit.errors.IncorrectObjectTypeException;
  68. import org.eclipse.jgit.errors.MissingObjectException;
  69. import org.eclipse.jgit.errors.ObjectWritingException;
  70. import org.eclipse.jgit.internal.storage.file.FileRepository;
  71. import org.eclipse.jgit.internal.storage.file.LockFile;
  72. import org.eclipse.jgit.internal.storage.file.ObjectDirectory;
  73. import org.eclipse.jgit.internal.storage.file.PackFile;
  74. import org.eclipse.jgit.internal.storage.file.PackIndex.MutableEntry;
  75. import org.eclipse.jgit.internal.storage.pack.PackWriter;
  76. import org.eclipse.jgit.lib.AnyObjectId;
  77. import org.eclipse.jgit.lib.Constants;
  78. import org.eclipse.jgit.lib.FileMode;
  79. import org.eclipse.jgit.lib.NullProgressMonitor;
  80. import org.eclipse.jgit.lib.ObjectChecker;
  81. import org.eclipse.jgit.lib.ObjectId;
  82. import org.eclipse.jgit.lib.ObjectInserter;
  83. import org.eclipse.jgit.lib.PersonIdent;
  84. import org.eclipse.jgit.lib.Ref;
  85. import org.eclipse.jgit.lib.RefUpdate;
  86. import org.eclipse.jgit.lib.RefWriter;
  87. import org.eclipse.jgit.lib.Repository;
  88. import org.eclipse.jgit.lib.TagBuilder;
  89. import org.eclipse.jgit.merge.MergeStrategy;
  90. import org.eclipse.jgit.merge.ThreeWayMerger;
  91. import org.eclipse.jgit.revwalk.ObjectWalk;
  92. import org.eclipse.jgit.revwalk.RevBlob;
  93. import org.eclipse.jgit.revwalk.RevCommit;
  94. import org.eclipse.jgit.revwalk.RevObject;
  95. import org.eclipse.jgit.revwalk.RevTag;
  96. import org.eclipse.jgit.revwalk.RevTree;
  97. import org.eclipse.jgit.revwalk.RevWalk;
  98. import org.eclipse.jgit.treewalk.TreeWalk;
  99. import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
  100. import org.eclipse.jgit.util.ChangeIdUtil;
  101. import org.eclipse.jgit.util.FileUtils;
  102. import org.eclipse.jgit.util.io.SafeBufferedOutputStream;
  103. /**
  104. * Wrapper to make creating test data easier.
  105. *
  106. * @param <R>
  107. * type of Repository the test data is stored on.
  108. */
  109. public class TestRepository<R extends Repository> {
  110. private static final PersonIdent defaultAuthor;
  111. private static final PersonIdent defaultCommitter;
  112. static {
  113. final MockSystemReader m = new MockSystemReader();
  114. final long now = m.getCurrentTime();
  115. final int tz = m.getTimezone(now);
  116. final String an = "J. Author";
  117. final String ae = "jauthor@example.com";
  118. defaultAuthor = new PersonIdent(an, ae, now, tz);
  119. final String cn = "J. Committer";
  120. final String ce = "jcommitter@example.com";
  121. defaultCommitter = new PersonIdent(cn, ce, now, tz);
  122. }
  123. private final R db;
  124. private final Git git;
  125. private final RevWalk pool;
  126. private final ObjectInserter inserter;
  127. private long now;
  128. /**
  129. * Wrap a repository with test building tools.
  130. *
  131. * @param db
  132. * the test repository to write into.
  133. * @throws IOException
  134. */
  135. public TestRepository(R db) throws IOException {
  136. this(db, new RevWalk(db));
  137. }
  138. /**
  139. * Wrap a repository with test building tools.
  140. *
  141. * @param db
  142. * the test repository to write into.
  143. * @param rw
  144. * the RevObject pool to use for object lookup.
  145. * @throws IOException
  146. */
  147. public TestRepository(R db, RevWalk rw) throws IOException {
  148. this.db = db;
  149. this.git = Git.wrap(db);
  150. this.pool = rw;
  151. this.inserter = db.newObjectInserter();
  152. this.now = 1236977987000L;
  153. }
  154. /** @return the repository this helper class operates against. */
  155. public R getRepository() {
  156. return db;
  157. }
  158. /** @return get the RevWalk pool all objects are allocated through. */
  159. public RevWalk getRevWalk() {
  160. return pool;
  161. }
  162. /**
  163. * @return an API wrapper for the underlying repository. This wrapper does
  164. * not allocate any new resources and need not be closed (but closing
  165. * it is harmless). */
  166. public Git git() {
  167. return git;
  168. }
  169. /** @return current time adjusted by {@link #tick(int)}. */
  170. public Date getClock() {
  171. return new Date(now);
  172. }
  173. /** @return timezone used for default identities. */
  174. public TimeZone getTimeZone() {
  175. return defaultCommitter.getTimeZone();
  176. }
  177. /**
  178. * Adjust the current time that will used by the next commit.
  179. *
  180. * @param secDelta
  181. * number of seconds to add to the current time.
  182. */
  183. public void tick(final int secDelta) {
  184. now += secDelta * 1000L;
  185. }
  186. /**
  187. * Set the author and committer using {@link #getClock()}.
  188. *
  189. * @param c
  190. * the commit builder to store.
  191. */
  192. public void setAuthorAndCommitter(org.eclipse.jgit.lib.CommitBuilder c) {
  193. c.setAuthor(new PersonIdent(defaultAuthor, new Date(now)));
  194. c.setCommitter(new PersonIdent(defaultCommitter, new Date(now)));
  195. }
  196. /**
  197. * Create a new blob object in the repository.
  198. *
  199. * @param content
  200. * file content, will be UTF-8 encoded.
  201. * @return reference to the blob.
  202. * @throws Exception
  203. */
  204. public RevBlob blob(final String content) throws Exception {
  205. return blob(content.getBytes("UTF-8"));
  206. }
  207. /**
  208. * Create a new blob object in the repository.
  209. *
  210. * @param content
  211. * binary file content.
  212. * @return reference to the blob.
  213. * @throws Exception
  214. */
  215. public RevBlob blob(final byte[] content) throws Exception {
  216. ObjectId id;
  217. try (ObjectInserter ins = inserter) {
  218. id = ins.insert(Constants.OBJ_BLOB, content);
  219. ins.flush();
  220. }
  221. return pool.lookupBlob(id);
  222. }
  223. /**
  224. * Construct a regular file mode tree entry.
  225. *
  226. * @param path
  227. * path of the file.
  228. * @param blob
  229. * a blob, previously constructed in the repository.
  230. * @return the entry.
  231. * @throws Exception
  232. */
  233. public DirCacheEntry file(final String path, final RevBlob blob)
  234. throws Exception {
  235. final DirCacheEntry e = new DirCacheEntry(path);
  236. e.setFileMode(FileMode.REGULAR_FILE);
  237. e.setObjectId(blob);
  238. return e;
  239. }
  240. /**
  241. * Construct a tree from a specific listing of file entries.
  242. *
  243. * @param entries
  244. * the files to include in the tree. The collection does not need
  245. * to be sorted properly and may be empty.
  246. * @return reference to the tree specified by the entry list.
  247. * @throws Exception
  248. */
  249. public RevTree tree(final DirCacheEntry... entries) throws Exception {
  250. final DirCache dc = DirCache.newInCore();
  251. final DirCacheBuilder b = dc.builder();
  252. for (final DirCacheEntry e : entries)
  253. b.add(e);
  254. b.finish();
  255. ObjectId root;
  256. try (ObjectInserter ins = inserter) {
  257. root = dc.writeTree(ins);
  258. ins.flush();
  259. }
  260. return pool.lookupTree(root);
  261. }
  262. /**
  263. * Lookup an entry stored in a tree, failing if not present.
  264. *
  265. * @param tree
  266. * the tree to search.
  267. * @param path
  268. * the path to find the entry of.
  269. * @return the parsed object entry at this path, never null.
  270. * @throws Exception
  271. */
  272. public RevObject get(final RevTree tree, final String path)
  273. throws Exception {
  274. try (TreeWalk tw = new TreeWalk(pool.getObjectReader())) {
  275. tw.setFilter(PathFilterGroup.createFromStrings(Collections
  276. .singleton(path)));
  277. tw.reset(tree);
  278. while (tw.next()) {
  279. if (tw.isSubtree() && !path.equals(tw.getPathString())) {
  280. tw.enterSubtree();
  281. continue;
  282. }
  283. final ObjectId entid = tw.getObjectId(0);
  284. final FileMode entmode = tw.getFileMode(0);
  285. return pool.lookupAny(entid, entmode.getObjectType());
  286. }
  287. }
  288. fail("Can't find " + path + " in tree " + tree.name());
  289. return null; // never reached.
  290. }
  291. /**
  292. * Create a new commit.
  293. * <p>
  294. * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
  295. * tree (no files or subdirectories).
  296. *
  297. * @param parents
  298. * zero or more parents of the commit.
  299. * @return the new commit.
  300. * @throws Exception
  301. */
  302. public RevCommit commit(final RevCommit... parents) throws Exception {
  303. return commit(1, tree(), parents);
  304. }
  305. /**
  306. * Create a new commit.
  307. * <p>
  308. * See {@link #commit(int, RevTree, RevCommit...)}.
  309. *
  310. * @param tree
  311. * the root tree for the commit.
  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 RevTree tree, final RevCommit... parents)
  318. throws Exception {
  319. return commit(1, tree, parents);
  320. }
  321. /**
  322. * Create a new commit.
  323. * <p>
  324. * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
  325. * tree (no files or subdirectories).
  326. *
  327. * @param secDelta
  328. * number of seconds to advance {@link #tick(int)} by.
  329. * @param parents
  330. * zero or more parents of the commit.
  331. * @return the new commit.
  332. * @throws Exception
  333. */
  334. public RevCommit commit(final int secDelta, final RevCommit... parents)
  335. throws Exception {
  336. return commit(secDelta, tree(), parents);
  337. }
  338. /**
  339. * Create a new commit.
  340. * <p>
  341. * The author and committer identities are stored using the current
  342. * timestamp, after being incremented by {@code secDelta}. The message body
  343. * is empty.
  344. *
  345. * @param secDelta
  346. * number of seconds to advance {@link #tick(int)} by.
  347. * @param tree
  348. * the root tree for the commit.
  349. * @param parents
  350. * zero or more parents of the commit.
  351. * @return the new commit.
  352. * @throws Exception
  353. */
  354. public RevCommit commit(final int secDelta, final RevTree tree,
  355. final RevCommit... parents) throws Exception {
  356. tick(secDelta);
  357. final org.eclipse.jgit.lib.CommitBuilder c;
  358. c = new org.eclipse.jgit.lib.CommitBuilder();
  359. c.setTreeId(tree);
  360. c.setParentIds(parents);
  361. c.setAuthor(new PersonIdent(defaultAuthor, new Date(now)));
  362. c.setCommitter(new PersonIdent(defaultCommitter, new Date(now)));
  363. c.setMessage("");
  364. ObjectId id;
  365. try (ObjectInserter ins = inserter) {
  366. id = ins.insert(c);
  367. ins.flush();
  368. }
  369. return pool.lookupCommit(id);
  370. }
  371. /** @return a new commit builder. */
  372. public CommitBuilder commit() {
  373. return new CommitBuilder();
  374. }
  375. /**
  376. * Construct an annotated tag object pointing at another object.
  377. * <p>
  378. * The tagger is the committer identity, at the current time as specified by
  379. * {@link #tick(int)}. The time is not increased.
  380. * <p>
  381. * The tag message is empty.
  382. *
  383. * @param name
  384. * name of the tag. Traditionally a tag name should not start
  385. * with {@code refs/tags/}.
  386. * @param dst
  387. * object the tag should be pointed at.
  388. * @return the annotated tag object.
  389. * @throws Exception
  390. */
  391. public RevTag tag(final String name, final RevObject dst) throws Exception {
  392. final TagBuilder t = new TagBuilder();
  393. t.setObjectId(dst);
  394. t.setTag(name);
  395. t.setTagger(new PersonIdent(defaultCommitter, new Date(now)));
  396. t.setMessage("");
  397. ObjectId id;
  398. try (ObjectInserter ins = inserter) {
  399. id = ins.insert(t);
  400. ins.flush();
  401. }
  402. return (RevTag) pool.lookupAny(id, Constants.OBJ_TAG);
  403. }
  404. /**
  405. * Update a reference to point to an object.
  406. *
  407. * @param ref
  408. * the name of the reference to update to. If {@code ref} does
  409. * not start with {@code refs/} and is not the magic names
  410. * {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
  411. * {@code refs/heads/} will be prefixed in front of the given
  412. * name, thereby assuming it is a branch.
  413. * @param to
  414. * the target object.
  415. * @return the target object.
  416. * @throws Exception
  417. */
  418. public RevCommit update(String ref, CommitBuilder to) throws Exception {
  419. return update(ref, to.create());
  420. }
  421. /**
  422. * Amend an existing ref.
  423. *
  424. * @param ref
  425. * the name of the reference to amend, which must already exist.
  426. * If {@code ref} does not start with {@code refs/} and is not the
  427. * magic names {@code HEAD} {@code FETCH_HEAD} or {@code
  428. * MERGE_HEAD}, then {@code refs/heads/} will be prefixed in front
  429. * of the given name, thereby assuming it is a branch.
  430. * @return commit builder that amends the branch on commit.
  431. * @throws Exception
  432. */
  433. public CommitBuilder amendRef(String ref) throws Exception {
  434. String name = normalizeRef(ref);
  435. Ref r = db.getRef(name);
  436. if (r == null)
  437. throw new IOException("Not a ref: " + ref);
  438. return amend(pool.parseCommit(r.getObjectId()), branch(name).commit());
  439. }
  440. /**
  441. * Amend an existing commit.
  442. *
  443. * @param id
  444. * the id of the commit to amend.
  445. * @return commit builder.
  446. * @throws Exception
  447. */
  448. public CommitBuilder amend(AnyObjectId id) throws Exception {
  449. return amend(pool.parseCommit(id), commit());
  450. }
  451. private CommitBuilder amend(RevCommit old, CommitBuilder b) throws Exception {
  452. pool.parseBody(old);
  453. b.author(old.getAuthorIdent());
  454. b.committer(old.getCommitterIdent());
  455. b.message(old.getFullMessage());
  456. // Use the committer name from the old commit, but update it after ticking
  457. // the clock in CommitBuilder#create().
  458. b.updateCommitterTime = true;
  459. // Reset parents to original parents.
  460. b.noParents();
  461. for (int i = 0; i < old.getParentCount(); i++)
  462. b.parent(old.getParent(i));
  463. // Reset tree to original tree; resetting parents reset tree contents to the
  464. // first parent.
  465. b.tree.clear();
  466. try (TreeWalk tw = new TreeWalk(db)) {
  467. tw.reset(old.getTree());
  468. tw.setRecursive(true);
  469. while (tw.next()) {
  470. b.edit(new PathEdit(tw.getPathString()) {
  471. @Override
  472. public void apply(DirCacheEntry ent) {
  473. ent.setFileMode(tw.getFileMode(0));
  474. ent.setObjectId(tw.getObjectId(0));
  475. }
  476. });
  477. }
  478. }
  479. return b;
  480. }
  481. /**
  482. * Update a reference to point to an object.
  483. *
  484. * @param <T>
  485. * type of the target object.
  486. * @param ref
  487. * the name of the reference to update to. If {@code ref} does
  488. * not start with {@code refs/} and is not the magic names
  489. * {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
  490. * {@code refs/heads/} will be prefixed in front of the given
  491. * name, thereby assuming it is a branch.
  492. * @param obj
  493. * the target object.
  494. * @return the target object.
  495. * @throws Exception
  496. */
  497. public <T extends AnyObjectId> T update(String ref, T obj) throws Exception {
  498. ref = normalizeRef(ref);
  499. RefUpdate u = db.updateRef(ref);
  500. u.setNewObjectId(obj);
  501. switch (u.forceUpdate()) {
  502. case FAST_FORWARD:
  503. case FORCED:
  504. case NEW:
  505. case NO_CHANGE:
  506. updateServerInfo();
  507. return obj;
  508. default:
  509. throw new IOException("Cannot write " + ref + " " + u.getResult());
  510. }
  511. }
  512. private static String normalizeRef(String ref) {
  513. if (Constants.HEAD.equals(ref)) {
  514. // nothing
  515. } else if ("FETCH_HEAD".equals(ref)) {
  516. // nothing
  517. } else if ("MERGE_HEAD".equals(ref)) {
  518. // nothing
  519. } else if (ref.startsWith(Constants.R_REFS)) {
  520. // nothing
  521. } else
  522. ref = Constants.R_HEADS + ref;
  523. return ref;
  524. }
  525. /**
  526. * Soft-reset HEAD to a detached state.
  527. * <p>
  528. * @param id
  529. * ID of detached head.
  530. * @throws Exception
  531. * @see #reset(String)
  532. */
  533. public void reset(AnyObjectId id) throws Exception {
  534. RefUpdate ru = db.updateRef(Constants.HEAD, true);
  535. ru.setNewObjectId(id);
  536. RefUpdate.Result result = ru.forceUpdate();
  537. switch (result) {
  538. case FAST_FORWARD:
  539. case FORCED:
  540. case NEW:
  541. case NO_CHANGE:
  542. break;
  543. default:
  544. throw new IOException(String.format(
  545. "Checkout \"%s\" failed: %s", id.name(), result));
  546. }
  547. }
  548. /**
  549. * Soft-reset HEAD to a different commit.
  550. * <p>
  551. * This is equivalent to {@code git reset --soft} in that it modifies HEAD but
  552. * not the index or the working tree of a non-bare repository.
  553. *
  554. * @param name
  555. * revision string; either an existing ref name, or something that
  556. * can be parsed to an object ID.
  557. * @throws Exception
  558. */
  559. public void reset(String name) throws Exception {
  560. RefUpdate.Result result;
  561. ObjectId id = db.resolve(name);
  562. if (id == null)
  563. throw new IOException("Not a revision: " + name);
  564. RefUpdate ru = db.updateRef(Constants.HEAD, false);
  565. ru.setNewObjectId(id);
  566. result = ru.forceUpdate();
  567. switch (result) {
  568. case FAST_FORWARD:
  569. case FORCED:
  570. case NEW:
  571. case NO_CHANGE:
  572. break;
  573. default:
  574. throw new IOException(String.format(
  575. "Checkout \"%s\" failed: %s", name, result));
  576. }
  577. }
  578. /**
  579. * Cherry-pick a commit onto HEAD.
  580. * <p>
  581. * This differs from {@code git cherry-pick} in that it works in a bare
  582. * repository. As a result, any merge failure results in an exception, as
  583. * there is no way to recover.
  584. *
  585. * @param id
  586. * commit-ish to cherry-pick.
  587. * @return newly created commit, or null if no work was done due to the
  588. * resulting tree being identical.
  589. * @throws Exception
  590. */
  591. public RevCommit cherryPick(AnyObjectId id) throws Exception {
  592. RevCommit commit = pool.parseCommit(id);
  593. pool.parseBody(commit);
  594. if (commit.getParentCount() != 1)
  595. throw new IOException(String.format(
  596. "Expected 1 parent for %s, found: %s",
  597. id.name(), Arrays.asList(commit.getParents())));
  598. RevCommit parent = commit.getParent(0);
  599. pool.parseHeaders(parent);
  600. Ref headRef = db.getRef(Constants.HEAD);
  601. if (headRef == null)
  602. throw new IOException("Missing HEAD");
  603. RevCommit head = pool.parseCommit(headRef.getObjectId());
  604. ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
  605. merger.setBase(parent.getTree());
  606. if (merger.merge(head, commit)) {
  607. if (AnyObjectId.equals(head.getTree(), merger.getResultTreeId()))
  608. return null;
  609. tick(1);
  610. org.eclipse.jgit.lib.CommitBuilder b =
  611. new org.eclipse.jgit.lib.CommitBuilder();
  612. b.setParentId(head);
  613. b.setTreeId(merger.getResultTreeId());
  614. b.setAuthor(commit.getAuthorIdent());
  615. b.setCommitter(new PersonIdent(defaultCommitter, new Date(now)));
  616. b.setMessage(commit.getFullMessage());
  617. ObjectId result;
  618. try (ObjectInserter ins = inserter) {
  619. result = ins.insert(b);
  620. ins.flush();
  621. }
  622. update(Constants.HEAD, result);
  623. return pool.parseCommit(result);
  624. } else {
  625. throw new IOException("Merge conflict");
  626. }
  627. }
  628. /**
  629. * Update the dumb client server info files.
  630. *
  631. * @throws Exception
  632. */
  633. public void updateServerInfo() throws Exception {
  634. if (db instanceof FileRepository) {
  635. final FileRepository fr = (FileRepository) db;
  636. RefWriter rw = new RefWriter(fr.getAllRefs().values()) {
  637. @Override
  638. protected void writeFile(final String name, final byte[] bin)
  639. throws IOException {
  640. File path = new File(fr.getDirectory(), name);
  641. TestRepository.this.writeFile(path, bin);
  642. }
  643. };
  644. rw.writePackedRefs();
  645. rw.writeInfoRefs();
  646. final StringBuilder w = new StringBuilder();
  647. for (PackFile p : fr.getObjectDatabase().getPacks()) {
  648. w.append("P ");
  649. w.append(p.getPackFile().getName());
  650. w.append('\n');
  651. }
  652. writeFile(new File(new File(fr.getObjectDatabase().getDirectory(),
  653. "info"), "packs"), Constants.encodeASCII(w.toString()));
  654. }
  655. }
  656. /**
  657. * Ensure the body of the given object has been parsed.
  658. *
  659. * @param <T>
  660. * type of object, e.g. {@link RevTag} or {@link RevCommit}.
  661. * @param object
  662. * reference to the (possibly unparsed) object to force body
  663. * parsing of.
  664. * @return {@code object}
  665. * @throws Exception
  666. */
  667. public <T extends RevObject> T parseBody(final T object) throws Exception {
  668. pool.parseBody(object);
  669. return object;
  670. }
  671. /**
  672. * Create a new branch builder for this repository.
  673. *
  674. * @param ref
  675. * name of the branch to be constructed. If {@code ref} does not
  676. * start with {@code refs/} the prefix {@code refs/heads/} will
  677. * be added.
  678. * @return builder for the named branch.
  679. */
  680. public BranchBuilder branch(String ref) {
  681. if (Constants.HEAD.equals(ref)) {
  682. // nothing
  683. } else if (ref.startsWith(Constants.R_REFS)) {
  684. // nothing
  685. } else
  686. ref = Constants.R_HEADS + ref;
  687. return new BranchBuilder(ref);
  688. }
  689. /**
  690. * Tag an object using a lightweight tag.
  691. *
  692. * @param name
  693. * the tag name. The /refs/tags/ prefix will be added if the name
  694. * doesn't start with it
  695. * @param obj
  696. * the object to tag
  697. * @return the tagged object
  698. * @throws Exception
  699. */
  700. public ObjectId lightweightTag(String name, ObjectId obj) throws Exception {
  701. if (!name.startsWith(Constants.R_TAGS))
  702. name = Constants.R_TAGS + name;
  703. return update(name, obj);
  704. }
  705. /**
  706. * Run consistency checks against the object database.
  707. * <p>
  708. * This method completes silently if the checks pass. A temporary revision
  709. * pool is constructed during the checking.
  710. *
  711. * @param tips
  712. * the tips to start checking from; if not supplied the refs of
  713. * the repository are used instead.
  714. * @throws MissingObjectException
  715. * @throws IncorrectObjectTypeException
  716. * @throws IOException
  717. */
  718. public void fsck(RevObject... tips) throws MissingObjectException,
  719. IncorrectObjectTypeException, IOException {
  720. try (ObjectWalk ow = new ObjectWalk(db)) {
  721. if (tips.length != 0) {
  722. for (RevObject o : tips)
  723. ow.markStart(ow.parseAny(o));
  724. } else {
  725. for (Ref r : db.getAllRefs().values())
  726. ow.markStart(ow.parseAny(r.getObjectId()));
  727. }
  728. ObjectChecker oc = new ObjectChecker();
  729. for (;;) {
  730. final RevCommit o = ow.next();
  731. if (o == null)
  732. break;
  733. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  734. oc.checkCommit(bin);
  735. assertHash(o, bin);
  736. }
  737. for (;;) {
  738. final RevObject o = ow.nextObject();
  739. if (o == null)
  740. break;
  741. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  742. oc.check(o.getType(), bin);
  743. assertHash(o, bin);
  744. }
  745. }
  746. }
  747. private static void assertHash(RevObject id, byte[] bin) {
  748. MessageDigest md = Constants.newMessageDigest();
  749. md.update(Constants.encodedTypeString(id.getType()));
  750. md.update((byte) ' ');
  751. md.update(Constants.encodeASCII(bin.length));
  752. md.update((byte) 0);
  753. md.update(bin);
  754. assertEquals(id, ObjectId.fromRaw(md.digest()));
  755. }
  756. /**
  757. * Pack all reachable objects in the repository into a single pack file.
  758. * <p>
  759. * All loose objects are automatically pruned. Existing packs however are
  760. * not removed.
  761. *
  762. * @throws Exception
  763. */
  764. public void packAndPrune() throws Exception {
  765. if (db.getObjectDatabase() instanceof ObjectDirectory) {
  766. ObjectDirectory odb = (ObjectDirectory) db.getObjectDatabase();
  767. NullProgressMonitor m = NullProgressMonitor.INSTANCE;
  768. final File pack, idx;
  769. try (PackWriter pw = new PackWriter(db)) {
  770. Set<ObjectId> all = new HashSet<ObjectId>();
  771. for (Ref r : db.getAllRefs().values())
  772. all.add(r.getObjectId());
  773. pw.preparePack(m, all, Collections.<ObjectId> emptySet());
  774. final ObjectId name = pw.computeName();
  775. pack = nameFor(odb, name, ".pack");
  776. try (OutputStream out =
  777. new SafeBufferedOutputStream(new FileOutputStream(pack))) {
  778. pw.writePack(m, m, out);
  779. }
  780. pack.setReadOnly();
  781. idx = nameFor(odb, name, ".idx");
  782. try (OutputStream out =
  783. new SafeBufferedOutputStream(new FileOutputStream(idx))) {
  784. pw.writeIndex(out);
  785. }
  786. idx.setReadOnly();
  787. }
  788. odb.openPack(pack);
  789. updateServerInfo();
  790. prunePacked(odb);
  791. }
  792. }
  793. private static void prunePacked(ObjectDirectory odb) throws IOException {
  794. for (PackFile p : odb.getPacks()) {
  795. for (MutableEntry e : p)
  796. FileUtils.delete(odb.fileFor(e.toObjectId()));
  797. }
  798. }
  799. private static File nameFor(ObjectDirectory odb, ObjectId name, String t) {
  800. File packdir = new File(odb.getDirectory(), "pack");
  801. return new File(packdir, "pack-" + name.name() + t);
  802. }
  803. private void writeFile(final File p, final byte[] bin) throws IOException,
  804. ObjectWritingException {
  805. final LockFile lck = new LockFile(p, db.getFS());
  806. if (!lck.lock())
  807. throw new ObjectWritingException("Can't write " + p);
  808. try {
  809. lck.write(bin);
  810. } catch (IOException ioe) {
  811. throw new ObjectWritingException("Can't write " + p);
  812. }
  813. if (!lck.commit())
  814. throw new ObjectWritingException("Can't write " + p);
  815. }
  816. /** Helper to build a branch with one or more commits */
  817. public class BranchBuilder {
  818. private final String ref;
  819. BranchBuilder(final String ref) {
  820. this.ref = ref;
  821. }
  822. /**
  823. * @return construct a new commit builder that updates this branch. If
  824. * the branch already exists, the commit builder will have its
  825. * first parent as the current commit and its tree will be
  826. * initialized to the current files.
  827. * @throws Exception
  828. * the commit builder can't read the current branch state
  829. */
  830. public CommitBuilder commit() throws Exception {
  831. return new CommitBuilder(this);
  832. }
  833. /**
  834. * Forcefully update this branch to a particular commit.
  835. *
  836. * @param to
  837. * the commit to update to.
  838. * @return {@code to}.
  839. * @throws Exception
  840. */
  841. public RevCommit update(CommitBuilder to) throws Exception {
  842. return update(to.create());
  843. }
  844. /**
  845. * Forcefully update this branch to a particular commit.
  846. *
  847. * @param to
  848. * the commit to update to.
  849. * @return {@code to}.
  850. * @throws Exception
  851. */
  852. public RevCommit update(RevCommit to) throws Exception {
  853. return TestRepository.this.update(ref, to);
  854. }
  855. }
  856. /** Helper to generate a commit. */
  857. public class CommitBuilder {
  858. private final BranchBuilder branch;
  859. private final DirCache tree = DirCache.newInCore();
  860. private ObjectId topLevelTree;
  861. private final List<RevCommit> parents = new ArrayList<RevCommit>(2);
  862. private int tick = 1;
  863. private String message = "";
  864. private RevCommit self;
  865. private PersonIdent author;
  866. private PersonIdent committer;
  867. private String changeId;
  868. private boolean updateCommitterTime;
  869. CommitBuilder() {
  870. branch = null;
  871. }
  872. CommitBuilder(BranchBuilder b) throws Exception {
  873. branch = b;
  874. Ref ref = db.getRef(branch.ref);
  875. if (ref != null && ref.getObjectId() != null)
  876. parent(pool.parseCommit(ref.getObjectId()));
  877. }
  878. CommitBuilder(CommitBuilder prior) throws Exception {
  879. branch = prior.branch;
  880. DirCacheBuilder b = tree.builder();
  881. for (int i = 0; i < prior.tree.getEntryCount(); i++)
  882. b.add(prior.tree.getEntry(i));
  883. b.finish();
  884. parents.add(prior.create());
  885. }
  886. public CommitBuilder parent(RevCommit p) throws Exception {
  887. if (parents.isEmpty()) {
  888. DirCacheBuilder b = tree.builder();
  889. parseBody(p);
  890. b.addTree(new byte[0], DirCacheEntry.STAGE_0, pool
  891. .getObjectReader(), p.getTree());
  892. b.finish();
  893. }
  894. parents.add(p);
  895. return this;
  896. }
  897. public List<RevCommit> parents() {
  898. return Collections.unmodifiableList(parents);
  899. }
  900. public CommitBuilder noParents() {
  901. parents.clear();
  902. return this;
  903. }
  904. public CommitBuilder noFiles() {
  905. tree.clear();
  906. return this;
  907. }
  908. public CommitBuilder setTopLevelTree(ObjectId treeId) {
  909. topLevelTree = treeId;
  910. return this;
  911. }
  912. public CommitBuilder add(String path, String content) throws Exception {
  913. return add(path, blob(content));
  914. }
  915. public CommitBuilder add(String path, final RevBlob id)
  916. throws Exception {
  917. return edit(new PathEdit(path) {
  918. @Override
  919. public void apply(DirCacheEntry ent) {
  920. ent.setFileMode(FileMode.REGULAR_FILE);
  921. ent.setObjectId(id);
  922. }
  923. });
  924. }
  925. public CommitBuilder edit(PathEdit edit) {
  926. DirCacheEditor e = tree.editor();
  927. e.add(edit);
  928. e.finish();
  929. return this;
  930. }
  931. public CommitBuilder rm(String path) {
  932. DirCacheEditor e = tree.editor();
  933. e.add(new DeletePath(path));
  934. e.add(new DeleteTree(path));
  935. e.finish();
  936. return this;
  937. }
  938. public CommitBuilder message(String m) {
  939. message = m;
  940. return this;
  941. }
  942. public String message() {
  943. return message;
  944. }
  945. public CommitBuilder tick(int secs) {
  946. tick = secs;
  947. return this;
  948. }
  949. public CommitBuilder ident(PersonIdent ident) {
  950. author = ident;
  951. committer = ident;
  952. return this;
  953. }
  954. public CommitBuilder author(PersonIdent a) {
  955. author = a;
  956. return this;
  957. }
  958. public PersonIdent author() {
  959. return author;
  960. }
  961. public CommitBuilder committer(PersonIdent c) {
  962. committer = c;
  963. return this;
  964. }
  965. public PersonIdent committer() {
  966. return committer;
  967. }
  968. public CommitBuilder insertChangeId() {
  969. changeId = "";
  970. return this;
  971. }
  972. public CommitBuilder insertChangeId(String c) {
  973. // Validate, but store as a string so we can use "" as a sentinel.
  974. ObjectId.fromString(c);
  975. changeId = c;
  976. return this;
  977. }
  978. public RevCommit create() throws Exception {
  979. if (self == null) {
  980. TestRepository.this.tick(tick);
  981. final org.eclipse.jgit.lib.CommitBuilder c;
  982. c = new org.eclipse.jgit.lib.CommitBuilder();
  983. c.setParentIds(parents);
  984. setAuthorAndCommitter(c);
  985. if (author != null)
  986. c.setAuthor(author);
  987. if (committer != null) {
  988. if (updateCommitterTime)
  989. committer = new PersonIdent(committer, new Date(now));
  990. c.setCommitter(committer);
  991. }
  992. ObjectId commitId;
  993. try (ObjectInserter ins = inserter) {
  994. if (topLevelTree != null)
  995. c.setTreeId(topLevelTree);
  996. else
  997. c.setTreeId(tree.writeTree(ins));
  998. insertChangeId(c);
  999. c.setMessage(message);
  1000. commitId = ins.insert(c);
  1001. ins.flush();
  1002. }
  1003. self = pool.lookupCommit(commitId);
  1004. if (branch != null)
  1005. branch.update(self);
  1006. }
  1007. return self;
  1008. }
  1009. private void insertChangeId(org.eclipse.jgit.lib.CommitBuilder c)
  1010. throws IOException {
  1011. if (changeId == null)
  1012. return;
  1013. int idx = ChangeIdUtil.indexOfChangeId(message, "\n");
  1014. if (idx >= 0)
  1015. return;
  1016. ObjectId firstParentId = null;
  1017. if (!parents.isEmpty())
  1018. firstParentId = parents.get(0);
  1019. ObjectId cid;
  1020. if (changeId.equals(""))
  1021. cid = ChangeIdUtil.computeChangeId(c.getTreeId(), firstParentId,
  1022. c.getAuthor(), c.getCommitter(), message);
  1023. else
  1024. cid = ObjectId.fromString(changeId);
  1025. message = ChangeIdUtil.insertId(message, cid);
  1026. if (cid != null)
  1027. message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
  1028. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
  1029. + cid.getName() + "\n"); //$NON-NLS-1$
  1030. }
  1031. public CommitBuilder child() throws Exception {
  1032. return new CommitBuilder(this);
  1033. }
  1034. }
  1035. }