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

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