Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

CommitCommand.java 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. ru.setRefLogMessage("commit : "
  194. + revCommit.getShortMessage(), false);
  195. ru.setExpectedOldObjectId(headId);
  196. Result rc = ru.forceUpdate();
  197. switch (rc) {
  198. case NEW:
  199. case FORCED:
  200. case FAST_FORWARD: {
  201. setCallable(false);
  202. if (state == RepositoryState.MERGING_RESOLVED) {
  203. // Commit was successful. Now delete the files
  204. // used for merge commits
  205. repo.writeMergeCommitMsg(null);
  206. repo.writeMergeHeads(null);
  207. }
  208. return revCommit;
  209. }
  210. case REJECTED:
  211. case LOCK_FAILURE:
  212. throw new ConcurrentRefUpdateException(JGitText
  213. .get().couldNotLockHEAD, ru.getRef(), rc);
  214. default:
  215. throw new JGitInternalException(MessageFormat
  216. .format(JGitText.get().updatingRefFailed,
  217. Constants.HEAD,
  218. commitId.toString(), rc));
  219. }
  220. } finally {
  221. revWalk.release();
  222. }
  223. } finally {
  224. odi.release();
  225. }
  226. } finally {
  227. index.unlock();
  228. }
  229. } catch (UnmergedPathException e) {
  230. // since UnmergedPathException is a subclass of IOException
  231. // which should not be wrapped by a JGitInternalException we
  232. // have to catch and re-throw it here
  233. throw e;
  234. } catch (IOException e) {
  235. throw new JGitInternalException(
  236. JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
  237. }
  238. }
  239. private DirCache createTemporaryIndex(ObjectId headId, DirCache index)
  240. throws IOException {
  241. ObjectInserter inserter = null;
  242. // get DirCacheEditor to modify the index if required
  243. DirCacheEditor dcEditor = index.editor();
  244. // get DirCacheBuilder for newly created in-core index to build a
  245. // temporary index for this commit
  246. DirCache inCoreIndex = DirCache.newInCore();
  247. DirCacheBuilder dcBuilder = inCoreIndex.builder();
  248. onlyProcessed = new boolean[only.size()];
  249. boolean emptyCommit = true;
  250. TreeWalk treeWalk = new TreeWalk(repo);
  251. int dcIdx = treeWalk.addTree(new DirCacheIterator(index));
  252. int fIdx = treeWalk.addTree(new FileTreeIterator(repo));
  253. int hIdx = -1;
  254. if (headId != null)
  255. hIdx = treeWalk.addTree(new RevWalk(repo).parseTree(headId));
  256. treeWalk.setRecursive(true);
  257. while (treeWalk.next()) {
  258. String path = treeWalk.getPathString();
  259. // check if current entry's path matches a specified path
  260. int pos = lookupOnly(path);
  261. CanonicalTreeParser hTree = null;
  262. if (hIdx != -1)
  263. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  264. if (pos >= 0) {
  265. // include entry in commit
  266. DirCacheIterator dcTree = treeWalk.getTree(dcIdx,
  267. DirCacheIterator.class);
  268. FileTreeIterator fTree = treeWalk.getTree(fIdx,
  269. FileTreeIterator.class);
  270. // check if entry refers to a tracked file
  271. boolean tracked = dcTree != null || hTree != null;
  272. if (!tracked)
  273. break;
  274. if (fTree != null) {
  275. // create a new DirCacheEntry with data retrieved from disk
  276. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  277. long entryLength = fTree.getEntryLength();
  278. dcEntry.setLength(entryLength);
  279. dcEntry.setLastModified(fTree.getEntryLastModified());
  280. dcEntry.setFileMode(fTree.getEntryFileMode());
  281. boolean objectExists = (dcTree != null && fTree
  282. .idEqual(dcTree))
  283. || (hTree != null && fTree.idEqual(hTree));
  284. if (objectExists) {
  285. dcEntry.setObjectId(fTree.getEntryObjectId());
  286. } else {
  287. // insert object
  288. if (inserter == null)
  289. inserter = repo.newObjectInserter();
  290. InputStream inputStream = fTree.openEntryStream();
  291. try {
  292. dcEntry.setObjectId(inserter.insert(
  293. Constants.OBJ_BLOB, entryLength,
  294. inputStream));
  295. } finally {
  296. inputStream.close();
  297. }
  298. }
  299. // update index
  300. dcEditor.add(new PathEdit(path) {
  301. @Override
  302. public void apply(DirCacheEntry ent) {
  303. ent.copyMetaData(dcEntry);
  304. }
  305. });
  306. // add to temporary in-core index
  307. dcBuilder.add(dcEntry);
  308. if (emptyCommit && (hTree == null || !hTree.idEqual(fTree)))
  309. // this is a change
  310. emptyCommit = false;
  311. } else {
  312. // if no file exists on disk, remove entry from index and
  313. // don't add it to temporary in-core index
  314. dcEditor.add(new DeletePath(path));
  315. if (emptyCommit && hTree != null)
  316. // this is a change
  317. emptyCommit = false;
  318. }
  319. // keep track of processed path
  320. onlyProcessed[pos] = true;
  321. } else {
  322. // add entries from HEAD for all other paths
  323. if (hTree != null) {
  324. // create a new DirCacheEntry with data retrieved from HEAD
  325. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  326. dcEntry.setObjectId(hTree.getEntryObjectId());
  327. dcEntry.setFileMode(hTree.getEntryFileMode());
  328. // add to temporary in-core index
  329. dcBuilder.add(dcEntry);
  330. }
  331. }
  332. }
  333. // there must be no unprocessed paths left at this point; otherwise an
  334. // untracked or unknown path has been specified
  335. for (int i = 0; i < onlyProcessed.length; i++)
  336. if (!onlyProcessed[i])
  337. throw new JGitInternalException(MessageFormat.format(
  338. JGitText.get().entryNotFoundByPath, only.get(i)));
  339. // there must be at least one change
  340. if (emptyCommit)
  341. throw new JGitInternalException(JGitText.get().emptyCommit);
  342. // update index
  343. dcEditor.commit();
  344. // finish temporary in-core index used for this commit
  345. dcBuilder.finish();
  346. return inCoreIndex;
  347. }
  348. /**
  349. * Look an entry's path up in the list of paths specified by the --only/ -o
  350. * option
  351. *
  352. * In case the complete (file) path (e.g. "d1/d2/f1") cannot be found in
  353. * <code>only</code>, lookup is also tried with (parent) directory paths
  354. * (e.g. "d1/d2" and "d1").
  355. *
  356. * @param pathString
  357. * entry's path
  358. * @return the item's index in <code>only</code>; -1 if no item matches
  359. */
  360. private int lookupOnly(String pathString) {
  361. int i = 0;
  362. for (String o : only) {
  363. String p = pathString;
  364. while (true) {
  365. if (p.equals(o))
  366. return i;
  367. int l = p.lastIndexOf("/");
  368. if (l < 1)
  369. break;
  370. p = p.substring(0, l);
  371. }
  372. i++;
  373. }
  374. return -1;
  375. }
  376. /**
  377. * Sets default values for not explicitly specified options. Then validates
  378. * that all required data has been provided.
  379. *
  380. * @param state
  381. * the state of the repository we are working on
  382. *
  383. * @throws NoMessageException
  384. * if the commit message has not been specified
  385. */
  386. private void processOptions(RepositoryState state) throws NoMessageException {
  387. if (committer == null)
  388. committer = new PersonIdent(repo);
  389. if (author == null)
  390. author = committer;
  391. // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
  392. if (state == RepositoryState.MERGING_RESOLVED) {
  393. try {
  394. parents = repo.readMergeHeads();
  395. } catch (IOException e) {
  396. throw new JGitInternalException(MessageFormat.format(
  397. JGitText.get().exceptionOccuredDuringReadingOfGIT_DIR,
  398. Constants.MERGE_HEAD, e), e);
  399. }
  400. if (message == null) {
  401. try {
  402. message = repo.readMergeCommitMsg();
  403. } catch (IOException e) {
  404. throw new JGitInternalException(MessageFormat.format(
  405. JGitText.get().exceptionOccuredDuringReadingOfGIT_DIR,
  406. Constants.MERGE_MSG, e), e);
  407. }
  408. }
  409. }
  410. if (message == null)
  411. // as long as we don't suppport -C option we have to have
  412. // an explicit message
  413. throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
  414. }
  415. /**
  416. * @param message
  417. * the commit message used for the {@code commit}
  418. * @return {@code this}
  419. */
  420. public CommitCommand setMessage(String message) {
  421. checkCallable();
  422. this.message = message;
  423. return this;
  424. }
  425. /**
  426. * @return the commit message used for the <code>commit</code>
  427. */
  428. public String getMessage() {
  429. return message;
  430. }
  431. /**
  432. * Sets the committer for this {@code commit}. If no committer is explicitly
  433. * specified because this method is never called or called with {@code null}
  434. * value then the committer will be deduced from config info in repository,
  435. * with current time.
  436. *
  437. * @param committer
  438. * the committer used for the {@code commit}
  439. * @return {@code this}
  440. */
  441. public CommitCommand setCommitter(PersonIdent committer) {
  442. checkCallable();
  443. this.committer = committer;
  444. return this;
  445. }
  446. /**
  447. * Sets the committer for this {@code commit}. If no committer is explicitly
  448. * specified because this method is never called or called with {@code null}
  449. * value then the committer will be deduced from config info in repository,
  450. * with current time.
  451. *
  452. * @param name
  453. * the name of the committer used for the {@code commit}
  454. * @param email
  455. * the email of the committer used for the {@code commit}
  456. * @return {@code this}
  457. */
  458. public CommitCommand setCommitter(String name, String email) {
  459. checkCallable();
  460. return setCommitter(new PersonIdent(name, email));
  461. }
  462. /**
  463. * @return the committer used for the {@code commit}. If no committer was
  464. * specified {@code null} is returned and the default
  465. * {@link PersonIdent} of this repo is used during execution of the
  466. * command
  467. */
  468. public PersonIdent getCommitter() {
  469. return committer;
  470. }
  471. /**
  472. * Sets the author for this {@code commit}. If no author is explicitly
  473. * specified because this method is never called or called with {@code null}
  474. * value then the author will be set to the committer.
  475. *
  476. * @param author
  477. * the author used for the {@code commit}
  478. * @return {@code this}
  479. */
  480. public CommitCommand setAuthor(PersonIdent author) {
  481. checkCallable();
  482. this.author = author;
  483. return this;
  484. }
  485. /**
  486. * Sets the author for this {@code commit}. If no author is explicitly
  487. * specified because this method is never called or called with {@code null}
  488. * value then the author will be set to the committer.
  489. *
  490. * @param name
  491. * the name of the author used for the {@code commit}
  492. * @param email
  493. * the email of the author used for the {@code commit}
  494. * @return {@code this}
  495. */
  496. public CommitCommand setAuthor(String name, String email) {
  497. checkCallable();
  498. return setAuthor(new PersonIdent(name, email));
  499. }
  500. /**
  501. * @return the author used for the {@code commit}. If no author was
  502. * specified {@code null} is returned and the default
  503. * {@link PersonIdent} of this repo is used during execution of the
  504. * command
  505. */
  506. public PersonIdent getAuthor() {
  507. return author;
  508. }
  509. /**
  510. * If set to true the Commit command automatically stages files that have
  511. * been modified and deleted, but new files not known by the repository are
  512. * not affected. This corresponds to the parameter -a on the command line.
  513. *
  514. * @param all
  515. * @return {@code this}
  516. * @throws JGitInternalException
  517. * in case of an illegal combination of arguments/ options
  518. */
  519. public CommitCommand setAll(boolean all) {
  520. checkCallable();
  521. if (!only.isEmpty())
  522. throw new JGitInternalException(MessageFormat.format(
  523. JGitText.get().illegalCombinationOfArguments, "--all",
  524. "--only"));
  525. this.all = all;
  526. return this;
  527. }
  528. /**
  529. * Used to amend the tip of the current branch. If set to true, the previous
  530. * commit will be amended. This is equivalent to --amend on the command
  531. * line.
  532. *
  533. * @param amend
  534. * @return {@code this}
  535. */
  536. public CommitCommand setAmend(boolean amend) {
  537. checkCallable();
  538. this.amend = amend;
  539. return this;
  540. }
  541. /**
  542. * Commit dedicated path only
  543. *
  544. * This method can be called several times to add multiple paths. Full file
  545. * paths are supported as well as directory paths; in the latter case this
  546. * commits all files/ directories below the specified path.
  547. *
  548. * @param only
  549. * path to commit
  550. * @return {@code this}
  551. */
  552. public CommitCommand setOnly(String only) {
  553. checkCallable();
  554. if (all)
  555. throw new JGitInternalException(MessageFormat.format(
  556. JGitText.get().illegalCombinationOfArguments, "--only",
  557. "--all"));
  558. String o = only.endsWith("/") ? only.substring(0, only.length() - 1)
  559. : only;
  560. // ignore duplicates
  561. if (!this.only.contains(o))
  562. this.only.add(o);
  563. return this;
  564. }
  565. }