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

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