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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  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.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. /**
  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. public CommitBuilder parent(RevCommit p) throws Exception {
  980. if (parents.isEmpty()) {
  981. DirCacheBuilder b = tree.builder();
  982. parseBody(p);
  983. b.addTree(new byte[0], DirCacheEntry.STAGE_0, pool
  984. .getObjectReader(), p.getTree());
  985. b.finish();
  986. }
  987. parents.add(p);
  988. return this;
  989. }
  990. public List<RevCommit> parents() {
  991. return Collections.unmodifiableList(parents);
  992. }
  993. public CommitBuilder noParents() {
  994. parents.clear();
  995. return this;
  996. }
  997. public CommitBuilder noFiles() {
  998. tree.clear();
  999. return this;
  1000. }
  1001. public CommitBuilder setTopLevelTree(ObjectId treeId) {
  1002. topLevelTree = treeId;
  1003. return this;
  1004. }
  1005. public CommitBuilder add(String path, String content) throws Exception {
  1006. return add(path, blob(content));
  1007. }
  1008. public CommitBuilder add(String path, RevBlob id)
  1009. throws Exception {
  1010. return edit(new PathEdit(path) {
  1011. @Override
  1012. public void apply(DirCacheEntry ent) {
  1013. ent.setFileMode(FileMode.REGULAR_FILE);
  1014. ent.setObjectId(id);
  1015. }
  1016. });
  1017. }
  1018. public CommitBuilder edit(PathEdit edit) {
  1019. DirCacheEditor e = tree.editor();
  1020. e.add(edit);
  1021. e.finish();
  1022. return this;
  1023. }
  1024. public CommitBuilder rm(String path) {
  1025. DirCacheEditor e = tree.editor();
  1026. e.add(new DeletePath(path));
  1027. e.add(new DeleteTree(path));
  1028. e.finish();
  1029. return this;
  1030. }
  1031. public CommitBuilder message(String m) {
  1032. message = m;
  1033. return this;
  1034. }
  1035. public String message() {
  1036. return message;
  1037. }
  1038. public CommitBuilder tick(int secs) {
  1039. tick = secs;
  1040. return this;
  1041. }
  1042. public CommitBuilder ident(PersonIdent ident) {
  1043. author = ident;
  1044. committer = ident;
  1045. return this;
  1046. }
  1047. public CommitBuilder author(PersonIdent a) {
  1048. author = a;
  1049. return this;
  1050. }
  1051. public PersonIdent author() {
  1052. return author;
  1053. }
  1054. public CommitBuilder committer(PersonIdent c) {
  1055. committer = c;
  1056. return this;
  1057. }
  1058. public PersonIdent committer() {
  1059. return committer;
  1060. }
  1061. public CommitBuilder insertChangeId() {
  1062. changeId = "";
  1063. return this;
  1064. }
  1065. public CommitBuilder insertChangeId(String c) {
  1066. // Validate, but store as a string so we can use "" as a sentinel.
  1067. ObjectId.fromString(c);
  1068. changeId = c;
  1069. return this;
  1070. }
  1071. public RevCommit create() throws Exception {
  1072. if (self == null) {
  1073. TestRepository.this.tick(tick);
  1074. final org.eclipse.jgit.lib.CommitBuilder c;
  1075. c = new org.eclipse.jgit.lib.CommitBuilder();
  1076. c.setParentIds(parents);
  1077. setAuthorAndCommitter(c);
  1078. if (author != null)
  1079. c.setAuthor(author);
  1080. if (committer != null) {
  1081. if (updateCommitterTime)
  1082. committer = new PersonIdent(committer, getDate());
  1083. c.setCommitter(committer);
  1084. }
  1085. ObjectId commitId;
  1086. try (ObjectInserter ins = inserter) {
  1087. if (topLevelTree != null)
  1088. c.setTreeId(topLevelTree);
  1089. else
  1090. c.setTreeId(tree.writeTree(ins));
  1091. insertChangeId(c);
  1092. c.setMessage(message);
  1093. commitId = ins.insert(c);
  1094. ins.flush();
  1095. }
  1096. self = pool.parseCommit(commitId);
  1097. if (branch != null)
  1098. branch.update(self);
  1099. }
  1100. return self;
  1101. }
  1102. private void insertChangeId(org.eclipse.jgit.lib.CommitBuilder c) {
  1103. if (changeId == null)
  1104. return;
  1105. int idx = ChangeIdUtil.indexOfChangeId(message, "\n");
  1106. if (idx >= 0)
  1107. return;
  1108. ObjectId firstParentId = null;
  1109. if (!parents.isEmpty())
  1110. firstParentId = parents.get(0);
  1111. ObjectId cid;
  1112. if (changeId.isEmpty())
  1113. cid = ChangeIdUtil.computeChangeId(c.getTreeId(), firstParentId,
  1114. c.getAuthor(), c.getCommitter(), message);
  1115. else
  1116. cid = ObjectId.fromString(changeId);
  1117. message = ChangeIdUtil.insertId(message, cid);
  1118. if (cid != null)
  1119. message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
  1120. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
  1121. + cid.getName() + "\n"); //$NON-NLS-1$
  1122. }
  1123. public CommitBuilder child() throws Exception {
  1124. return new CommitBuilder(this);
  1125. }
  1126. }
  1127. }