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

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