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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429
  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, unparsed commit.
  333. * <p>
  334. * See {@link #unparsedCommit(int, RevTree, ObjectId...)}. The tree is the
  335. * empty tree (no files or subdirectories).
  336. *
  337. * @param parents
  338. * zero or more IDs of the commit's parents.
  339. * @return the ID of the new commit.
  340. * @throws Exception
  341. */
  342. public ObjectId unparsedCommit(ObjectId... parents) throws Exception {
  343. return unparsedCommit(1, tree(), parents);
  344. }
  345. /**
  346. * Create a new commit.
  347. * <p>
  348. * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
  349. * tree (no files or subdirectories).
  350. *
  351. * @param parents
  352. * zero or more parents of the commit.
  353. * @return the new commit.
  354. * @throws Exception
  355. */
  356. public RevCommit commit(RevCommit... parents) throws Exception {
  357. return commit(1, tree(), parents);
  358. }
  359. /**
  360. * Create a new commit.
  361. * <p>
  362. * See {@link #commit(int, RevTree, RevCommit...)}.
  363. *
  364. * @param tree
  365. * the root tree for the commit.
  366. * @param parents
  367. * zero or more parents of the commit.
  368. * @return the new commit.
  369. * @throws Exception
  370. */
  371. public RevCommit commit(RevTree tree, RevCommit... parents)
  372. throws Exception {
  373. return commit(1, tree, parents);
  374. }
  375. /**
  376. * Create a new commit.
  377. * <p>
  378. * See {@link #commit(int, RevTree, RevCommit...)}. The tree is the empty
  379. * tree (no files or subdirectories).
  380. *
  381. * @param secDelta
  382. * number of seconds to advance {@link #tick(int)} by.
  383. * @param parents
  384. * zero or more parents of the commit.
  385. * @return the new commit.
  386. * @throws Exception
  387. */
  388. public RevCommit commit(int secDelta, RevCommit... parents)
  389. throws Exception {
  390. return commit(secDelta, tree(), parents);
  391. }
  392. /**
  393. * Create a new commit.
  394. * <p>
  395. * The author and committer identities are stored using the current
  396. * timestamp, after being incremented by {@code secDelta}. The message body
  397. * is empty.
  398. *
  399. * @param secDelta
  400. * number of seconds to advance {@link #tick(int)} by.
  401. * @param tree
  402. * the root tree for the commit.
  403. * @param parents
  404. * zero or more parents of the commit.
  405. * @return the new, fully parsed commit.
  406. * @throws Exception
  407. */
  408. public RevCommit commit(final int secDelta, final RevTree tree,
  409. final RevCommit... parents) throws Exception {
  410. ObjectId id = unparsedCommit(secDelta, tree, parents);
  411. return pool.parseCommit(id);
  412. }
  413. /**
  414. * Create a new, unparsed commit.
  415. * <p>
  416. * The author and committer identities are stored using the current
  417. * timestamp, after being incremented by {@code secDelta}. The message body
  418. * is empty.
  419. *
  420. * @param secDelta
  421. * number of seconds to advance {@link #tick(int)} by.
  422. * @param tree
  423. * the root tree for the commit.
  424. * @param parents
  425. * zero or more IDs of the commit's parents.
  426. * @return the ID of the new commit.
  427. * @throws Exception
  428. */
  429. public ObjectId unparsedCommit(final int secDelta, final RevTree tree,
  430. final ObjectId... parents) throws Exception {
  431. tick(secDelta);
  432. final org.eclipse.jgit.lib.CommitBuilder c;
  433. c = new org.eclipse.jgit.lib.CommitBuilder();
  434. c.setTreeId(tree);
  435. c.setParentIds(parents);
  436. c.setAuthor(new PersonIdent(defaultAuthor, getDate()));
  437. c.setCommitter(new PersonIdent(defaultCommitter, getDate()));
  438. c.setMessage("");
  439. ObjectId id;
  440. try (ObjectInserter ins = inserter) {
  441. id = ins.insert(c);
  442. ins.flush();
  443. }
  444. return id;
  445. }
  446. /**
  447. * Create commit builder
  448. *
  449. * @return a new commit builder.
  450. */
  451. public CommitBuilder commit() {
  452. return new CommitBuilder();
  453. }
  454. /**
  455. * Construct an annotated tag object pointing at another object.
  456. * <p>
  457. * The tagger is the committer identity, at the current time as specified by
  458. * {@link #tick(int)}. The time is not increased.
  459. * <p>
  460. * The tag message is empty.
  461. *
  462. * @param name
  463. * name of the tag. Traditionally a tag name should not start
  464. * with {@code refs/tags/}.
  465. * @param dst
  466. * object the tag should be pointed at.
  467. * @return the new, fully parsed annotated tag object.
  468. * @throws Exception
  469. */
  470. public RevTag tag(String name, RevObject dst) throws Exception {
  471. final TagBuilder t = new TagBuilder();
  472. t.setObjectId(dst);
  473. t.setTag(name);
  474. t.setTagger(new PersonIdent(defaultCommitter, getDate()));
  475. t.setMessage("");
  476. ObjectId id;
  477. try (ObjectInserter ins = inserter) {
  478. id = ins.insert(t);
  479. ins.flush();
  480. }
  481. return pool.parseTag(id);
  482. }
  483. /**
  484. * Update a reference to point to an object.
  485. *
  486. * @param ref
  487. * the name of the reference to update to. If {@code ref} does
  488. * not start with {@code refs/} and is not the magic names
  489. * {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
  490. * {@code refs/heads/} will be prefixed in front of the given
  491. * name, thereby assuming it is a branch.
  492. * @param to
  493. * the target object.
  494. * @return the target object.
  495. * @throws Exception
  496. */
  497. public RevCommit update(String ref, CommitBuilder to) throws Exception {
  498. return update(ref, to.create());
  499. }
  500. /**
  501. * Amend an existing ref.
  502. *
  503. * @param ref
  504. * the name of the reference to amend, which must already exist.
  505. * If {@code ref} does not start with {@code refs/} and is not the
  506. * magic names {@code HEAD} {@code FETCH_HEAD} or {@code
  507. * MERGE_HEAD}, then {@code refs/heads/} will be prefixed in front
  508. * of the given name, thereby assuming it is a branch.
  509. * @return commit builder that amends the branch on commit.
  510. * @throws Exception
  511. */
  512. public CommitBuilder amendRef(String ref) throws Exception {
  513. String name = normalizeRef(ref);
  514. Ref r = db.exactRef(name);
  515. if (r == null)
  516. throw new IOException("Not a ref: " + ref);
  517. return amend(pool.parseCommit(r.getObjectId()), branch(name).commit());
  518. }
  519. /**
  520. * Amend an existing commit.
  521. *
  522. * @param id
  523. * the id of the commit to amend.
  524. * @return commit builder.
  525. * @throws Exception
  526. */
  527. public CommitBuilder amend(AnyObjectId id) throws Exception {
  528. return amend(pool.parseCommit(id), commit());
  529. }
  530. private CommitBuilder amend(RevCommit old, CommitBuilder b) throws Exception {
  531. pool.parseBody(old);
  532. b.author(old.getAuthorIdent());
  533. b.committer(old.getCommitterIdent());
  534. b.message(old.getFullMessage());
  535. // Use the committer name from the old commit, but update it after ticking
  536. // the clock in CommitBuilder#create().
  537. b.updateCommitterTime = true;
  538. // Reset parents to original parents.
  539. b.noParents();
  540. for (int i = 0; i < old.getParentCount(); i++)
  541. b.parent(old.getParent(i));
  542. // Reset tree to original tree; resetting parents reset tree contents to the
  543. // first parent.
  544. b.tree.clear();
  545. try (TreeWalk tw = new TreeWalk(db)) {
  546. tw.reset(old.getTree());
  547. tw.setRecursive(true);
  548. while (tw.next()) {
  549. b.edit(new PathEdit(tw.getPathString()) {
  550. @Override
  551. public void apply(DirCacheEntry ent) {
  552. ent.setFileMode(tw.getFileMode(0));
  553. ent.setObjectId(tw.getObjectId(0));
  554. }
  555. });
  556. }
  557. }
  558. return b;
  559. }
  560. /**
  561. * Update a reference to point to an object.
  562. *
  563. * @param <T>
  564. * type of the target object.
  565. * @param ref
  566. * the name of the reference to update to. If {@code ref} does
  567. * not start with {@code refs/} and is not the magic names
  568. * {@code HEAD} {@code FETCH_HEAD} or {@code MERGE_HEAD}, then
  569. * {@code refs/heads/} will be prefixed in front of the given
  570. * name, thereby assuming it is a branch.
  571. * @param obj
  572. * the target object.
  573. * @return the target object.
  574. * @throws Exception
  575. */
  576. public <T extends AnyObjectId> T update(String ref, T obj) throws Exception {
  577. ref = normalizeRef(ref);
  578. RefUpdate u = db.updateRef(ref);
  579. u.setNewObjectId(obj);
  580. switch (u.forceUpdate()) {
  581. case FAST_FORWARD:
  582. case FORCED:
  583. case NEW:
  584. case NO_CHANGE:
  585. updateServerInfo();
  586. return obj;
  587. default:
  588. throw new IOException("Cannot write " + ref + " " + u.getResult());
  589. }
  590. }
  591. /**
  592. * Delete a reference.
  593. *
  594. * @param ref
  595. * the name of the reference to delete. This is normalized
  596. * in the same way as {@link #update(String, AnyObjectId)}.
  597. * @throws Exception
  598. * @since 4.4
  599. */
  600. public void delete(String ref) throws Exception {
  601. ref = normalizeRef(ref);
  602. RefUpdate u = db.updateRef(ref);
  603. u.setForceUpdate(true);
  604. switch (u.delete()) {
  605. case FAST_FORWARD:
  606. case FORCED:
  607. case NEW:
  608. case NO_CHANGE:
  609. updateServerInfo();
  610. return;
  611. default:
  612. throw new IOException("Cannot delete " + ref + " " + u.getResult());
  613. }
  614. }
  615. private static String normalizeRef(String ref) {
  616. if (Constants.HEAD.equals(ref)) {
  617. // nothing
  618. } else if ("FETCH_HEAD".equals(ref)) {
  619. // nothing
  620. } else if ("MERGE_HEAD".equals(ref)) {
  621. // nothing
  622. } else if (ref.startsWith(Constants.R_REFS)) {
  623. // nothing
  624. } else
  625. ref = Constants.R_HEADS + ref;
  626. return ref;
  627. }
  628. /**
  629. * Soft-reset HEAD to a detached state.
  630. *
  631. * @param id
  632. * ID of detached head.
  633. * @throws Exception
  634. * @see #reset(String)
  635. */
  636. public void reset(AnyObjectId id) throws Exception {
  637. RefUpdate ru = db.updateRef(Constants.HEAD, true);
  638. ru.setNewObjectId(id);
  639. RefUpdate.Result result = ru.forceUpdate();
  640. switch (result) {
  641. case FAST_FORWARD:
  642. case FORCED:
  643. case NEW:
  644. case NO_CHANGE:
  645. break;
  646. default:
  647. throw new IOException(String.format(
  648. "Checkout \"%s\" failed: %s", id.name(), result));
  649. }
  650. }
  651. /**
  652. * Soft-reset HEAD to a different commit.
  653. * <p>
  654. * This is equivalent to {@code git reset --soft} in that it modifies HEAD but
  655. * not the index or the working tree of a non-bare repository.
  656. *
  657. * @param name
  658. * revision string; either an existing ref name, or something that
  659. * can be parsed to an object ID.
  660. * @throws Exception
  661. */
  662. public void reset(String name) throws Exception {
  663. RefUpdate.Result result;
  664. ObjectId id = db.resolve(name);
  665. if (id == null)
  666. throw new IOException("Not a revision: " + name);
  667. RefUpdate ru = db.updateRef(Constants.HEAD, false);
  668. ru.setNewObjectId(id);
  669. result = ru.forceUpdate();
  670. switch (result) {
  671. case FAST_FORWARD:
  672. case FORCED:
  673. case NEW:
  674. case NO_CHANGE:
  675. break;
  676. default:
  677. throw new IOException(String.format(
  678. "Checkout \"%s\" failed: %s", name, result));
  679. }
  680. }
  681. /**
  682. * Cherry-pick a commit onto HEAD.
  683. * <p>
  684. * This differs from {@code git cherry-pick} in that it works in a bare
  685. * repository. As a result, any merge failure results in an exception, as
  686. * there is no way to recover.
  687. *
  688. * @param id
  689. * commit-ish to cherry-pick.
  690. * @return the new, fully parsed commit, or null if no work was done due to
  691. * the resulting tree being identical.
  692. * @throws Exception
  693. */
  694. public RevCommit cherryPick(AnyObjectId id) throws Exception {
  695. RevCommit commit = pool.parseCommit(id);
  696. pool.parseBody(commit);
  697. if (commit.getParentCount() != 1)
  698. throw new IOException(String.format(
  699. "Expected 1 parent for %s, found: %s",
  700. id.name(), Arrays.asList(commit.getParents())));
  701. RevCommit parent = commit.getParent(0);
  702. pool.parseHeaders(parent);
  703. Ref headRef = db.exactRef(Constants.HEAD);
  704. if (headRef == null)
  705. throw new IOException("Missing HEAD");
  706. RevCommit head = pool.parseCommit(headRef.getObjectId());
  707. ThreeWayMerger merger = MergeStrategy.RECURSIVE.newMerger(db, true);
  708. merger.setBase(parent.getTree());
  709. if (merger.merge(head, commit)) {
  710. if (AnyObjectId.isEqual(head.getTree(), merger.getResultTreeId()))
  711. return null;
  712. tick(1);
  713. org.eclipse.jgit.lib.CommitBuilder b =
  714. new org.eclipse.jgit.lib.CommitBuilder();
  715. b.setParentId(head);
  716. b.setTreeId(merger.getResultTreeId());
  717. b.setAuthor(commit.getAuthorIdent());
  718. b.setCommitter(new PersonIdent(defaultCommitter, getDate()));
  719. b.setMessage(commit.getFullMessage());
  720. ObjectId result;
  721. try (ObjectInserter ins = inserter) {
  722. result = ins.insert(b);
  723. ins.flush();
  724. }
  725. update(Constants.HEAD, result);
  726. return pool.parseCommit(result);
  727. }
  728. throw new IOException("Merge conflict");
  729. }
  730. /**
  731. * Update the dumb client server info files.
  732. *
  733. * @throws Exception
  734. */
  735. public void updateServerInfo() throws Exception {
  736. if (db instanceof FileRepository) {
  737. final FileRepository fr = (FileRepository) db;
  738. RefWriter rw = new RefWriter(fr.getRefDatabase().getRefs()) {
  739. @Override
  740. protected void writeFile(String name, byte[] bin)
  741. throws IOException {
  742. File path = new File(fr.getDirectory(), name);
  743. TestRepository.this.writeFile(path, bin);
  744. }
  745. };
  746. rw.writePackedRefs();
  747. rw.writeInfoRefs();
  748. final StringBuilder w = new StringBuilder();
  749. for (PackFile p : fr.getObjectDatabase().getPacks()) {
  750. w.append("P ");
  751. w.append(p.getPackFile().getName());
  752. w.append('\n');
  753. }
  754. writeFile(new File(new File(fr.getObjectDatabase().getDirectory(),
  755. "info"), "packs"), Constants.encodeASCII(w.toString()));
  756. }
  757. }
  758. /**
  759. * Ensure the body of the given object has been parsed.
  760. *
  761. * @param <T>
  762. * type of object, e.g. {@link org.eclipse.jgit.revwalk.RevTag}
  763. * or {@link org.eclipse.jgit.revwalk.RevCommit}.
  764. * @param object
  765. * reference to the (possibly unparsed) object to force body
  766. * parsing of.
  767. * @return {@code object}
  768. * @throws Exception
  769. */
  770. public <T extends RevObject> T parseBody(T object) throws Exception {
  771. pool.parseBody(object);
  772. return object;
  773. }
  774. /**
  775. * Create a new branch builder for this repository.
  776. *
  777. * @param ref
  778. * name of the branch to be constructed. If {@code ref} does not
  779. * start with {@code refs/} the prefix {@code refs/heads/} will
  780. * be added.
  781. * @return builder for the named branch.
  782. */
  783. public BranchBuilder branch(String ref) {
  784. if (Constants.HEAD.equals(ref)) {
  785. // nothing
  786. } else if (ref.startsWith(Constants.R_REFS)) {
  787. // nothing
  788. } else
  789. ref = Constants.R_HEADS + ref;
  790. return new BranchBuilder(ref);
  791. }
  792. /**
  793. * Tag an object using a lightweight tag.
  794. *
  795. * @param name
  796. * the tag name. The /refs/tags/ prefix will be added if the name
  797. * doesn't start with it
  798. * @param obj
  799. * the object to tag
  800. * @return the tagged object
  801. * @throws Exception
  802. */
  803. public ObjectId lightweightTag(String name, ObjectId obj) throws Exception {
  804. if (!name.startsWith(Constants.R_TAGS))
  805. name = Constants.R_TAGS + name;
  806. return update(name, obj);
  807. }
  808. /**
  809. * Run consistency checks against the object database.
  810. * <p>
  811. * This method completes silently if the checks pass. A temporary revision
  812. * pool is constructed during the checking.
  813. *
  814. * @param tips
  815. * the tips to start checking from; if not supplied the refs of
  816. * the repository are used instead.
  817. * @throws MissingObjectException
  818. * @throws IncorrectObjectTypeException
  819. * @throws IOException
  820. */
  821. public void fsck(RevObject... tips) throws MissingObjectException,
  822. IncorrectObjectTypeException, IOException {
  823. try (ObjectWalk ow = new ObjectWalk(db)) {
  824. if (tips.length != 0) {
  825. for (RevObject o : tips)
  826. ow.markStart(ow.parseAny(o));
  827. } else {
  828. for (Ref r : db.getRefDatabase().getRefs())
  829. ow.markStart(ow.parseAny(r.getObjectId()));
  830. }
  831. ObjectChecker oc = new ObjectChecker();
  832. for (;;) {
  833. final RevCommit o = ow.next();
  834. if (o == null)
  835. break;
  836. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  837. oc.checkCommit(o, bin);
  838. assertHash(o, bin);
  839. }
  840. for (;;) {
  841. final RevObject o = ow.nextObject();
  842. if (o == null)
  843. break;
  844. final byte[] bin = db.open(o, o.getType()).getCachedBytes();
  845. oc.check(o, o.getType(), bin);
  846. assertHash(o, bin);
  847. }
  848. }
  849. }
  850. private static void assertHash(RevObject id, byte[] bin) {
  851. MessageDigest md = Constants.newMessageDigest();
  852. md.update(Constants.encodedTypeString(id.getType()));
  853. md.update((byte) ' ');
  854. md.update(Constants.encodeASCII(bin.length));
  855. md.update((byte) 0);
  856. md.update(bin);
  857. assertEquals(id, ObjectId.fromRaw(md.digest()));
  858. }
  859. /**
  860. * Pack all reachable objects in the repository into a single pack file.
  861. * <p>
  862. * All loose objects are automatically pruned. Existing packs however are
  863. * not removed.
  864. *
  865. * @throws Exception
  866. */
  867. public void packAndPrune() throws Exception {
  868. if (db.getObjectDatabase() instanceof ObjectDirectory) {
  869. ObjectDirectory odb = (ObjectDirectory) db.getObjectDatabase();
  870. NullProgressMonitor m = NullProgressMonitor.INSTANCE;
  871. final File pack, idx;
  872. try (PackWriter pw = new PackWriter(db)) {
  873. Set<ObjectId> all = new HashSet<>();
  874. for (Ref r : db.getRefDatabase().getRefs())
  875. all.add(r.getObjectId());
  876. pw.preparePack(m, all, PackWriter.NONE);
  877. final ObjectId name = pw.computeName();
  878. pack = nameFor(odb, name, ".pack");
  879. try (OutputStream out =
  880. new BufferedOutputStream(new FileOutputStream(pack))) {
  881. pw.writePack(m, m, out);
  882. }
  883. pack.setReadOnly();
  884. idx = nameFor(odb, name, ".idx");
  885. try (OutputStream out =
  886. new BufferedOutputStream(new FileOutputStream(idx))) {
  887. pw.writeIndex(out);
  888. }
  889. idx.setReadOnly();
  890. }
  891. odb.openPack(pack);
  892. updateServerInfo();
  893. prunePacked(odb);
  894. }
  895. }
  896. /**
  897. * Closes the underlying {@link Repository} object and any other internal
  898. * resources.
  899. * <p>
  900. * {@link AutoCloseable} resources that may escape this object, such as
  901. * those returned by the {@link #git} and {@link #getRevWalk()} methods are
  902. * not closed.
  903. */
  904. @Override
  905. public void close() {
  906. try {
  907. inserter.close();
  908. } finally {
  909. db.close();
  910. }
  911. }
  912. private static void prunePacked(ObjectDirectory odb) throws IOException {
  913. for (PackFile p : odb.getPacks()) {
  914. for (MutableEntry e : p)
  915. FileUtils.delete(odb.fileFor(e.toObjectId()));
  916. }
  917. }
  918. private static File nameFor(ObjectDirectory odb, ObjectId name, String t) {
  919. File packdir = odb.getPackDirectory();
  920. return new File(packdir, "pack-" + name.name() + t);
  921. }
  922. private void writeFile(File p, byte[] bin) throws IOException,
  923. ObjectWritingException {
  924. final LockFile lck = new LockFile(p);
  925. if (!lck.lock())
  926. throw new ObjectWritingException("Can't write " + p);
  927. try {
  928. lck.write(bin);
  929. } catch (IOException ioe) {
  930. throw new ObjectWritingException("Can't write " + p);
  931. }
  932. if (!lck.commit())
  933. throw new ObjectWritingException("Can't write " + p);
  934. }
  935. /** Helper to build a branch with one or more commits */
  936. public class BranchBuilder {
  937. private final String ref;
  938. BranchBuilder(String ref) {
  939. this.ref = ref;
  940. }
  941. /**
  942. * @return construct a new commit builder that updates this branch. If
  943. * the branch already exists, the commit builder will have its
  944. * first parent as the current commit and its tree will be
  945. * initialized to the current files.
  946. * @throws Exception
  947. * the commit builder can't read the current branch state
  948. */
  949. public CommitBuilder commit() throws Exception {
  950. return new CommitBuilder(this);
  951. }
  952. /**
  953. * Forcefully update this branch to a particular commit.
  954. *
  955. * @param to
  956. * the commit to update to.
  957. * @return {@code to}.
  958. * @throws Exception
  959. */
  960. public RevCommit update(CommitBuilder to) throws Exception {
  961. return update(to.create());
  962. }
  963. /**
  964. * Forcefully update this branch to a particular commit.
  965. *
  966. * @param to
  967. * the commit to update to.
  968. * @return {@code to}.
  969. * @throws Exception
  970. */
  971. public RevCommit update(RevCommit to) throws Exception {
  972. return TestRepository.this.update(ref, to);
  973. }
  974. /**
  975. * Delete this branch.
  976. * @throws Exception
  977. * @since 4.4
  978. */
  979. public void delete() throws Exception {
  980. TestRepository.this.delete(ref);
  981. }
  982. }
  983. /** Helper to generate a commit. */
  984. public class CommitBuilder {
  985. private final BranchBuilder branch;
  986. private final DirCache tree = DirCache.newInCore();
  987. private ObjectId topLevelTree;
  988. private final List<RevCommit> parents = new ArrayList<>(2);
  989. private int tick = 1;
  990. private String message = "";
  991. private RevCommit self;
  992. private PersonIdent author;
  993. private PersonIdent committer;
  994. private String changeId;
  995. private boolean updateCommitterTime;
  996. CommitBuilder() {
  997. branch = null;
  998. }
  999. CommitBuilder(BranchBuilder b) throws Exception {
  1000. branch = b;
  1001. Ref ref = db.exactRef(branch.ref);
  1002. if (ref != null && ref.getObjectId() != null)
  1003. parent(pool.parseCommit(ref.getObjectId()));
  1004. }
  1005. CommitBuilder(CommitBuilder prior) throws Exception {
  1006. branch = prior.branch;
  1007. DirCacheBuilder b = tree.builder();
  1008. for (int i = 0; i < prior.tree.getEntryCount(); i++)
  1009. b.add(prior.tree.getEntry(i));
  1010. b.finish();
  1011. parents.add(prior.create());
  1012. }
  1013. /**
  1014. * set parent commit
  1015. *
  1016. * @param p
  1017. * parent commit
  1018. * @return this commit builder
  1019. * @throws Exception
  1020. */
  1021. public CommitBuilder parent(RevCommit p) throws Exception {
  1022. if (parents.isEmpty()) {
  1023. DirCacheBuilder b = tree.builder();
  1024. parseBody(p);
  1025. b.addTree(new byte[0], DirCacheEntry.STAGE_0, pool
  1026. .getObjectReader(), p.getTree());
  1027. b.finish();
  1028. }
  1029. parents.add(p);
  1030. return this;
  1031. }
  1032. /**
  1033. * Get parent commits
  1034. *
  1035. * @return parent commits
  1036. */
  1037. public List<RevCommit> parents() {
  1038. return Collections.unmodifiableList(parents);
  1039. }
  1040. /**
  1041. * Remove parent commits
  1042. *
  1043. * @return this commit builder
  1044. */
  1045. public CommitBuilder noParents() {
  1046. parents.clear();
  1047. return this;
  1048. }
  1049. /**
  1050. * Remove files
  1051. *
  1052. * @return this commit builder
  1053. */
  1054. public CommitBuilder noFiles() {
  1055. tree.clear();
  1056. return this;
  1057. }
  1058. /**
  1059. * Set top level tree
  1060. *
  1061. * @param treeId
  1062. * the top level tree
  1063. * @return this commit builder
  1064. */
  1065. public CommitBuilder setTopLevelTree(ObjectId treeId) {
  1066. topLevelTree = treeId;
  1067. return this;
  1068. }
  1069. /**
  1070. * Add file with given content
  1071. *
  1072. * @param path
  1073. * path of the file
  1074. * @param content
  1075. * the file content
  1076. * @return this commit builder
  1077. * @throws Exception
  1078. */
  1079. public CommitBuilder add(String path, String content) throws Exception {
  1080. return add(path, blob(content));
  1081. }
  1082. /**
  1083. * Add file with given path and blob
  1084. *
  1085. * @param path
  1086. * path of the file
  1087. * @param id
  1088. * blob for this file
  1089. * @return this commit builder
  1090. * @throws Exception
  1091. */
  1092. public CommitBuilder add(String path, RevBlob id)
  1093. throws Exception {
  1094. return edit(new PathEdit(path) {
  1095. @Override
  1096. public void apply(DirCacheEntry ent) {
  1097. ent.setFileMode(FileMode.REGULAR_FILE);
  1098. ent.setObjectId(id);
  1099. }
  1100. });
  1101. }
  1102. /**
  1103. * Edit the index
  1104. *
  1105. * @param edit
  1106. * the index record update
  1107. * @return this commit builder
  1108. */
  1109. public CommitBuilder edit(PathEdit edit) {
  1110. DirCacheEditor e = tree.editor();
  1111. e.add(edit);
  1112. e.finish();
  1113. return this;
  1114. }
  1115. /**
  1116. * Remove a file
  1117. *
  1118. * @param path
  1119. * path of the file
  1120. * @return this commit builder
  1121. */
  1122. public CommitBuilder rm(String path) {
  1123. DirCacheEditor e = tree.editor();
  1124. e.add(new DeletePath(path));
  1125. e.add(new DeleteTree(path));
  1126. e.finish();
  1127. return this;
  1128. }
  1129. /**
  1130. * Set commit message
  1131. *
  1132. * @param m
  1133. * the message
  1134. * @return this commit builder
  1135. */
  1136. public CommitBuilder message(String m) {
  1137. message = m;
  1138. return this;
  1139. }
  1140. /**
  1141. * Get the commit message
  1142. *
  1143. * @return the commit message
  1144. */
  1145. public String message() {
  1146. return message;
  1147. }
  1148. /**
  1149. * Tick the clock
  1150. *
  1151. * @param secs
  1152. * number of seconds
  1153. * @return this commit builder
  1154. */
  1155. public CommitBuilder tick(int secs) {
  1156. tick = secs;
  1157. return this;
  1158. }
  1159. /**
  1160. * Set author and committer identity
  1161. *
  1162. * @param ident
  1163. * identity to set
  1164. * @return this commit builder
  1165. */
  1166. public CommitBuilder ident(PersonIdent ident) {
  1167. author = ident;
  1168. committer = ident;
  1169. return this;
  1170. }
  1171. /**
  1172. * Set the author identity
  1173. *
  1174. * @param a
  1175. * the author's identity
  1176. * @return this commit builder
  1177. */
  1178. public CommitBuilder author(PersonIdent a) {
  1179. author = a;
  1180. return this;
  1181. }
  1182. /**
  1183. * Get the author identity
  1184. *
  1185. * @return the author identity
  1186. */
  1187. public PersonIdent author() {
  1188. return author;
  1189. }
  1190. /**
  1191. * Set the committer identity
  1192. *
  1193. * @param c
  1194. * the committer identity
  1195. * @return this commit builder
  1196. */
  1197. public CommitBuilder committer(PersonIdent c) {
  1198. committer = c;
  1199. return this;
  1200. }
  1201. /**
  1202. * Get the committer identity
  1203. *
  1204. * @return the committer identity
  1205. */
  1206. public PersonIdent committer() {
  1207. return committer;
  1208. }
  1209. /**
  1210. * Insert changeId
  1211. *
  1212. * @return this commit builder
  1213. */
  1214. public CommitBuilder insertChangeId() {
  1215. changeId = "";
  1216. return this;
  1217. }
  1218. /**
  1219. * Insert given changeId
  1220. *
  1221. * @param c
  1222. * changeId
  1223. * @return this commit builder
  1224. */
  1225. public CommitBuilder insertChangeId(String c) {
  1226. // Validate, but store as a string so we can use "" as a sentinel.
  1227. ObjectId.fromString(c);
  1228. changeId = c;
  1229. return this;
  1230. }
  1231. /**
  1232. * Create the commit
  1233. *
  1234. * @return the new commit
  1235. * @throws Exception
  1236. * if creation failed
  1237. */
  1238. public RevCommit create() throws Exception {
  1239. if (self == null) {
  1240. TestRepository.this.tick(tick);
  1241. final org.eclipse.jgit.lib.CommitBuilder c;
  1242. c = new org.eclipse.jgit.lib.CommitBuilder();
  1243. c.setParentIds(parents);
  1244. setAuthorAndCommitter(c);
  1245. if (author != null)
  1246. c.setAuthor(author);
  1247. if (committer != null) {
  1248. if (updateCommitterTime)
  1249. committer = new PersonIdent(committer, getDate());
  1250. c.setCommitter(committer);
  1251. }
  1252. ObjectId commitId;
  1253. try (ObjectInserter ins = inserter) {
  1254. if (topLevelTree != null)
  1255. c.setTreeId(topLevelTree);
  1256. else
  1257. c.setTreeId(tree.writeTree(ins));
  1258. insertChangeId(c);
  1259. c.setMessage(message);
  1260. commitId = ins.insert(c);
  1261. ins.flush();
  1262. }
  1263. self = pool.parseCommit(commitId);
  1264. if (branch != null)
  1265. branch.update(self);
  1266. }
  1267. return self;
  1268. }
  1269. private void insertChangeId(org.eclipse.jgit.lib.CommitBuilder c) {
  1270. if (changeId == null)
  1271. return;
  1272. int idx = ChangeIdUtil.indexOfChangeId(message, "\n");
  1273. if (idx >= 0)
  1274. return;
  1275. ObjectId firstParentId = null;
  1276. if (!parents.isEmpty())
  1277. firstParentId = parents.get(0);
  1278. ObjectId cid;
  1279. if (changeId.isEmpty())
  1280. cid = ChangeIdUtil.computeChangeId(c.getTreeId(), firstParentId,
  1281. c.getAuthor(), c.getCommitter(), message);
  1282. else
  1283. cid = ObjectId.fromString(changeId);
  1284. message = ChangeIdUtil.insertId(message, cid);
  1285. if (cid != null)
  1286. message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
  1287. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
  1288. + cid.getName() + "\n"); //$NON-NLS-1$
  1289. }
  1290. /**
  1291. * Create child commit builder
  1292. *
  1293. * @return child commit builder
  1294. * @throws Exception
  1295. */
  1296. public CommitBuilder child() throws Exception {
  1297. return new CommitBuilder(this);
  1298. }
  1299. }
  1300. }