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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. /*
  2. * Copyright (C) 2010-2012, 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.io.PrintStream;
  47. import java.text.MessageFormat;
  48. import java.util.ArrayList;
  49. import java.util.Collections;
  50. import java.util.HashMap;
  51. import java.util.LinkedList;
  52. import java.util.List;
  53. import org.eclipse.jgit.api.errors.AbortedByHookException;
  54. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  55. import org.eclipse.jgit.api.errors.EmptyCommitException;
  56. import org.eclipse.jgit.api.errors.GitAPIException;
  57. import org.eclipse.jgit.api.errors.JGitInternalException;
  58. import org.eclipse.jgit.api.errors.NoFilepatternException;
  59. import org.eclipse.jgit.api.errors.NoHeadException;
  60. import org.eclipse.jgit.api.errors.NoMessageException;
  61. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  62. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  63. import org.eclipse.jgit.dircache.DirCache;
  64. import org.eclipse.jgit.dircache.DirCacheBuildIterator;
  65. import org.eclipse.jgit.dircache.DirCacheBuilder;
  66. import org.eclipse.jgit.dircache.DirCacheEntry;
  67. import org.eclipse.jgit.dircache.DirCacheIterator;
  68. import org.eclipse.jgit.errors.UnmergedPathException;
  69. import org.eclipse.jgit.hooks.CommitMsgHook;
  70. import org.eclipse.jgit.hooks.Hooks;
  71. import org.eclipse.jgit.hooks.PostCommitHook;
  72. import org.eclipse.jgit.hooks.PreCommitHook;
  73. import org.eclipse.jgit.internal.JGitText;
  74. import org.eclipse.jgit.lib.CommitBuilder;
  75. import org.eclipse.jgit.lib.Constants;
  76. import org.eclipse.jgit.lib.FileMode;
  77. import org.eclipse.jgit.lib.ObjectId;
  78. import org.eclipse.jgit.lib.ObjectInserter;
  79. import org.eclipse.jgit.lib.PersonIdent;
  80. import org.eclipse.jgit.lib.Ref;
  81. import org.eclipse.jgit.lib.RefUpdate;
  82. import org.eclipse.jgit.lib.RefUpdate.Result;
  83. import org.eclipse.jgit.lib.Repository;
  84. import org.eclipse.jgit.lib.RepositoryState;
  85. import org.eclipse.jgit.revwalk.RevCommit;
  86. import org.eclipse.jgit.revwalk.RevObject;
  87. import org.eclipse.jgit.revwalk.RevTag;
  88. import org.eclipse.jgit.revwalk.RevWalk;
  89. import org.eclipse.jgit.treewalk.CanonicalTreeParser;
  90. import org.eclipse.jgit.treewalk.FileTreeIterator;
  91. import org.eclipse.jgit.treewalk.TreeWalk;
  92. import org.eclipse.jgit.treewalk.TreeWalk.OperationType;
  93. import org.eclipse.jgit.util.ChangeIdUtil;
  94. /**
  95. * A class used to execute a {@code Commit} command. It has setters for all
  96. * supported options and arguments of this command and a {@link #call()} method
  97. * to finally execute the command.
  98. *
  99. * @see <a
  100. * href="http://www.kernel.org/pub/software/scm/git/docs/git-commit.html"
  101. * >Git documentation about Commit</a>
  102. */
  103. public class CommitCommand extends GitCommand<RevCommit> {
  104. private PersonIdent author;
  105. private PersonIdent committer;
  106. private String message;
  107. private boolean all;
  108. private List<String> only = new ArrayList<>();
  109. private boolean[] onlyProcessed;
  110. private boolean amend;
  111. private boolean insertChangeId;
  112. /**
  113. * parents this commit should have. The current HEAD will be in this list
  114. * and also all commits mentioned in .git/MERGE_HEAD
  115. */
  116. private List<ObjectId> parents = new LinkedList<>();
  117. private String reflogComment;
  118. private boolean useDefaultReflogMessage = true;
  119. /**
  120. * Setting this option bypasses the pre-commit and commit-msg hooks.
  121. */
  122. private boolean noVerify;
  123. private HashMap<String, PrintStream> hookOutRedirect = new HashMap<>(3);
  124. private Boolean allowEmpty;
  125. /**
  126. * Constructor for CommitCommand
  127. *
  128. * @param repo
  129. * the {@link org.eclipse.jgit.lib.Repository}
  130. */
  131. protected CommitCommand(Repository repo) {
  132. super(repo);
  133. }
  134. /**
  135. * {@inheritDoc}
  136. * <p>
  137. * Executes the {@code commit} command with all the options and parameters
  138. * collected by the setter methods of this class. Each instance of this
  139. * class should only be used for one invocation of the command (means: one
  140. * call to {@link #call()})
  141. */
  142. @Override
  143. public RevCommit call() throws GitAPIException, NoHeadException,
  144. NoMessageException, UnmergedPathsException,
  145. ConcurrentRefUpdateException, WrongRepositoryStateException,
  146. AbortedByHookException {
  147. checkCallable();
  148. Collections.sort(only);
  149. try (RevWalk rw = new RevWalk(repo)) {
  150. RepositoryState state = repo.getRepositoryState();
  151. if (!state.canCommit())
  152. throw new WrongRepositoryStateException(MessageFormat.format(
  153. JGitText.get().cannotCommitOnARepoWithState,
  154. state.name()));
  155. if (!noVerify) {
  156. Hooks.preCommit(repo, hookOutRedirect.get(PreCommitHook.NAME))
  157. .call();
  158. }
  159. processOptions(state, rw);
  160. if (all && !repo.isBare()) {
  161. try (Git git = new Git(repo)) {
  162. git.add()
  163. .addFilepattern(".") //$NON-NLS-1$
  164. .setUpdate(true).call();
  165. } catch (NoFilepatternException e) {
  166. // should really not happen
  167. throw new JGitInternalException(e.getMessage(), e);
  168. }
  169. }
  170. Ref head = repo.exactRef(Constants.HEAD);
  171. if (head == null)
  172. throw new NoHeadException(
  173. JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported);
  174. // determine the current HEAD and the commit it is referring to
  175. ObjectId headId = repo.resolve(Constants.HEAD + "^{commit}"); //$NON-NLS-1$
  176. if (headId == null && amend)
  177. throw new WrongRepositoryStateException(
  178. JGitText.get().commitAmendOnInitialNotPossible);
  179. if (headId != null)
  180. if (amend) {
  181. RevCommit previousCommit = rw.parseCommit(headId);
  182. for (RevCommit p : previousCommit.getParents())
  183. parents.add(p.getId());
  184. if (author == null)
  185. author = previousCommit.getAuthorIdent();
  186. } else {
  187. parents.add(0, headId);
  188. }
  189. if (!noVerify) {
  190. message = Hooks
  191. .commitMsg(repo,
  192. hookOutRedirect.get(CommitMsgHook.NAME))
  193. .setCommitMessage(message).call();
  194. }
  195. // lock the index
  196. DirCache index = repo.lockDirCache();
  197. try (ObjectInserter odi = repo.newObjectInserter()) {
  198. if (!only.isEmpty())
  199. index = createTemporaryIndex(headId, index, rw);
  200. // Write the index as tree to the object database. This may
  201. // fail for example when the index contains unmerged paths
  202. // (unresolved conflicts)
  203. ObjectId indexTreeId = index.writeTree(odi);
  204. if (insertChangeId)
  205. insertChangeId(indexTreeId);
  206. // Check for empty commits
  207. if (headId != null && !allowEmpty.booleanValue()) {
  208. RevCommit headCommit = rw.parseCommit(headId);
  209. headCommit.getTree();
  210. if (indexTreeId.equals(headCommit.getTree())) {
  211. throw new EmptyCommitException(
  212. JGitText.get().emptyCommit);
  213. }
  214. }
  215. // Create a Commit object, populate it and write it
  216. CommitBuilder commit = new CommitBuilder();
  217. commit.setCommitter(committer);
  218. commit.setAuthor(author);
  219. commit.setMessage(message);
  220. commit.setParentIds(parents);
  221. commit.setTreeId(indexTreeId);
  222. ObjectId commitId = odi.insert(commit);
  223. odi.flush();
  224. RevCommit revCommit = rw.parseCommit(commitId);
  225. RefUpdate ru = repo.updateRef(Constants.HEAD);
  226. ru.setNewObjectId(commitId);
  227. if (!useDefaultReflogMessage) {
  228. ru.setRefLogMessage(reflogComment, false);
  229. } else {
  230. String prefix = amend ? "commit (amend): " //$NON-NLS-1$
  231. : parents.size() == 0 ? "commit (initial): " //$NON-NLS-1$
  232. : "commit: "; //$NON-NLS-1$
  233. ru.setRefLogMessage(prefix + revCommit.getShortMessage(),
  234. false);
  235. }
  236. if (headId != null)
  237. ru.setExpectedOldObjectId(headId);
  238. else
  239. ru.setExpectedOldObjectId(ObjectId.zeroId());
  240. Result rc = ru.forceUpdate();
  241. switch (rc) {
  242. case NEW:
  243. case FORCED:
  244. case FAST_FORWARD: {
  245. setCallable(false);
  246. if (state == RepositoryState.MERGING_RESOLVED
  247. || isMergeDuringRebase(state)) {
  248. // Commit was successful. Now delete the files
  249. // used for merge commits
  250. repo.writeMergeCommitMsg(null);
  251. repo.writeMergeHeads(null);
  252. } else if (state == RepositoryState.CHERRY_PICKING_RESOLVED) {
  253. repo.writeMergeCommitMsg(null);
  254. repo.writeCherryPickHead(null);
  255. } else if (state == RepositoryState.REVERTING_RESOLVED) {
  256. repo.writeMergeCommitMsg(null);
  257. repo.writeRevertHead(null);
  258. }
  259. Hooks.postCommit(repo,
  260. hookOutRedirect.get(PostCommitHook.NAME)).call();
  261. return revCommit;
  262. }
  263. case REJECTED:
  264. case LOCK_FAILURE:
  265. throw new ConcurrentRefUpdateException(
  266. JGitText.get().couldNotLockHEAD, ru.getRef(), rc);
  267. default:
  268. throw new JGitInternalException(MessageFormat.format(
  269. JGitText.get().updatingRefFailed, Constants.HEAD,
  270. commitId.toString(), rc));
  271. }
  272. } finally {
  273. index.unlock();
  274. }
  275. } catch (UnmergedPathException e) {
  276. throw new UnmergedPathsException(e);
  277. } catch (IOException e) {
  278. throw new JGitInternalException(
  279. JGitText.get().exceptionCaughtDuringExecutionOfCommitCommand, e);
  280. }
  281. }
  282. private void insertChangeId(ObjectId treeId) {
  283. ObjectId firstParentId = null;
  284. if (!parents.isEmpty())
  285. firstParentId = parents.get(0);
  286. ObjectId changeId = ChangeIdUtil.computeChangeId(treeId, firstParentId,
  287. author, committer, message);
  288. message = ChangeIdUtil.insertId(message, changeId);
  289. if (changeId != null)
  290. message = message.replaceAll("\nChange-Id: I" //$NON-NLS-1$
  291. + ObjectId.zeroId().getName() + "\n", "\nChange-Id: I" //$NON-NLS-1$ //$NON-NLS-2$
  292. + changeId.getName() + "\n"); //$NON-NLS-1$
  293. }
  294. private DirCache createTemporaryIndex(ObjectId headId, DirCache index,
  295. RevWalk rw)
  296. throws IOException {
  297. ObjectInserter inserter = null;
  298. // get DirCacheBuilder for existing index
  299. DirCacheBuilder existingBuilder = index.builder();
  300. // get DirCacheBuilder for newly created in-core index to build a
  301. // temporary index for this commit
  302. DirCache inCoreIndex = DirCache.newInCore();
  303. DirCacheBuilder tempBuilder = inCoreIndex.builder();
  304. onlyProcessed = new boolean[only.size()];
  305. boolean emptyCommit = true;
  306. try (TreeWalk treeWalk = new TreeWalk(repo)) {
  307. treeWalk.setOperationType(OperationType.CHECKIN_OP);
  308. int dcIdx = treeWalk
  309. .addTree(new DirCacheBuildIterator(existingBuilder));
  310. FileTreeIterator fti = new FileTreeIterator(repo);
  311. fti.setDirCacheIterator(treeWalk, 0);
  312. int fIdx = treeWalk.addTree(fti);
  313. int hIdx = -1;
  314. if (headId != null)
  315. hIdx = treeWalk.addTree(rw.parseTree(headId));
  316. treeWalk.setRecursive(true);
  317. String lastAddedFile = null;
  318. while (treeWalk.next()) {
  319. String path = treeWalk.getPathString();
  320. // check if current entry's path matches a specified path
  321. int pos = lookupOnly(path);
  322. CanonicalTreeParser hTree = null;
  323. if (hIdx != -1)
  324. hTree = treeWalk.getTree(hIdx, CanonicalTreeParser.class);
  325. DirCacheIterator dcTree = treeWalk.getTree(dcIdx,
  326. DirCacheIterator.class);
  327. if (pos >= 0) {
  328. // include entry in commit
  329. FileTreeIterator fTree = treeWalk.getTree(fIdx,
  330. FileTreeIterator.class);
  331. // check if entry refers to a tracked file
  332. boolean tracked = dcTree != null || hTree != null;
  333. if (!tracked)
  334. continue;
  335. // for an unmerged path, DirCacheBuildIterator will yield 3
  336. // entries, we only want to add one
  337. if (path.equals(lastAddedFile))
  338. continue;
  339. lastAddedFile = path;
  340. if (fTree != null) {
  341. // create a new DirCacheEntry with data retrieved from
  342. // disk
  343. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  344. long entryLength = fTree.getEntryLength();
  345. dcEntry.setLength(entryLength);
  346. dcEntry.setLastModified(fTree.getEntryLastModifiedInstant());
  347. dcEntry.setFileMode(fTree.getIndexFileMode(dcTree));
  348. boolean objectExists = (dcTree != null
  349. && fTree.idEqual(dcTree))
  350. || (hTree != null && fTree.idEqual(hTree));
  351. if (objectExists) {
  352. dcEntry.setObjectId(fTree.getEntryObjectId());
  353. } else {
  354. if (FileMode.GITLINK.equals(dcEntry.getFileMode()))
  355. dcEntry.setObjectId(fTree.getEntryObjectId());
  356. else {
  357. // insert object
  358. if (inserter == null)
  359. inserter = repo.newObjectInserter();
  360. long contentLength = fTree
  361. .getEntryContentLength();
  362. try (InputStream inputStream = fTree
  363. .openEntryStream()) {
  364. dcEntry.setObjectId(inserter.insert(
  365. Constants.OBJ_BLOB, contentLength,
  366. inputStream));
  367. }
  368. }
  369. }
  370. // add to existing index
  371. existingBuilder.add(dcEntry);
  372. // add to temporary in-core index
  373. tempBuilder.add(dcEntry);
  374. if (emptyCommit
  375. && (hTree == null || !hTree.idEqual(fTree)
  376. || hTree.getEntryRawMode() != fTree
  377. .getEntryRawMode()))
  378. // this is a change
  379. emptyCommit = false;
  380. } else {
  381. // if no file exists on disk, neither add it to
  382. // index nor to temporary in-core index
  383. if (emptyCommit && hTree != null)
  384. // this is a change
  385. emptyCommit = false;
  386. }
  387. // keep track of processed path
  388. onlyProcessed[pos] = true;
  389. } else {
  390. // add entries from HEAD for all other paths
  391. if (hTree != null) {
  392. // create a new DirCacheEntry with data retrieved from
  393. // HEAD
  394. final DirCacheEntry dcEntry = new DirCacheEntry(path);
  395. dcEntry.setObjectId(hTree.getEntryObjectId());
  396. dcEntry.setFileMode(hTree.getEntryFileMode());
  397. // add to temporary in-core index
  398. tempBuilder.add(dcEntry);
  399. }
  400. // preserve existing entry in index
  401. if (dcTree != null)
  402. existingBuilder.add(dcTree.getDirCacheEntry());
  403. }
  404. }
  405. }
  406. // there must be no unprocessed paths left at this point; otherwise an
  407. // untracked or unknown path has been specified
  408. for (int i = 0; i < onlyProcessed.length; i++)
  409. if (!onlyProcessed[i])
  410. throw new JGitInternalException(MessageFormat.format(
  411. JGitText.get().entryNotFoundByPath, only.get(i)));
  412. // there must be at least one change
  413. if (emptyCommit && !allowEmpty.booleanValue())
  414. // Would like to throw a EmptyCommitException. But this would break the API
  415. // TODO(ch): Change this in the next release
  416. throw new JGitInternalException(JGitText.get().emptyCommit);
  417. // update index
  418. existingBuilder.commit();
  419. // finish temporary in-core index used for this commit
  420. tempBuilder.finish();
  421. return inCoreIndex;
  422. }
  423. /**
  424. * Look an entry's path up in the list of paths specified by the --only/ -o
  425. * option
  426. *
  427. * In case the complete (file) path (e.g. "d1/d2/f1") cannot be found in
  428. * <code>only</code>, lookup is also tried with (parent) directory paths
  429. * (e.g. "d1/d2" and "d1").
  430. *
  431. * @param pathString
  432. * entry's path
  433. * @return the item's index in <code>only</code>; -1 if no item matches
  434. */
  435. private int lookupOnly(String pathString) {
  436. String p = pathString;
  437. while (true) {
  438. int position = Collections.binarySearch(only, p);
  439. if (position >= 0)
  440. return position;
  441. int l = p.lastIndexOf("/"); //$NON-NLS-1$
  442. if (l < 1)
  443. break;
  444. p = p.substring(0, l);
  445. }
  446. return -1;
  447. }
  448. /**
  449. * Sets default values for not explicitly specified options. Then validates
  450. * that all required data has been provided.
  451. *
  452. * @param state
  453. * the state of the repository we are working on
  454. * @param rw
  455. * the RevWalk to use
  456. *
  457. * @throws NoMessageException
  458. * if the commit message has not been specified
  459. */
  460. private void processOptions(RepositoryState state, RevWalk rw)
  461. throws NoMessageException {
  462. if (committer == null)
  463. committer = new PersonIdent(repo);
  464. if (author == null && !amend)
  465. author = committer;
  466. if (allowEmpty == null)
  467. // JGit allows empty commits by default. Only when pathes are
  468. // specified the commit should not be empty. This behaviour differs
  469. // from native git but can only be adapted in the next release.
  470. // TODO(ch) align the defaults with native git
  471. allowEmpty = (only.isEmpty()) ? Boolean.TRUE : Boolean.FALSE;
  472. // when doing a merge commit parse MERGE_HEAD and MERGE_MSG files
  473. if (state == RepositoryState.MERGING_RESOLVED
  474. || isMergeDuringRebase(state)) {
  475. try {
  476. parents = repo.readMergeHeads();
  477. if (parents != null)
  478. for (int i = 0; i < parents.size(); i++) {
  479. RevObject ro = rw.parseAny(parents.get(i));
  480. if (ro instanceof RevTag)
  481. parents.set(i, rw.peel(ro));
  482. }
  483. } catch (IOException e) {
  484. throw new JGitInternalException(MessageFormat.format(
  485. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  486. Constants.MERGE_HEAD, e), e);
  487. }
  488. if (message == null) {
  489. try {
  490. message = repo.readMergeCommitMsg();
  491. } catch (IOException e) {
  492. throw new JGitInternalException(MessageFormat.format(
  493. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  494. Constants.MERGE_MSG, e), e);
  495. }
  496. }
  497. } else if (state == RepositoryState.SAFE && message == null) {
  498. try {
  499. message = repo.readSquashCommitMsg();
  500. if (message != null)
  501. repo.writeSquashCommitMsg(null /* delete */);
  502. } catch (IOException e) {
  503. throw new JGitInternalException(MessageFormat.format(
  504. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  505. Constants.MERGE_MSG, e), e);
  506. }
  507. }
  508. if (message == null)
  509. // as long as we don't support -C option we have to have
  510. // an explicit message
  511. throw new NoMessageException(JGitText.get().commitMessageNotSpecified);
  512. }
  513. private boolean isMergeDuringRebase(RepositoryState state) {
  514. if (state != RepositoryState.REBASING_INTERACTIVE
  515. && state != RepositoryState.REBASING_MERGE)
  516. return false;
  517. try {
  518. return repo.readMergeHeads() != null;
  519. } catch (IOException e) {
  520. throw new JGitInternalException(MessageFormat.format(
  521. JGitText.get().exceptionOccurredDuringReadingOfGIT_DIR,
  522. Constants.MERGE_HEAD, e), e);
  523. }
  524. }
  525. /**
  526. * Set the commit message
  527. *
  528. * @param message
  529. * the commit message used for the {@code commit}
  530. * @return {@code this}
  531. */
  532. public CommitCommand setMessage(String message) {
  533. checkCallable();
  534. this.message = message;
  535. return this;
  536. }
  537. /**
  538. * Set whether to allow to create an empty commit
  539. *
  540. * @param allowEmpty
  541. * whether it should be allowed to create a commit which has the
  542. * same tree as it's sole predecessor (a commit which doesn't
  543. * change anything). By default when creating standard commits
  544. * (without specifying paths) JGit allows to create such commits.
  545. * When this flag is set to false an attempt to create an "empty"
  546. * standard commit will lead to an EmptyCommitException.
  547. * <p>
  548. * By default when creating a commit containing only specified
  549. * paths an attempt to create an empty commit leads to a
  550. * {@link org.eclipse.jgit.api.errors.JGitInternalException}. By
  551. * setting this flag to <code>true</code> this exception will not
  552. * be thrown.
  553. * @return {@code this}
  554. * @since 4.2
  555. */
  556. public CommitCommand setAllowEmpty(boolean allowEmpty) {
  557. this.allowEmpty = Boolean.valueOf(allowEmpty);
  558. return this;
  559. }
  560. /**
  561. * Get the commit message
  562. *
  563. * @return the commit message used for the <code>commit</code>
  564. */
  565. public String getMessage() {
  566. return message;
  567. }
  568. /**
  569. * Sets the committer for this {@code commit}. If no committer is explicitly
  570. * specified because this method is never called or called with {@code null}
  571. * value then the committer will be deduced from config info in repository,
  572. * with current time.
  573. *
  574. * @param committer
  575. * the committer used for the {@code commit}
  576. * @return {@code this}
  577. */
  578. public CommitCommand setCommitter(PersonIdent committer) {
  579. checkCallable();
  580. this.committer = committer;
  581. return this;
  582. }
  583. /**
  584. * Sets the committer for this {@code commit}. If no committer is explicitly
  585. * specified because this method is never called then the committer will be
  586. * deduced from config info in repository, with current time.
  587. *
  588. * @param name
  589. * the name of the committer used for the {@code commit}
  590. * @param email
  591. * the email of the committer used for the {@code commit}
  592. * @return {@code this}
  593. */
  594. public CommitCommand setCommitter(String name, String email) {
  595. checkCallable();
  596. return setCommitter(new PersonIdent(name, email));
  597. }
  598. /**
  599. * Get the committer
  600. *
  601. * @return the committer used for the {@code commit}. If no committer was
  602. * specified {@code null} is returned and the default
  603. * {@link org.eclipse.jgit.lib.PersonIdent} of this repo is used
  604. * during execution of the command
  605. */
  606. public PersonIdent getCommitter() {
  607. return committer;
  608. }
  609. /**
  610. * Sets the author for this {@code commit}. If no author is explicitly
  611. * specified because this method is never called or called with {@code null}
  612. * value then the author will be set to the committer or to the original
  613. * author when amending.
  614. *
  615. * @param author
  616. * the author used for the {@code commit}
  617. * @return {@code this}
  618. */
  619. public CommitCommand setAuthor(PersonIdent author) {
  620. checkCallable();
  621. this.author = author;
  622. return this;
  623. }
  624. /**
  625. * Sets the author for this {@code commit}. If no author is explicitly
  626. * specified because this method is never called then the author will be set
  627. * to the committer or to the original author when amending.
  628. *
  629. * @param name
  630. * the name of the author used for the {@code commit}
  631. * @param email
  632. * the email of the author used for the {@code commit}
  633. * @return {@code this}
  634. */
  635. public CommitCommand setAuthor(String name, String email) {
  636. checkCallable();
  637. return setAuthor(new PersonIdent(name, email));
  638. }
  639. /**
  640. * Get the author
  641. *
  642. * @return the author used for the {@code commit}. If no author was
  643. * specified {@code null} is returned and the default
  644. * {@link org.eclipse.jgit.lib.PersonIdent} of this repo is used
  645. * during execution of the command
  646. */
  647. public PersonIdent getAuthor() {
  648. return author;
  649. }
  650. /**
  651. * If set to true the Commit command automatically stages files that have
  652. * been modified and deleted, but new files not known by the repository are
  653. * not affected. This corresponds to the parameter -a on the command line.
  654. *
  655. * @param all
  656. * whether to auto-stage all files that have been modified and
  657. * deleted
  658. * @return {@code this}
  659. * @throws JGitInternalException
  660. * in case of an illegal combination of arguments/ options
  661. */
  662. public CommitCommand setAll(boolean all) {
  663. checkCallable();
  664. if (all && !only.isEmpty())
  665. throw new JGitInternalException(MessageFormat.format(
  666. JGitText.get().illegalCombinationOfArguments, "--all", //$NON-NLS-1$
  667. "--only")); //$NON-NLS-1$
  668. this.all = all;
  669. return this;
  670. }
  671. /**
  672. * Used to amend the tip of the current branch. If set to {@code true}, the
  673. * previous commit will be amended. This is equivalent to --amend on the
  674. * command line.
  675. *
  676. * @param amend
  677. * whether to ammend the tip of the current branch
  678. * @return {@code this}
  679. */
  680. public CommitCommand setAmend(boolean amend) {
  681. checkCallable();
  682. this.amend = amend;
  683. return this;
  684. }
  685. /**
  686. * Commit dedicated path only.
  687. * <p>
  688. * This method can be called several times to add multiple paths. Full file
  689. * paths are supported as well as directory paths; in the latter case this
  690. * commits all files/directories below the specified path.
  691. *
  692. * @param only
  693. * path to commit (with <code>/</code> as separator)
  694. * @return {@code this}
  695. */
  696. public CommitCommand setOnly(String only) {
  697. checkCallable();
  698. if (all)
  699. throw new JGitInternalException(MessageFormat.format(
  700. JGitText.get().illegalCombinationOfArguments, "--only", //$NON-NLS-1$
  701. "--all")); //$NON-NLS-1$
  702. String o = only.endsWith("/") ? only.substring(0, only.length() - 1) //$NON-NLS-1$
  703. : only;
  704. // ignore duplicates
  705. if (!this.only.contains(o))
  706. this.only.add(o);
  707. return this;
  708. }
  709. /**
  710. * If set to true a change id will be inserted into the commit message
  711. *
  712. * An existing change id is not replaced. An initial change id (I000...)
  713. * will be replaced by the change id.
  714. *
  715. * @param insertChangeId
  716. * whether to insert a change id
  717. * @return {@code this}
  718. */
  719. public CommitCommand setInsertChangeId(boolean insertChangeId) {
  720. checkCallable();
  721. this.insertChangeId = insertChangeId;
  722. return this;
  723. }
  724. /**
  725. * Override the message written to the reflog
  726. *
  727. * @param reflogComment
  728. * the comment to be written into the reflog or <code>null</code>
  729. * to specify that no reflog should be written
  730. * @return {@code this}
  731. */
  732. public CommitCommand setReflogComment(String reflogComment) {
  733. this.reflogComment = reflogComment;
  734. useDefaultReflogMessage = false;
  735. return this;
  736. }
  737. /**
  738. * Sets the {@link #noVerify} option on this commit command.
  739. * <p>
  740. * Both the pre-commit and commit-msg hooks can block a commit by their
  741. * return value; setting this option to <code>true</code> will bypass these
  742. * two hooks.
  743. * </p>
  744. *
  745. * @param noVerify
  746. * Whether this commit should be verified by the pre-commit and
  747. * commit-msg hooks.
  748. * @return {@code this}
  749. * @since 3.7
  750. */
  751. public CommitCommand setNoVerify(boolean noVerify) {
  752. this.noVerify = noVerify;
  753. return this;
  754. }
  755. /**
  756. * Set the output stream for all hook scripts executed by this command
  757. * (pre-commit, commit-msg, post-commit). If not set it defaults to
  758. * {@code System.out}.
  759. *
  760. * @param hookStdOut
  761. * the output stream for hook scripts executed by this command
  762. * @return {@code this}
  763. * @since 3.7
  764. */
  765. public CommitCommand setHookOutputStream(PrintStream hookStdOut) {
  766. setHookOutputStream(PreCommitHook.NAME, hookStdOut);
  767. setHookOutputStream(CommitMsgHook.NAME, hookStdOut);
  768. setHookOutputStream(PostCommitHook.NAME, hookStdOut);
  769. return this;
  770. }
  771. /**
  772. * Set the output stream for a selected hook script executed by this command
  773. * (pre-commit, commit-msg, post-commit). If not set it defaults to
  774. * {@code System.out}.
  775. *
  776. * @param hookName
  777. * name of the hook to set the output stream for
  778. * @param hookStdOut
  779. * the output stream to use for the selected hook
  780. * @return {@code this}
  781. * @since 4.5
  782. */
  783. public CommitCommand setHookOutputStream(String hookName,
  784. PrintStream hookStdOut) {
  785. if (!(PreCommitHook.NAME.equals(hookName)
  786. || CommitMsgHook.NAME.equals(hookName)
  787. || PostCommitHook.NAME.equals(hookName))) {
  788. throw new IllegalArgumentException(
  789. MessageFormat.format(JGitText.get().illegalHookName,
  790. hookName));
  791. }
  792. hookOutRedirect.put(hookName, hookStdOut);
  793. return this;
  794. }
  795. }