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

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