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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  1. /*
  2. * Copyright (C) 2009-2010, Google Inc.
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.junit;
  44. import static org.eclipse.jgit.lib.Constants.CHARSET;
  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(CHARSET));
  245. }
  246. /**
  247. * Create a new blob object in the repository.
  248. *
  249. * @param content
  250. * binary file content.
  251. * @return reference to the 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 pool.lookupBlob(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 reference to the 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 (final DirCacheEntry e : entries)
  292. b.add(e);
  293. b.finish();
  294. ObjectId root;
  295. try (ObjectInserter ins = inserter) {
  296. root = dc.writeTree(ins);
  297. ins.flush();
  298. }
  299. return pool.lookupTree(root);
  300. }
  301. /**
  302. * Lookup an entry stored in a tree, failing if not present.
  303. *
  304. * @param tree
  305. * the tree to search.
  306. * @param path
  307. * the path to find the entry of.
  308. * @return the parsed object entry at this path, never null.
  309. * @throws Exception
  310. */
  311. public RevObject get(RevTree tree, String path)
  312. throws Exception {
  313. try (TreeWalk tw = new TreeWalk(pool.getObjectReader())) {
  314. tw.setFilter(PathFilterGroup.createFromStrings(Collections
  315. .singleton(path)));
  316. tw.reset(tree);
  317. while (tw.next()) {
  318. if (tw.isSubtree() && !path.equals(tw.getPathString())) {
  319. tw.enterSubtree();
  320. continue;
  321. }
  322. final ObjectId entid = tw.getObjectId(0);
  323. final FileMode entmode = tw.getFileMode(0);
  324. return pool.lookupAny(entid, entmode.getObjectType());
  325. }
  326. }
  327. fail("Can't find " + path + " in tree " + tree.name());
  328. return null; // never reached.
  329. }
  330. /**
  331. * Create a new commit.
  332. * <p>
  333. * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
  334. * tree (no files or subdirectories).
  335. *
  336. * @param parents
  337. * zero or more parents of the commit.
  338. * @return the new commit.
  339. * @throws Exception
  340. */
  341. public RevCommit commit(RevCommit... parents) throws Exception {
  342. return commit(1, tree(), parents);
  343. }
  344. /**
  345. * Create a new commit.
  346. * <p>
  347. * See {@link #commit(int, RevTree, RevCommit...)}.
  348. *
  349. * @param tree
  350. * the root tree for the commit.
  351. * @param parents
  352. * zero or more parents of the commit.
  353. * @return the new commit.
  354. * @throws Exception
  355. */
  356. public RevCommit commit(RevTree tree, RevCommit... parents)
  357. throws Exception {
  358. return commit(1, tree, parents);
  359. }
  360. /**
  361. * Create a new commit.
  362. * <p>
  363. * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
  364. * tree (no files or subdirectories).
  365. *
  366. * @param secDelta
  367. * number of seconds to advance {@link #tick(int)} by.
  368. * @param parents
  369. * zero or more parents of the commit.
  370. * @return the new commit.
  371. * @throws Exception
  372. */
  373. public RevCommit commit(int secDelta, RevCommit... parents)
  374. throws Exception {
  375. return commit(secDelta, tree(), parents);
  376. }
  377. /**
  378. * Create a new commit.
  379. * <p>
  380. * The author and committer identities are stored using the current
  381. * timestamp, after being incremented by {@code secDelta}. The message body
  382. * is empty.
  383. *
  384. * @param secDelta
  385. * number of seconds to advance {@link #tick(int)} by.
  386. * @param tree
  387. * the root tree for the commit.
  388. * @param parents
  389. * zero or more parents of the commit.
  390. * @return the new commit.
  391. * @throws Exception
  392. */
  393. public RevCommit commit(final int secDelta, final RevTree tree,
  394. final RevCommit... parents) throws Exception {
  395. tick(secDelta);
  396. final org.eclipse.jgit.lib.CommitBuilder c;
  397. c = new org.eclipse.jgit.lib.CommitBuilder();
  398. c.setTreeId(tree);
  399. c.setParentIds(parents);
  400. c.setAuthor(new PersonIdent(defaultAuthor, getDate()));
  401. c.setCommitter(new PersonIdent(defaultCommitter, getDate()));
  402. c.setMessage("");
  403. ObjectId id;
  404. try (ObjectInserter ins = inserter) {
  405. id = ins.insert(c);
  406. ins.flush();
  407. }
  408. return pool.lookupCommit(id);
  409. }
  410. /**
  411. * Create commit builder
  412. *
  413. * @return a new commit builder.
  414. */
  415. public CommitBuilder commit() {
  416. return new CommitBuilder();
  417. }
  418. /**
  419. * Construct an annotated tag object pointing at another object.
  420. * <p>
  421. * The tagger is the committer identity, at the current time as specified by
  422. * {@link #tick(int)}. The time is not increased.
  423. * <p>
  424. * The tag message is empty.
  425. *
  426. * @param name
  427. * name of the tag. Traditionally a tag name should not start
  428. * with {@code refs/tags/}.
  429. * @param dst
  430. * object the tag should be pointed at.
  431. * @return the annotated tag object.
  432. * @throws Exception
  433. */
  434. public RevTag tag(String name, RevObject dst) throws Exception {
  435. final TagBuilder t = new TagBuilder();
  436. t.setObjectId(dst);
  437. t.setTag(name);
  438. t.setTagger(new PersonIdent(defaultCommitter, getDate()));
  439. t.setMessage("");
  440. ObjectId id;
  441. try (ObjectInserter ins = inserter) {
  442. id = ins.insert(t);
  443. ins.flush();
  444. }
  445. return (RevTag) pool.lookupAny(id, Constants.OBJ_TAG);
  446. }
  447. /**
  448. * Update a reference to point to an object.
  449. *
  450. * @param ref
  451. * the name of the reference to update to. If {@code ref} does
  452. * not start with {@code refs/} and is not the magic names
  453. * {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
  454. * {@code refs/heads/} will be prefixed in front of the given
  455. * name, thereby assuming it is a branch.
  456. * @param to
  457. * the target object.
  458. * @return the target object.
  459. * @throws Exception
  460. */
  461. public RevCommit update(String ref, CommitBuilder to) throws Exception {
  462. return update(ref, to.create());
  463. }
  464. /**
  465. * Amend an existing ref.
  466. *
  467. * @param ref
  468. * the name of the reference to amend, which must already exist.
  469. * If {@code ref} does not start with {@code refs/} and is not the
  470. * magic names {@code HEAD} {@code FETCH_HEAD} or {@code
  471. * MERGE_HEAD}, then {@code refs/heads/} will be prefixed in front
  472. * of the given name, thereby assuming it is a branch.
  473. * @return commit builder that amends the branch on commit.
  474. * @throws Exception
  475. */
  476. public CommitBuilder amendRef(String ref) throws Exception {
  477. String name = normalizeRef(ref);
  478. Ref r = db.exactRef(name);
  479. if (r == null)
  480. throw new IOException("Not a ref: " + ref);
  481. return amend(pool.parseCommit(r.getObjectId()), branch(name).commit());
  482. }
  483. /**
  484. * Amend an existing commit.
  485. *
  486. * @param id
  487. * the id of the commit to amend.
  488. * @return commit builder.
  489. * @throws Exception
  490. */
  491. public CommitBuilder amend(AnyObjectId id) throws Exception {
  492. return amend(pool.parseCommit(id), commit());
  493. }
  494. private CommitBuilder amend(RevCommit old, CommitBuilder b) throws Exception {
  495. pool.parseBody(old);
  496. b.author(old.getAuthorIdent());
  497. b.committer(old.getCommitterIdent());
  498. b.message(old.getFullMessage());
  499. // Use the committer name from the old commit, but update it after ticking
  500. // the clock in CommitBuilder#create().
  501. b.updateCommitterTime = true;
  502. // Reset parents to original parents.
  503. b.noParents();
  504. for (int i = 0; i < old.getParentCount(); i++)
  505. b.parent(old.getParent(i));
  506. // Reset tree to original tree; resetting parents reset tree contents to the
  507. // first parent.
  508. b.tree.clear();
  509. try (TreeWalk tw = new TreeWalk(db)) {
  510. tw.reset(old.getTree());
  511. tw.setRecursive(true);
  512. while (tw.next()) {
  513. b.edit(new PathEdit(tw.getPathString()) {
  514. @Override
  515. public void apply(DirCacheEntry ent) {
  516. ent.setFileMode(tw.getFileMode(0));
  517. ent.setObjectId(tw.getObjectId(0));
  518. }
  519. });
  520. }
  521. }
  522. return b;
  523. }
  524. /**
  525. * Update a reference to point to an object.
  526. *
  527. * @param <T>
  528. * type of the target object.
  529. * @param ref
  530. * the name of the reference to update to. If {@code ref} does
  531. * not start with {@code refs/} and is not the magic names
  532. * {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
  533. * {@code refs/heads/} will be prefixed in front of the given
  534. * name, thereby assuming it is a branch.
  535. * @param obj
  536. * the target object.
  537. * @return the target object.
  538. * @throws Exception
  539. */
  540. public <T extends AnyObjectId> T update(String ref, T obj) throws Exception {
  541. ref = normalizeRef(ref);
  542. RefUpdate u = db.updateRef(ref);
  543. u.setNewObjectId(obj);
  544. switch (u.forceUpdate()) {
  545. case FAST_FORWARD:
  546. case FORCED:
  547. case NEW:
  548. case NO_CHANGE:
  549. updateServerInfo();
  550. return obj;
  551. default:
  552. throw new IOException("Cannot write " + ref + " " + u.getResult());
  553. }
  554. }
  555. /**
  556. * Delete a reference.
  557. *
  558. * @param ref
  559. * the name of the reference to delete. This is normalized
  560. * in the same way as {@link #update(String, AnyObjectId)}.
  561. * @throws Exception
  562. * @since 4.4
  563. */
  564. public void delete(String ref) throws Exception {
  565. ref = normalizeRef(ref);
  566. RefUpdate u = db.updateRef(ref);
  567. u.setForceUpdate(true);
  568. switch (u.delete()) {
  569. case FAST_FORWARD:
  570. case FORCED:
  571. case NEW:
  572. case NO_CHANGE:
  573. updateServerInfo();
  574. return;
  575. default:
  576. throw new IOException("Cannot delete " + ref + " " + u.getResult());
  577. }
  578. }
  579. private static String normalizeRef(String ref) {
  580. if (Constants.HEAD.equals(ref)) {
  581. // nothing
  582. } else if ("FETCH_HEAD".equals(ref)) {
  583. // nothing
  584. } else if ("MERGE_HEAD".equals(ref)) {
  585. // nothing
  586. } else if (ref.startsWith(Constants.R_REFS)) {
  587. // nothing
  588. } else
  589. ref = Constants.R_HEADS + ref;
  590. return ref;
  591. }
  592. /**
  593. * Soft-reset HEAD to a detached state.
  594. *
  595. * @param id
  596. * ID of detached head.
  597. * @throws Exception
  598. * @see #reset(String)
  599. */
  600. public void reset(AnyObjectId id) throws Exception {
  601. RefUpdate ru = db.updateRef(Constants.HEAD, true);
  602. ru.setNewObjectId(id);
  603. RefUpdate.Result result = ru.forceUpdate();
  604. switch (result) {
  605. case FAST_FORWARD:
  606. case FORCED:
  607. case NEW:
  608. case NO_CHANGE:
  609. break;
  610. default:
  611. throw new IOException(String.format(
  612. "Checkout \"%s\" failed: %s", id.name(), result));
  613. }
  614. }
  615. /**
  616. * Soft-reset HEAD to a different commit.
  617. * <p>
  618. * This is equivalent to {@code git reset --soft} in that it modifies HEAD but
  619. * not the index or the working tree of a non-bare repository.
  620. *
  621. * @param name
  622. * revision string; either an existing ref name, or something that
  623. * can be parsed to an object ID.
  624. * @throws Exception
  625. */
  626. public void reset(String name) throws Exception {
  627. RefUpdate.Result result;
  628. ObjectId id = db.resolve(name);
  629. if (id == null)
  630. throw new IOException("Not a revision: " + name);
  631. RefUpdate ru = db.updateRef(Constants.HEAD, false);
  632. ru.setNewObjectId(id);
  633. result = ru.forceUpdate();
  634. switch (result) {
  635. case FAST_FORWARD:
  636. case FORCED:
  637. case NEW:
  638. case NO_CHANGE:
  639. break;
  640. default:
  641. throw new IOException(String.format(
  642. "Checkout \"%s\" failed: %s", name, result));
  643. }
  644. }
  645. /**
  646. * Cherry-pick a commit onto HEAD.
  647. * <p>
  648. * This differs from {@code git cherry-pick} in that it works in a bare
  649. * repository. As a result, any merge failure results in an exception, as
  650. * there is no way to recover.
  651. *
  652. * @param id
  653. * commit-ish to cherry-pick.
  654. * @return newly created commit, or null if no work was done due to the
  655. * resulting tree being identical.
  656. * @throws Exception
  657. */
  658. public RevCommit cherryPick(AnyObjectId id) throws Exception {
  659. RevCommit commit = pool.parseCommit(id);
  660. pool.parseBody(commit);
  661. if (commit.getParentCount() != 1)
  662. throw new IOException(String.format(
  663. "Expected 1 parent for %s, found: %s",
  664. id.name(), Arrays.asList(commit.getParents())));
  665. RevCommit parent = commit.getParent(0);
  666. pool.parseHeaders(parent);
  667. Ref headRef = db.exactRef(Constants.HEAD);
  668. if (headRef == null)
  669. throw new IOException("Missing HEAD");
  670. RevCommit head = pool.parseCommit(headRef.getObjectId());
  671. ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
  672. merger.setBase(parent.getTree());
  673. if (merger.merge(head, commit)) {
  674. if (AnyObjectId.equals(head.getTree(), merger.getResultTreeId()))
  675. return null;
  676. tick(1);
  677. org.eclipse.jgit.lib.CommitBuilder b =
  678. new org.eclipse.jgit.lib.CommitBuilder();
  679. b.setParentId(head);
  680. b.setTreeId(merger.getResultTreeId());
  681. b.setAuthor(commit.getAuthorIdent());
  682. b.setCommitter(new PersonIdent(defaultCommitter, getDate()));
  683. b.setMessage(commit.getFullMessage());
  684. ObjectId result;
  685. try (ObjectInserter ins = inserter) {
  686. result = ins.insert(b);
  687. ins.flush();
  688. }
  689. update(Constants.HEAD, result);
  690. return pool.parseCommit(result);
  691. } else {
  692. throw new IOException("Merge conflict");
  693. }
  694. }
  695. /**
  696. * Update the dumb client server info files.
  697. *
  698. * @throws Exception
  699. */
  700. public void updateServerInfo() throws Exception {
  701. if (db instanceof FileRepository) {
  702. final FileRepository fr = (FileRepository) db;
  703. RefWriter rw = new RefWriter(fr.getAllRefs().values()) {
  704. @Override
  705. protected void writeFile(String name, byte[] bin)
  706. throws IOException {
  707. File path = new File(fr.getDirectory(), name);
  708. TestRepository.this.writeFile(path, bin);
  709. }
  710. };
  711. rw.writePackedRefs();
  712. rw.writeInfoRefs();
  713. final StringBuilder w = new StringBuilder();
  714. for (PackFile p : fr.getObjectDatabase().getPacks()) {
  715. w.append("P ");
  716. w.append(p.getPackFile().getName());
  717. w.append('\n');
  718. }
  719. writeFile(new File(new File(fr.getObjectDatabase().getDirectory(),
  720. "info"), "packs"), Constants.encodeASCII(w.toString()));
  721. }
  722. }
  723. /**
  724. * Ensure the body of the given object has been parsed.
  725. *
  726. * @param <T>
  727. * type of object, e.g. {@link org.eclipse.jgit.revwalk.RevTag}
  728. * or {@link org.eclipse.jgit.revwalk.RevCommit}.
  729. * @param object
  730. * reference to the (possibly unparsed) object to force body
  731. * parsing of.
  732. * @return {@code object}
  733. * @throws Exception
  734. */
  735. public <T extends RevObject> T parseBody(T object) throws Exception {
  736. pool.parseBody(object);
  737. return object;
  738. }
  739. /**
  740. * Create a new branch builder for this repository.
  741. *
  742. * @param ref
  743. * name of the branch to be constructed. If {@code ref} does not
  744. * start with {@code refs/} the prefix {@code refs/heads/} will
  745. * be added.
  746. * @return builder for the named branch.
  747. */
  748. public BranchBuilder branch(String ref) {
  749. if (Constants.HEAD.equals(ref)) {
  750. // nothing
  751. } else if (ref.startsWith(Constants.R_REFS)) {
  752. // nothing
  753. } else
  754. ref = Constants.R_HEADS + ref;
  755. return new BranchBuilder(ref);
  756. }
  757. /**
  758. * Tag an object using a lightweight tag.
  759. *
  760. * @param name
  761. * the tag name. The /refs/tags/ prefix will be added if the name
  762. * doesn't start with it
  763. * @param obj
  764. * the object to tag
  765. * @return the tagged object
  766. * @throws Exception
  767. */
  768. public ObjectId lightweightTag(String name, ObjectId obj) throws Exception {
  769. if (!name.startsWith(Constants.R_TAGS))
  770. name = Constants.R_TAGS + name;
  771. return update(name, obj);
  772. }
  773. /**
  774. * Run consistency checks against the object database.
  775. * <p>
  776. * This method completes silently if the checks pass. A temporary revision
  777. * pool is constructed during the checking.
  778. *
  779. * @param tips
  780. * the tips to start checking from; if not supplied the refs of
  781. * the repository are used instead.
  782. * @throws MissingObjectException
  783. * @throws IncorrectObjectTypeException
  784. * @throws IOException
  785. */
  786. public void fsck(RevObject... tips) throws MissingObjectException,
  787. IncorrectObjectTypeException, IOException {
  788. try (ObjectWalk ow = new ObjectWalk(db)) {
  789. if (tips.length != 0) {
  790. for (RevObject o : tips)
  791. ow.markStart(ow.parseAny(o));
  792. } else {
  793. for (Ref r : db.getAllRefs().values())
  794. ow.markStart(ow.parseAny(r.getObjectId()));
  795. }
  796. ObjectChecker oc = new ObjectChecker();
  797. for (;;) {
  798. final RevCommit o = ow.next();
  799. if (o == null)
  800. break;
  801. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  802. oc.checkCommit(o, bin);
  803. assertHash(o, bin);
  804. }
  805. for (;;) {
  806. final RevObject o = ow.nextObject();
  807. if (o == null)
  808. break;
  809. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  810. oc.check(o, o.getType(), bin);
  811. assertHash(o, bin);
  812. }
  813. }
  814. }
  815. private static void assertHash(RevObject id, byte[] bin) {
  816. MessageDigest md = Constants.newMessageDigest();
  817. md.update(Constants.encodedTypeString(id.getType()));
  818. md.update((byte) ' ');
  819. md.update(Constants.encodeASCII(bin.length));
  820. md.update((byte) 0);
  821. md.update(bin);
  822. assertEquals(id, ObjectId.fromRaw(md.digest()));
  823. }
  824. /**
  825. * Pack all reachable objects in the repository into a single pack file.
  826. * <p>
  827. * All loose objects are automatically pruned. Existing packs however are
  828. * not removed.
  829. *
  830. * @throws Exception
  831. */
  832. public void packAndPrune() throws Exception {
  833. if (db.getObjectDatabase() instanceof ObjectDirectory) {
  834. ObjectDirectory odb = (ObjectDirectory) db.getObjectDatabase();
  835. NullProgressMonitor m = NullProgressMonitor.INSTANCE;
  836. final File pack, idx;
  837. try (PackWriter pw = new PackWriter(db)) {
  838. Set<ObjectId> all = new HashSet<>();
  839. for (Ref r : db.getAllRefs().values())
  840. all.add(r.getObjectId());
  841. pw.preparePack(m, all, PackWriter.NONE);
  842. final ObjectId name = pw.computeName();
  843. pack = nameFor(odb, name, ".pack");
  844. try (OutputStream out =
  845. new BufferedOutputStream(new FileOutputStream(pack))) {
  846. pw.writePack(m, m, out);
  847. }
  848. pack.setReadOnly();
  849. idx = nameFor(odb, name, ".idx");
  850. try (OutputStream out =
  851. new BufferedOutputStream(new FileOutputStream(idx))) {
  852. pw.writeIndex(out);
  853. }
  854. idx.setReadOnly();
  855. }
  856. odb.openPack(pack);
  857. updateServerInfo();
  858. prunePacked(odb);
  859. }
  860. }
  861. private static void prunePacked(ObjectDirectory odb) throws IOException {
  862. for (PackFile p : odb.getPacks()) {
  863. for (MutableEntry e : p)
  864. FileUtils.delete(odb.fileFor(e.toObjectId()));
  865. }
  866. }
  867. private static File nameFor(ObjectDirectory odb, ObjectId name, String t) {
  868. File packdir = odb.getPackDirectory();
  869. return new File(packdir, "pack-" + name.name() + t);
  870. }
  871. private void writeFile(File p, byte[] bin) throws IOException,
  872. ObjectWritingException {
  873. final LockFile lck = new LockFile(p);
  874. if (!lck.lock())
  875. throw new ObjectWritingException("Can't write " + p);
  876. try {
  877. lck.write(bin);
  878. } catch (IOException ioe) {
  879. throw new ObjectWritingException("Can't write " + p);
  880. }
  881. if (!lck.commit())
  882. throw new ObjectWritingException("Can't write " + p);
  883. }
  884. /** Helper to build a branch with one or more commits */
  885. public class BranchBuilder {
  886. private final String ref;
  887. BranchBuilder(final String ref) {
  888. this.ref = ref;
  889. }
  890. /**
  891. * @return construct a new commit builder that updates this branch. If
  892. * the branch already exists, the commit builder will have its
  893. * first parent as the current commit and its tree will be
  894. * initialized to the current files.
  895. * @throws Exception
  896. * the commit builder can't read the current branch state
  897. */
  898. public CommitBuilder commit() throws Exception {
  899. return new CommitBuilder(this);
  900. }
  901. /**
  902. * Forcefully update this branch to a particular commit.
  903. *
  904. * @param to
  905. * the commit to update to.
  906. * @return {@code to}.
  907. * @throws Exception
  908. */
  909. public RevCommit update(CommitBuilder to) throws Exception {
  910. return update(to.create());
  911. }
  912. /**
  913. * Forcefully update this branch to a particular commit.
  914. *
  915. * @param to
  916. * the commit to update to.
  917. * @return {@code to}.
  918. * @throws Exception
  919. */
  920. public RevCommit update(RevCommit to) throws Exception {
  921. return TestRepository.this.update(ref, to);
  922. }
  923. /**
  924. * Delete this branch.
  925. * @throws Exception
  926. * @since 4.4
  927. */
  928. public void delete() throws Exception {
  929. TestRepository.this.delete(ref);
  930. }
  931. }
  932. /** Helper to generate a commit. */
  933. public class CommitBuilder {
  934. private final BranchBuilder branch;
  935. private final DirCache tree = DirCache.newInCore();
  936. private ObjectId topLevelTree;
  937. private final List<RevCommit> parents = new ArrayList<>(2);
  938. private int tick = 1;
  939. private String message = "";
  940. private RevCommit self;
  941. private PersonIdent author;
  942. private PersonIdent committer;
  943. private String changeId;
  944. private boolean updateCommitterTime;
  945. CommitBuilder() {
  946. branch = null;
  947. }
  948. CommitBuilder(BranchBuilder b) throws Exception {
  949. branch = b;
  950. Ref ref = db.exactRef(branch.ref);
  951. if (ref != null && ref.getObjectId() != null)
  952. parent(pool.parseCommit(ref.getObjectId()));
  953. }
  954. CommitBuilder(CommitBuilder prior) throws Exception {
  955. branch = prior.branch;
  956. DirCacheBuilder b = tree.builder();
  957. for (int i = 0; i < prior.tree.getEntryCount(); i++)
  958. b.add(prior.tree.getEntry(i));
  959. b.finish();
  960. parents.add(prior.create());
  961. }
  962. public CommitBuilder parent(RevCommit p) throws Exception {
  963. if (parents.isEmpty()) {
  964. DirCacheBuilder b = tree.builder();
  965. parseBody(p);
  966. b.addTree(new byte[0], DirCacheEntry.STAGE_0, pool
  967. .getObjectReader(), p.getTree());
  968. b.finish();
  969. }
  970. parents.add(p);
  971. return this;
  972. }
  973. public List<RevCommit> parents() {
  974. return Collections.unmodifiableList(parents);
  975. }
  976. public CommitBuilder noParents() {
  977. parents.clear();
  978. return this;
  979. }
  980. public CommitBuilder noFiles() {
  981. tree.clear();
  982. return this;
  983. }
  984. public CommitBuilder setTopLevelTree(ObjectId treeId) {
  985. topLevelTree = treeId;
  986. return this;
  987. }
  988. public CommitBuilder add(String path, String content) throws Exception {
  989. return add(path, blob(content));
  990. }
  991. public CommitBuilder add(String path, RevBlob id)
  992. throws Exception {
  993. return edit(new PathEdit(path) {
  994. @Override
  995. public void apply(DirCacheEntry ent) {
  996. ent.setFileMode(FileMode.REGULAR_FILE);
  997. ent.setObjectId(id);
  998. }
  999. });
  1000. }
  1001. public CommitBuilder edit(PathEdit edit) {
  1002. DirCacheEditor e = tree.editor();
  1003. e.add(edit);
  1004. e.finish();
  1005. return this;
  1006. }
  1007. public CommitBuilder rm(String path) {
  1008. DirCacheEditor e = tree.editor();
  1009. e.add(new DeletePath(path));
  1010. e.add(new DeleteTree(path));
  1011. e.finish();
  1012. return this;
  1013. }
  1014. public CommitBuilder message(String m) {
  1015. message = m;
  1016. return this;
  1017. }
  1018. public String message() {
  1019. return message;
  1020. }
  1021. public CommitBuilder tick(int secs) {
  1022. tick = secs;
  1023. return this;
  1024. }
  1025. public CommitBuilder ident(PersonIdent ident) {
  1026. author = ident;
  1027. committer = ident;
  1028. return this;
  1029. }
  1030. public CommitBuilder author(PersonIdent a) {
  1031. author = a;
  1032. return this;
  1033. }
  1034. public PersonIdent author() {
  1035. return author;
  1036. }
  1037. public CommitBuilder committer(PersonIdent c) {
  1038. committer = c;
  1039. return this;
  1040. }
  1041. public PersonIdent committer() {
  1042. return committer;
  1043. }
  1044. public CommitBuilder insertChangeId() {
  1045. changeId = "";
  1046. return this;
  1047. }
  1048. public CommitBuilder insertChangeId(String c) {
  1049. // Validate, but store as a string so we can use "" as a sentinel.
  1050. ObjectId.fromString(c);
  1051. changeId = c;
  1052. return this;
  1053. }
  1054. public RevCommit create() throws Exception {
  1055. if (self == null) {
  1056. TestRepository.this.tick(tick);
  1057. final org.eclipse.jgit.lib.CommitBuilder c;
  1058. c = new org.eclipse.jgit.lib.CommitBuilder();
  1059. c.setParentIds(parents);
  1060. setAuthorAndCommitter(c);
  1061. if (author != null)
  1062. c.setAuthor(author);
  1063. if (committer != null) {
  1064. if (updateCommitterTime)
  1065. committer = new PersonIdent(committer, getDate());
  1066. c.setCommitter(committer);
  1067. }
  1068. ObjectId commitId;
  1069. try (ObjectInserter ins = inserter) {
  1070. if (topLevelTree != null)
  1071. c.setTreeId(topLevelTree);
  1072. else
  1073. c.setTreeId(tree.writeTree(ins));
  1074. insertChangeId(c);
  1075. c.setMessage(message);
  1076. commitId = ins.insert(c);
  1077. ins.flush();
  1078. }
  1079. self = pool.lookupCommit(commitId);
  1080. if (branch != null)
  1081. branch.update(self);
  1082. }
  1083. return self;
  1084. }
  1085. private void insertChangeId(org.eclipse.jgit.lib.CommitBuilder c) {
  1086. if (changeId == null)
  1087. return;
  1088. int idx = ChangeIdUtil.indexOfChangeId(message, "\n");
  1089. if (idx >= 0)
  1090. return;
  1091. ObjectId firstParentId = null;
  1092. if (!parents.isEmpty())
  1093. firstParentId = parents.get(0);
  1094. ObjectId cid;
  1095. if (changeId.equals(""))
  1096. cid = ChangeIdUtil.computeChangeId(c.getTreeId(), firstParentId,
  1097. c.getAuthor(), c.getCommitter(), message);
  1098. else
  1099. cid = ObjectId.fromString(changeId);
  1100. message = ChangeIdUtil.insertId(message, cid);
  1101. if (cid != null)
  1102. message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
  1103. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
  1104. + cid.getName() + "\n"); //$NON-NLS-1$
  1105. }
  1106. public CommitBuilder child() throws Exception {
  1107. return new CommitBuilder(this);
  1108. }
  1109. }
  1110. }