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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  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> implements AutoCloseable {
  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.isEqual(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. /**
  863. * Closes the underlying {@link Repository} object and any other internal
  864. * resources.
  865. * <p>
  866. * {@link AutoCloseable} resources that may escape this object, such as
  867. * those returned by the {@link #git} and {@link #getRevWalk()} methods are
  868. * not closed.
  869. */
  870. @Override
  871. public void close() {
  872. try {
  873. inserter.close();
  874. } finally {
  875. db.close();
  876. }
  877. }
  878. private static void prunePacked(ObjectDirectory odb) throws IOException {
  879. for (PackFile p : odb.getPacks()) {
  880. for (MutableEntry e : p)
  881. FileUtils.delete(odb.fileFor(e.toObjectId()));
  882. }
  883. }
  884. private static File nameFor(ObjectDirectory odb, ObjectId name, String t) {
  885. File packdir = odb.getPackDirectory();
  886. return new File(packdir, "pack-" + name.name() + t);
  887. }
  888. private void writeFile(File p, byte[] bin) throws IOException,
  889. ObjectWritingException {
  890. final LockFile lck = new LockFile(p);
  891. if (!lck.lock())
  892. throw new ObjectWritingException("Can't write " + p);
  893. try {
  894. lck.write(bin);
  895. } catch (IOException ioe) {
  896. throw new ObjectWritingException("Can't write " + p);
  897. }
  898. if (!lck.commit())
  899. throw new ObjectWritingException("Can't write " + p);
  900. }
  901. /** Helper to build a branch with one or more commits */
  902. public class BranchBuilder {
  903. private final String ref;
  904. BranchBuilder(String ref) {
  905. this.ref = ref;
  906. }
  907. /**
  908. * @return construct a new commit builder that updates this branch. If
  909. * the branch already exists, the commit builder will have its
  910. * first parent as the current commit and its tree will be
  911. * initialized to the current files.
  912. * @throws Exception
  913. * the commit builder can't read the current branch state
  914. */
  915. public CommitBuilder commit() throws Exception {
  916. return new CommitBuilder(this);
  917. }
  918. /**
  919. * Forcefully update this branch to a particular commit.
  920. *
  921. * @param to
  922. * the commit to update to.
  923. * @return {@code to}.
  924. * @throws Exception
  925. */
  926. public RevCommit update(CommitBuilder to) throws Exception {
  927. return update(to.create());
  928. }
  929. /**
  930. * Forcefully update this branch to a particular commit.
  931. *
  932. * @param to
  933. * the commit to update to.
  934. * @return {@code to}.
  935. * @throws Exception
  936. */
  937. public RevCommit update(RevCommit to) throws Exception {
  938. return TestRepository.this.update(ref, to);
  939. }
  940. /**
  941. * Delete this branch.
  942. * @throws Exception
  943. * @since 4.4
  944. */
  945. public void delete() throws Exception {
  946. TestRepository.this.delete(ref);
  947. }
  948. }
  949. /** Helper to generate a commit. */
  950. public class CommitBuilder {
  951. private final BranchBuilder branch;
  952. private final DirCache tree = DirCache.newInCore();
  953. private ObjectId topLevelTree;
  954. private final List<RevCommit> parents = new ArrayList<>(2);
  955. private int tick = 1;
  956. private String message = "";
  957. private RevCommit self;
  958. private PersonIdent author;
  959. private PersonIdent committer;
  960. private String changeId;
  961. private boolean updateCommitterTime;
  962. CommitBuilder() {
  963. branch = null;
  964. }
  965. CommitBuilder(BranchBuilder b) throws Exception {
  966. branch = b;
  967. Ref ref = db.exactRef(branch.ref);
  968. if (ref != null && ref.getObjectId() != null)
  969. parent(pool.parseCommit(ref.getObjectId()));
  970. }
  971. CommitBuilder(CommitBuilder prior) throws Exception {
  972. branch = prior.branch;
  973. DirCacheBuilder b = tree.builder();
  974. for (int i = 0; i < prior.tree.getEntryCount(); i++)
  975. b.add(prior.tree.getEntry(i));
  976. b.finish();
  977. parents.add(prior.create());
  978. }
  979. /**
  980. * set parent commit
  981. *
  982. * @param p
  983. * parent commit
  984. * @return this commit builder
  985. * @throws Exception
  986. */
  987. public CommitBuilder parent(RevCommit p) throws Exception {
  988. if (parents.isEmpty()) {
  989. DirCacheBuilder b = tree.builder();
  990. parseBody(p);
  991. b.addTree(new byte[0], DirCacheEntry.STAGE_0, pool
  992. .getObjectReader(), p.getTree());
  993. b.finish();
  994. }
  995. parents.add(p);
  996. return this;
  997. }
  998. /**
  999. * Get parent commits
  1000. *
  1001. * @return parent commits
  1002. */
  1003. public List<RevCommit> parents() {
  1004. return Collections.unmodifiableList(parents);
  1005. }
  1006. /**
  1007. * Remove parent commits
  1008. *
  1009. * @return this commit builder
  1010. */
  1011. public CommitBuilder noParents() {
  1012. parents.clear();
  1013. return this;
  1014. }
  1015. /**
  1016. * Remove files
  1017. *
  1018. * @return this commit builder
  1019. */
  1020. public CommitBuilder noFiles() {
  1021. tree.clear();
  1022. return this;
  1023. }
  1024. /**
  1025. * Set top level tree
  1026. *
  1027. * @param treeId
  1028. * the top level tree
  1029. * @return this commit builder
  1030. */
  1031. public CommitBuilder setTopLevelTree(ObjectId treeId) {
  1032. topLevelTree = treeId;
  1033. return this;
  1034. }
  1035. /**
  1036. * Add file with given content
  1037. *
  1038. * @param path
  1039. * path of the file
  1040. * @param content
  1041. * the file content
  1042. * @return this commit builder
  1043. * @throws Exception
  1044. */
  1045. public CommitBuilder add(String path, String content) throws Exception {
  1046. return add(path, blob(content));
  1047. }
  1048. /**
  1049. * Add file with given path and blob
  1050. *
  1051. * @param path
  1052. * path of the file
  1053. * @param id
  1054. * blob for this file
  1055. * @return this commit builder
  1056. * @throws Exception
  1057. */
  1058. public CommitBuilder add(String path, RevBlob id)
  1059. throws Exception {
  1060. return edit(new PathEdit(path) {
  1061. @Override
  1062. public void apply(DirCacheEntry ent) {
  1063. ent.setFileMode(FileMode.REGULAR_FILE);
  1064. ent.setObjectId(id);
  1065. }
  1066. });
  1067. }
  1068. /**
  1069. * Edit the index
  1070. *
  1071. * @param edit
  1072. * the index record update
  1073. * @return this commit builder
  1074. */
  1075. public CommitBuilder edit(PathEdit edit) {
  1076. DirCacheEditor e = tree.editor();
  1077. e.add(edit);
  1078. e.finish();
  1079. return this;
  1080. }
  1081. /**
  1082. * Remove a file
  1083. *
  1084. * @param path
  1085. * path of the file
  1086. * @return this commit builder
  1087. */
  1088. public CommitBuilder rm(String path) {
  1089. DirCacheEditor e = tree.editor();
  1090. e.add(new DeletePath(path));
  1091. e.add(new DeleteTree(path));
  1092. e.finish();
  1093. return this;
  1094. }
  1095. /**
  1096. * Set commit message
  1097. *
  1098. * @param m
  1099. * the message
  1100. * @return this commit builder
  1101. */
  1102. public CommitBuilder message(String m) {
  1103. message = m;
  1104. return this;
  1105. }
  1106. /**
  1107. * Get the commit message
  1108. *
  1109. * @return the commit message
  1110. */
  1111. public String message() {
  1112. return message;
  1113. }
  1114. /**
  1115. * Tick the clock
  1116. *
  1117. * @param secs
  1118. * number of seconds
  1119. * @return this commit builder
  1120. */
  1121. public CommitBuilder tick(int secs) {
  1122. tick = secs;
  1123. return this;
  1124. }
  1125. /**
  1126. * Set author and committer identity
  1127. *
  1128. * @param ident
  1129. * identity to set
  1130. * @return this commit builder
  1131. */
  1132. public CommitBuilder ident(PersonIdent ident) {
  1133. author = ident;
  1134. committer = ident;
  1135. return this;
  1136. }
  1137. /**
  1138. * Set the author identity
  1139. *
  1140. * @param a
  1141. * the author's identity
  1142. * @return this commit builder
  1143. */
  1144. public CommitBuilder author(PersonIdent a) {
  1145. author = a;
  1146. return this;
  1147. }
  1148. /**
  1149. * Get the author identity
  1150. *
  1151. * @return the author identity
  1152. */
  1153. public PersonIdent author() {
  1154. return author;
  1155. }
  1156. /**
  1157. * Set the committer identity
  1158. *
  1159. * @param c
  1160. * the committer identity
  1161. * @return this commit builder
  1162. */
  1163. public CommitBuilder committer(PersonIdent c) {
  1164. committer = c;
  1165. return this;
  1166. }
  1167. /**
  1168. * Get the committer identity
  1169. *
  1170. * @return the committer identity
  1171. */
  1172. public PersonIdent committer() {
  1173. return committer;
  1174. }
  1175. /**
  1176. * Insert changeId
  1177. *
  1178. * @return this commit builder
  1179. */
  1180. public CommitBuilder insertChangeId() {
  1181. changeId = "";
  1182. return this;
  1183. }
  1184. /**
  1185. * Insert given changeId
  1186. *
  1187. * @param c
  1188. * changeId
  1189. * @return this commit builder
  1190. */
  1191. public CommitBuilder insertChangeId(String c) {
  1192. // Validate, but store as a string so we can use "" as a sentinel.
  1193. ObjectId.fromString(c);
  1194. changeId = c;
  1195. return this;
  1196. }
  1197. /**
  1198. * Create the commit
  1199. *
  1200. * @return the new commit
  1201. * @throws Exception
  1202. * if creation failed
  1203. */
  1204. public RevCommit create() throws Exception {
  1205. if (self == null) {
  1206. TestRepository.this.tick(tick);
  1207. final org.eclipse.jgit.lib.CommitBuilder c;
  1208. c = new org.eclipse.jgit.lib.CommitBuilder();
  1209. c.setParentIds(parents);
  1210. setAuthorAndCommitter(c);
  1211. if (author != null)
  1212. c.setAuthor(author);
  1213. if (committer != null) {
  1214. if (updateCommitterTime)
  1215. committer = new PersonIdent(committer, getDate());
  1216. c.setCommitter(committer);
  1217. }
  1218. ObjectId commitId;
  1219. try (ObjectInserter ins = inserter) {
  1220. if (topLevelTree != null)
  1221. c.setTreeId(topLevelTree);
  1222. else
  1223. c.setTreeId(tree.writeTree(ins));
  1224. insertChangeId(c);
  1225. c.setMessage(message);
  1226. commitId = ins.insert(c);
  1227. ins.flush();
  1228. }
  1229. self = pool.parseCommit(commitId);
  1230. if (branch != null)
  1231. branch.update(self);
  1232. }
  1233. return self;
  1234. }
  1235. private void insertChangeId(org.eclipse.jgit.lib.CommitBuilder c) {
  1236. if (changeId == null)
  1237. return;
  1238. int idx = ChangeIdUtil.indexOfChangeId(message, "\n");
  1239. if (idx >= 0)
  1240. return;
  1241. ObjectId firstParentId = null;
  1242. if (!parents.isEmpty())
  1243. firstParentId = parents.get(0);
  1244. ObjectId cid;
  1245. if (changeId.isEmpty())
  1246. cid = ChangeIdUtil.computeChangeId(c.getTreeId(), firstParentId,
  1247. c.getAuthor(), c.getCommitter(), message);
  1248. else
  1249. cid = ObjectId.fromString(changeId);
  1250. message = ChangeIdUtil.insertId(message, cid);
  1251. if (cid != null)
  1252. message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
  1253. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
  1254. + cid.getName() + "\n"); //$NON-NLS-1$
  1255. }
  1256. /**
  1257. * Create child commit builder
  1258. *
  1259. * @return child commit builder
  1260. * @throws Exception
  1261. */
  1262. public CommitBuilder child() throws Exception {
  1263. return new CommitBuilder(this);
  1264. }
  1265. }
  1266. }