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.

CommitCommand.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. /*
  2. * Copyright (C) 2010, Christian Halstrick <christian.halstrick@sap.com>
  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.api;
  44. import java.io.IOException;
  45. import java.io.InputStream;
  46. import java.text.MessageFormat;
  47. import java.util.ArrayList;
  48. import java.util.LinkedList;
  49. import java.util.List;
  50. import org.eclipse.jgit.JGitText;
  51. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  52. import org.eclipse.jgit.api.errors.JGitInternalException;
  53. import org.eclipse.jgit.api.errors.NoFilepatternException;
  54. import org.eclipse.jgit.api.errors.NoHeadException;
  55. import org.eclipse.jgit.api.errors.NoMessageException;
  56. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  57. import org.eclipse.jgit.dircache.DirCache;
  58. import org.eclipse.jgit.dircache.DirCacheBuilder;
  59. import org.eclipse.jgit.dircache.DirCacheEditor;
  60. import org.eclipse.jgit.dircache.DirCacheEditor.DeletePath;
  61. import org.eclipse.jgit.dircache.DirCacheEditor.PathEdit;
  62. import org.eclipse.jgit.dircache.DirCacheEntry;
  63. import org.eclipse.jgit.dircache.DirCacheIterator;
  64. import org.eclipse.jgit.errors.UnmergedPathException;
  65. import org.eclipse.jgit.lib.CommitBuilder;
  66. import org.eclipse.jgit.lib.Constants;
  67. import org.eclipse.jgit.lib.ObjectId;
  68. import org.eclipse.jgit.lib.ObjectInserter;
  69. import org.eclipse.jgit.lib.PersonIdent;
  70. import org.eclipse.jgit.lib.Ref;
  71. import org.eclipse.jgit.lib.RefUpdate;
  72. import org.eclipse.jgit.lib.RefUpdate.Result;
  73. import org.eclipse.jgit.lib.Repository;
  74. import org.eclipse.jgit.lib.RepositoryState;
  75. import org.eclipse.jgit.revwalk.RevCommit;
  76. import org.eclipse.jgit.revwalk.RevWalk;
  77. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  78. import org.eclipse.jgit.treewalk.FileTreeIterator;
  79. import org.eclipse.jgit.treewalk.TreeWalk;
  80. /**
  81. * A class used to execute a {@code Commit} command. It has setters for all
  82. * supported options and arguments of this command and a {@link #call()} method
  83. * to finally execute the command.
  84. *
  85. * @see <a
  86. * href="http://www.kernel.org/pub/software/scm/git/docs/git-commit.html"
  87. * >Git documentation about Commit</a>
  88. */
  89. public class CommitCommand extends GitCommand<RevCommit> {
  90. private PersonIdent author;
  91. private PersonIdent committer;
  92. private String message;
  93. private boolean all;
  94. private List<String> only = new ArrayList<String>();
  95. private boolean[] onlyProcessed;
  96. private boolean amend;
  97. /**
  98. * parents this commit should have. The current HEAD will be in this list
  99. * and also all commits mentioned in .git/MERGE_HEAD
  100. */
  101. private List<ObjectId> parents = new LinkedList<ObjectId>();
  102. /**
  103. * @param repo
  104. */
  105. protected CommitCommand(Repository repo) {
  106. super(repo);
  107. }
  108. /**
  109. * Executes the {@code commit} command with all the options and parameters
  110. * collected by the setter methods of this class. Each instance of this
  111. * class should only be used for one invocation of the command (means: one
  112. * call to {@link #call()})
  113. *
  114. * @return a {@link RevCommit} object representing the successful commit.
  115. * @throws NoHeadException
  116. * when called on a git repo without a HEAD reference
  117. * @throws NoMessageException
  118. * when called without specifying a commit message
  119. * @throws UnmergedPathException
  120. * when the current index contained unmerged paths (conflicts)
  121. * @throws WrongRepositoryStateException
  122. * when repository is not in the right state for committing
  123. * @throws JGitInternalException
  124. * a low-level exception of JGit has occurred. The original
  125. * exception can be retrieved by calling
  126. * {@link Exception#getCause()}. Expect only
  127. * {@code IOException's} to be wrapped. Subclasses of
  128. * {@link IOException} (e.g. {@link UnmergedPathException}) are
  129. * typically not wrapped here but thrown as original exception
  130. */
  131. public RevCommit call() throws NoHeadException, NoMessageException,
  132. UnmergedPathException, ConcurrentRefUpdateException,
  133. JGitInternalException, WrongRepositoryStateException {
  134. checkCallable();
  135. RepositoryState state = repo.getRepositoryState();
  136. if (!state.canCommit())
  137. throw new WrongRepositoryStateException(MessageFormat.format(
  138. JGitText.get().cannotCommitOnARepoWithState, state.name()));
  139. processOptions(state);
  140. try {
  141. if (all && !repo.isBare() && repo.getWorkTree() != null) {
  142. Git git = new Git(repo);
  143. try {
  144. git.add()
  145. .addFilepattern(".")
  146. .setUpdate(true).call();
  147. } catch (NoFilepatternException e) {
  148. // should really not happen
  149. throw new JGitInternalException(e.getMessage(), e);
  150. }
  151. }
  152. Ref head = repo.getRef(Constants.HEAD);
  153. if (head == null)
  154. throw new NoHeadException(
  155. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  156. // determine the current HEAD and the commit it is referring to
  157. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}");
  158. if (headId != null)
  159. if (amend) {
  160. RevCommit previousCommit = new RevWalk(repo)
  161. .parseCommit(headId);
  162. RevCommit[] p = previousCommit.getParents();
  163. for (int i = 0; i < p.length; i++)
  164. parents.add(0, p[i].getId());
  165. } else {
  166. parents.add(0, headId);
  167. }
  168. // lock the index
  169. DirCache index = repo.lockDirCache();
  170. try {
  171. if (!only.isEmpty())
  172. index = createTemporaryIndex(headId, index);
  173. ObjectInserter odi = repo.newObjectInserter();
  174. try {
  175. // Write the index as tree to the object database. This may
  176. // fail for example when the index contains unmerged paths
  177. // (unresolved conflicts)
  178. ObjectId indexTreeId = index.writeTree(odi);
  179. // Create a Commit object, populate it and write it
  180. CommitBuilder commit = new CommitBuilder();
  181. commit.setCommitter(committer);
  182. commit.setAuthor(author);
  183. commit.setMessage(message);
  184. commit.setParentIds(parents);
  185. commit.setTreeId(indexTreeId);
  186. ObjectId commitId = odi.insert(commit);
  187. odi.flush();
  188. RevWalk revWalk = new RevWalk(repo);
  189. try {
  190. RevCommit revCommit = revWalk.parseCommit(commitId);
  191. RefUpdate ru = repo.updateRef(Constants.HEAD);
  192. ru.setNewObjectId(commitId);
  193. String prefix = amend ? "commit (amend): " : "commit: ";
  194. ru.setRefLogMessage(
  195. prefix + revCommit.getShortMessage(), false);
  196. ru.setExpectedOldObjectId(headId);
  197. Result rc = ru.forceUpdate();
  198. switch (rc) {
  199. case NEW:
  200. case FORCED:
  201. case FAST_FORWARD: {
  202. setCallable(false);
  203. if (state == RepositoryState.MERGING_RESOLVED) {
  204. // Commit was successful. Now delete the files
  205. // used for merge commits
  206. repo.writeMergeCommitMsg(null);
  207. repo.writeMergeHeads(null);
  208. }
  209. return revCommit;
  210. }
  211. case REJECTED:
  212. case LOCK_FAILURE:
  213. throw new ConcurrentRefUpdateException(JGitText
  214. .get().couldNotLockHEAD, ru.getRef(), rc);
  215. default:
  216. throw new JGitInternalException(MessageFormat
  217. .format(JGitText.get().updatingRefFailed,
  218. Constants.HEAD,
  219. commitId.toString(), rc));
  220. }
  221. } finally {
  222. revWalk.release();
  223. }
  224. } finally {
  225. odi.release();
  226. }
  227. } finally {
  228. index.unlock();
  229. }
  230. } catch (UnmergedPathException e) {
  231. // since UnmergedPathException is a subclass of IOException
  232. // which should not be wrapped by a JGitInternalException we
  233. // have to catch and re-throw it here
  234. throw e;
  235. } catch (IOException e) {
  236. throw new JGitInternalException(
  237. JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
  238. }
  239. }
  240. private DirCache createTemporaryIndex(ObjectId headId, DirCache index)
  241. throws IOException {
  242. ObjectInserter inserter = null;
  243. // get DirCacheEditor to modify the index if required
  244. DirCacheEditor dcEditor = index.editor();
  245. // get DirCacheBuilder for newly created in-core index to build a
  246. // temporary index for this commit
  247. DirCache inCoreIndex = DirCache.newInCore();
  248. DirCacheBuilder dcBuilder = inCoreIndex.builder();
  249. onlyProcessed = new boolean[only.size()];
  250. boolean emptyCommit = true;
  251. TreeWalk treeWalk = new TreeWalk(repo);
  252. int dcIdx = treeWalk.addTree(new DirCacheIterator(index));
  253. int fIdx = treeWalk.addTree(new FileTreeIterator(repo));
  254. int hIdx = -1;
  255. if (headId != null)
  256. hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
  257. treeWalk.setRecursive(true);
  258. while (treeWalk.next()) {
  259. String path = treeWalk.getPathString();
  260. // check if current entry's path matches a specified path
  261. int pos = lookupOnly(path);
  262. CanonicalTreeParser hTree = null;
  263. if (hIdx != -1)
  264. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  265. if (pos >= 0) {
  266. // include entry in commit
  267. DirCacheIterator dcTree = treeWalk.getTree(dcIdx,
  268. DirCacheIterator.class);
  269. FileTreeIterator fTree = treeWalk.getTree(fIdx,
  270. FileTreeIterator.class);
  271. // check if entry refers to a tracked file
  272. boolean tracked = dcTree != null || hTree != null;
  273. if (!tracked)
  274. break;
  275. if (fTree != null) {
  276. // create a new DirCacheEntry with data retrieved from disk
  277. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  278. long entryLength = fTree.getEntryLength();
  279. dcEntry.setLength(entryLength);
  280. dcEntry.setLastModified(fTree.getEntryLastModified());
  281. dcEntry.setFileMode(fTree.getEntryFileMode());
  282. boolean objectExists = (dcTree != null && fTree
  283. .idEqual(dcTree))
  284. || (hTree != null && fTree.idEqual(hTree));
  285. if (objectExists) {
  286. dcEntry.setObjectId(fTree.getEntryObjectId());
  287. } else {
  288. // insert object
  289. if (inserter == null)
  290. inserter = repo.newObjectInserter();
  291. InputStream inputStream = fTree.openEntryStream();
  292. try {
  293. dcEntry.setObjectId(inserter.insert(
  294. Constants.OBJ_BLOB, entryLength,
  295. inputStream));
  296. } finally {
  297. inputStream.close();
  298. }
  299. }
  300. // update index
  301. dcEditor.add(new PathEdit(path) {
  302. @Override
  303. public void apply(DirCacheEntry ent) {
  304. ent.copyMetaData(dcEntry);
  305. }
  306. });
  307. // add to temporary in-core index
  308. dcBuilder.add(dcEntry);
  309. if (emptyCommit && (hTree == null || !hTree.idEqual(fTree)))
  310. // this is a change
  311. emptyCommit = false;
  312. } else {
  313. // if no file exists on disk, remove entry from index and
  314. // don't add it to temporary in-core index
  315. dcEditor.add(new DeletePath(path));
  316. if (emptyCommit && hTree != null)
  317. // this is a change
  318. emptyCommit = false;
  319. }
  320. // keep track of processed path
  321. onlyProcessed[pos] = true;
  322. } else {
  323. // add entries from HEAD for all other paths
  324. if (hTree != null) {
  325. // create a new DirCacheEntry with data retrieved from HEAD
  326. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  327. dcEntry.setObjectId(hTree.getEntryObjectId());
  328. dcEntry.setFileMode(hTree.getEntryFileMode());
  329. // add to temporary in-core index
  330. dcBuilder.add(dcEntry);
  331. }
  332. }
  333. }
  334. // there must be no unprocessed paths left at this point; otherwise an
  335. // untracked or unknown path has been specified
  336. for (int i = 0; i < onlyProcessed.length; i++)
  337. if (!onlyProcessed[i])
  338. throw new JGitInternalException(MessageFormat.format(
  339. JGitText.get().entryNotFoundByPath, only.get(i)));
  340. // there must be at least one change
  341. if (emptyCommit)
  342. throw new JGitInternalException(JGitText.get().emptyCommit);
  343. // update index
  344. dcEditor.commit();
  345. // finish temporary in-core index used for this commit
  346. dcBuilder.finish();
  347. return inCoreIndex;
  348. }
  349. /**
  350. * Look an entry's path up in the list of paths specified by the --only/ -o
  351. * option
  352. *
  353. * In case the complete (file) path (e.g. "d1/d2/f1") cannot be found in
  354. * <code>only</code>, lookup is also tried with (parent) directory paths
  355. * (e.g. "d1/d2" and "d1").
  356. *
  357. * @param pathString
  358. * entry's path
  359. * @return the item's index in <code>only</code>; -1 if no item matches
  360. */
  361. private int lookupOnly(String pathString) {
  362. int i = 0;
  363. for (String o : only) {
  364. String p = pathString;
  365. while (true) {
  366. if (p.equals(o))
  367. return i;
  368. int l = p.lastIndexOf("/");
  369. if (l < 1)
  370. break;
  371. p = p.substring(0, l);
  372. }
  373. i++;
  374. }
  375. return -1;
  376. }
  377. /**
  378. * Sets default values for not explicitly specified options. Then validates
  379. * that all required data has been provided.
  380. *
  381. * @param state
  382. * the state of the repository we are working on
  383. *
  384. * @throws NoMessageException
  385. * if the commit message has not been specified
  386. */
  387. private void processOptions(RepositoryState state) throws NoMessageException {
  388. if (committer == null)
  389. committer = new PersonIdent(repo);
  390. if (author == null)
  391. author = committer;
  392. // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
  393. if (state == RepositoryState.MERGING_RESOLVED) {
  394. try {
  395. parents = repo.readMergeHeads();
  396. } catch (IOException e) {
  397. throw new JGitInternalException(MessageFormat.format(
  398. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  399. Constants.MERGE_HEAD, e), e);
  400. }
  401. if (message == null) {
  402. try {
  403. message = repo.readMergeCommitMsg();
  404. } catch (IOException e) {
  405. throw new JGitInternalException(MessageFormat.format(
  406. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  407. Constants.MERGE_MSG, e), e);
  408. }
  409. }
  410. }
  411. if (message == null)
  412. // as long as we don't suppport -C option we have to have
  413. // an explicit message
  414. throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
  415. }
  416. /**
  417. * @param message
  418. * the commit message used for the {@code commit}
  419. * @return {@code this}
  420. */
  421. public CommitCommand setMessage(String message) {
  422. checkCallable();
  423. this.message = message;
  424. return this;
  425. }
  426. /**
  427. * @return the commit message used for the <code>commit</code>
  428. */
  429. public String getMessage() {
  430. return message;
  431. }
  432. /**
  433. * Sets the committer for this {@code commit}. If no committer is explicitly
  434. * specified because this method is never called or called with {@code null}
  435. * value then the committer will be deduced from config info in repository,
  436. * with current time.
  437. *
  438. * @param committer
  439. * the committer used for the {@code commit}
  440. * @return {@code this}
  441. */
  442. public CommitCommand setCommitter(PersonIdent committer) {
  443. checkCallable();
  444. this.committer = committer;
  445. return this;
  446. }
  447. /**
  448. * Sets the committer for this {@code commit}. If no committer is explicitly
  449. * specified because this method is never called or called with {@code null}
  450. * value then the committer will be deduced from config info in repository,
  451. * with current time.
  452. *
  453. * @param name
  454. * the name of the committer used for the {@code commit}
  455. * @param email
  456. * the email of the committer used for the {@code commit}
  457. * @return {@code this}
  458. */
  459. public CommitCommand setCommitter(String name, String email) {
  460. checkCallable();
  461. return setCommitter(new PersonIdent(name, email));
  462. }
  463. /**
  464. * @return the committer used for the {@code commit}. If no committer was
  465. * specified {@code null} is returned and the default
  466. * {@link PersonIdent} of this repo is used during execution of the
  467. * command
  468. */
  469. public PersonIdent getCommitter() {
  470. return committer;
  471. }
  472. /**
  473. * Sets the author for this {@code commit}. If no author is explicitly
  474. * specified because this method is never called or called with {@code null}
  475. * value then the author will be set to the committer.
  476. *
  477. * @param author
  478. * the author used for the {@code commit}
  479. * @return {@code this}
  480. */
  481. public CommitCommand setAuthor(PersonIdent author) {
  482. checkCallable();
  483. this.author = author;
  484. return this;
  485. }
  486. /**
  487. * Sets the author for this {@code commit}. If no author is explicitly
  488. * specified because this method is never called or called with {@code null}
  489. * value then the author will be set to the committer.
  490. *
  491. * @param name
  492. * the name of the author used for the {@code commit}
  493. * @param email
  494. * the email of the author used for the {@code commit}
  495. * @return {@code this}
  496. */
  497. public CommitCommand setAuthor(String name, String email) {
  498. checkCallable();
  499. return setAuthor(new PersonIdent(name, email));
  500. }
  501. /**
  502. * @return the author used for the {@code commit}. If no author was
  503. * specified {@code null} is returned and the default
  504. * {@link PersonIdent} of this repo is used during execution of the
  505. * command
  506. */
  507. public PersonIdent getAuthor() {
  508. return author;
  509. }
  510. /**
  511. * If set to true the Commit command automatically stages files that have
  512. * been modified and deleted, but new files not known by the repository are
  513. * not affected. This corresponds to the parameter -a on the command line.
  514. *
  515. * @param all
  516. * @return {@code this}
  517. * @throws JGitInternalException
  518. * in case of an illegal combination of arguments/ options
  519. */
  520. public CommitCommand setAll(boolean all) {
  521. checkCallable();
  522. if (!only.isEmpty())
  523. throw new JGitInternalException(MessageFormat.format(
  524. JGitText.get().illegalCombinationOfArguments, "--all",
  525. "--only"));
  526. this.all = all;
  527. return this;
  528. }
  529. /**
  530. * Used to amend the tip of the current branch. If set to true, the previous
  531. * commit will be amended. This is equivalent to --amend on the command
  532. * line.
  533. *
  534. * @param amend
  535. * @return {@code this}
  536. */
  537. public CommitCommand setAmend(boolean amend) {
  538. checkCallable();
  539. this.amend = amend;
  540. return this;
  541. }
  542. /**
  543. * Commit dedicated path only
  544. *
  545. * This method can be called several times to add multiple paths. Full file
  546. * paths are supported as well as directory paths; in the latter case this
  547. * commits all files/ directories below the specified path.
  548. *
  549. * @param only
  550. * path to commit
  551. * @return {@code this}
  552. */
  553. public CommitCommand setOnly(String only) {
  554. checkCallable();
  555. if (all)
  556. throw new JGitInternalException(MessageFormat.format(
  557. JGitText.get().illegalCombinationOfArguments, "--only",
  558. "--all"));
  559. String o = only.endsWith("/") ? only.substring(0, only.length() - 1)
  560. : only;
  561. // ignore duplicates
  562. if (!this.only.contains(o))
  563. this.only.add(o);
  564. return this;
  565. }
  566. }