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.

RebaseCommand.java 42KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340
  1. /*
  2. * Copyright (C) 2010, 2013 Mathias Kinzler <mathias.kinzler@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.ByteArrayOutputStream;
  45. import java.io.File;
  46. import java.io.FileNotFoundException;
  47. import java.io.FileOutputStream;
  48. import java.io.IOException;
  49. import java.text.MessageFormat;
  50. import java.util.ArrayList;
  51. import java.util.Collection;
  52. import java.util.Collections;
  53. import java.util.HashMap;
  54. import java.util.LinkedList;
  55. import java.util.List;
  56. import java.util.Map;
  57. import java.util.regex.Matcher;
  58. import java.util.regex.Pattern;
  59. import org.eclipse.jgit.api.RebaseResult.Status;
  60. import org.eclipse.jgit.api.ResetCommand.ResetType;
  61. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  62. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  63. import org.eclipse.jgit.api.errors.GitAPIException;
  64. import org.eclipse.jgit.api.errors.InvalidRebaseStepException;
  65. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  66. import org.eclipse.jgit.api.errors.JGitInternalException;
  67. import org.eclipse.jgit.api.errors.NoHeadException;
  68. import org.eclipse.jgit.api.errors.NoMessageException;
  69. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  70. import org.eclipse.jgit.api.errors.RefNotFoundException;
  71. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  72. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  73. import org.eclipse.jgit.diff.DiffFormatter;
  74. import org.eclipse.jgit.dircache.DirCache;
  75. import org.eclipse.jgit.dircache.DirCacheCheckout;
  76. import org.eclipse.jgit.dircache.DirCacheIterator;
  77. import org.eclipse.jgit.internal.JGitText;
  78. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  79. import org.eclipse.jgit.lib.AnyObjectId;
  80. import org.eclipse.jgit.lib.Constants;
  81. import org.eclipse.jgit.lib.NullProgressMonitor;
  82. import org.eclipse.jgit.lib.ObjectId;
  83. import org.eclipse.jgit.lib.ObjectReader;
  84. import org.eclipse.jgit.lib.PersonIdent;
  85. import org.eclipse.jgit.lib.ProgressMonitor;
  86. import org.eclipse.jgit.lib.RebaseTodoLine;
  87. import org.eclipse.jgit.lib.RebaseTodoLine.Action;
  88. import org.eclipse.jgit.lib.Ref;
  89. import org.eclipse.jgit.lib.RefUpdate;
  90. import org.eclipse.jgit.lib.RefUpdate.Result;
  91. import org.eclipse.jgit.lib.Repository;
  92. import org.eclipse.jgit.revwalk.RevCommit;
  93. import org.eclipse.jgit.revwalk.RevWalk;
  94. import org.eclipse.jgit.treewalk.TreeWalk;
  95. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  96. import org.eclipse.jgit.util.FileUtils;
  97. import org.eclipse.jgit.util.IO;
  98. import org.eclipse.jgit.util.RawParseUtils;
  99. /**
  100. * A class used to execute a {@code Rebase} command. It has setters for all
  101. * supported options and arguments of this command and a {@link #call()} method
  102. * to finally execute the command. Each instance of this class should only be
  103. * used for one invocation of the command (means: one call to {@link #call()})
  104. * <p>
  105. *
  106. * @see <a
  107. * href="http://www.kernel.org/pub/software/scm/git/docs/git-rebase.html"
  108. * >Git documentation about Rebase</a>
  109. */
  110. public class RebaseCommand extends GitCommand<RebaseResult> {
  111. /**
  112. * The name of the "rebase-merge" folder for interactive rebases.
  113. */
  114. public static final String REBASE_MERGE = "rebase-merge"; //$NON-NLS-1$
  115. /**
  116. * The name of the "rebase-apply" folder for non-interactive rebases.
  117. */
  118. private static final String REBASE_APPLY = "rebase-apply"; //$NON-NLS-1$
  119. /**
  120. * The name of the "stopped-sha" file
  121. */
  122. public static final String STOPPED_SHA = "stopped-sha"; //$NON-NLS-1$
  123. private static final String AUTHOR_SCRIPT = "author-script"; //$NON-NLS-1$
  124. private static final String DONE = "done"; //$NON-NLS-1$
  125. private static final String GIT_AUTHOR_DATE = "GIT_AUTHOR_DATE"; //$NON-NLS-1$
  126. private static final String GIT_AUTHOR_EMAIL = "GIT_AUTHOR_EMAIL"; //$NON-NLS-1$
  127. private static final String GIT_AUTHOR_NAME = "GIT_AUTHOR_NAME"; //$NON-NLS-1$
  128. private static final String GIT_REBASE_TODO = "git-rebase-todo"; //$NON-NLS-1$
  129. private static final String HEAD_NAME = "head-name"; //$NON-NLS-1$
  130. private static final String INTERACTIVE = "interactive"; //$NON-NLS-1$
  131. private static final String MESSAGE = "message"; //$NON-NLS-1$
  132. private static final String ONTO = "onto"; //$NON-NLS-1$
  133. private static final String ONTO_NAME = "onto-name"; //$NON-NLS-1$
  134. private static final String PATCH = "patch"; //$NON-NLS-1$
  135. private static final String REBASE_HEAD = "head"; //$NON-NLS-1$
  136. private static final String AMEND = "amend"; //$NON-NLS-1$
  137. private static final String MESSAGE_FIXUP = "message-fixup"; //$NON-NLS-1$
  138. private static final String MESSAGE_SQUASH = "message-squash"; //$NON-NLS-1$
  139. /**
  140. * The available operations
  141. */
  142. public enum Operation {
  143. /**
  144. * Initiates rebase
  145. */
  146. BEGIN,
  147. /**
  148. * Continues after a conflict resolution
  149. */
  150. CONTINUE,
  151. /**
  152. * Skips the "current" commit
  153. */
  154. SKIP,
  155. /**
  156. * Aborts and resets the current rebase
  157. */
  158. ABORT,
  159. /**
  160. * Starts processing steps
  161. * @since 3.2
  162. */
  163. PROCESS_STEPS;
  164. }
  165. private Operation operation = Operation.BEGIN;
  166. private RevCommit upstreamCommit;
  167. private String upstreamCommitName;
  168. private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;
  169. private final RevWalk walk;
  170. private final RebaseState rebaseState;
  171. private InteractiveHandler interactiveHandler;
  172. private boolean stopAfterInitialization = false;
  173. private RevCommit newHead;
  174. private boolean lastStepWasForward;
  175. /**
  176. * @param repo
  177. */
  178. protected RebaseCommand(Repository repo) {
  179. super(repo);
  180. walk = new RevWalk(repo);
  181. rebaseState = new RebaseState(repo.getDirectory());
  182. }
  183. /**
  184. * Executes the {@code Rebase} command with all the options and parameters
  185. * collected by the setter methods of this class. Each instance of this
  186. * class should only be used for one invocation of the command. Don't call
  187. * this method twice on an instance.
  188. *
  189. * @return an object describing the result of this command
  190. * @throws GitAPIException
  191. * @throws WrongRepositoryStateException
  192. * @throws NoHeadException
  193. * @throws RefNotFoundException
  194. */
  195. public RebaseResult call() throws GitAPIException, NoHeadException,
  196. RefNotFoundException, WrongRepositoryStateException {
  197. newHead = null;
  198. lastStepWasForward = false;
  199. checkCallable();
  200. checkParameters();
  201. try {
  202. switch (operation) {
  203. case ABORT:
  204. try {
  205. return abort(RebaseResult.ABORTED_RESULT);
  206. } catch (IOException ioe) {
  207. throw new JGitInternalException(ioe.getMessage(), ioe);
  208. }
  209. case PROCESS_STEPS:
  210. // fall through
  211. case SKIP:
  212. // fall through
  213. case CONTINUE:
  214. String upstreamCommitId = rebaseState.readFile(ONTO);
  215. try {
  216. upstreamCommitName = rebaseState.readFile(ONTO_NAME);
  217. } catch (FileNotFoundException e) {
  218. // Fall back to commit ID if file doesn't exist (e.g. rebase
  219. // was started by C Git)
  220. upstreamCommitName = upstreamCommitId;
  221. }
  222. this.upstreamCommit = walk.parseCommit(repo
  223. .resolve(upstreamCommitId));
  224. break;
  225. case BEGIN:
  226. RebaseResult res = initFilesAndRewind();
  227. if (stopAfterInitialization)
  228. return RebaseResult.INTERACTIVE_PREPARED_RESULT;
  229. if (res != null)
  230. return res;
  231. }
  232. if (monitor.isCancelled())
  233. return abort(RebaseResult.ABORTED_RESULT);
  234. if (operation == Operation.CONTINUE) {
  235. newHead = continueRebase();
  236. List<RebaseTodoLine> doneLines = repo.readRebaseTodo(
  237. rebaseState.getPath(DONE), true);
  238. RebaseTodoLine step = doneLines.get(doneLines.size() - 1);
  239. if (newHead != null
  240. && step.getAction() != Action.PICK) {
  241. RebaseTodoLine newStep = new RebaseTodoLine(
  242. step.getAction(),
  243. AbbreviatedObjectId.fromObjectId(newHead),
  244. step.getShortMessage());
  245. RebaseResult result = processStep(newStep, false);
  246. if (result != null)
  247. return result;
  248. }
  249. File amendFile = rebaseState.getFile(AMEND);
  250. boolean amendExists = amendFile.exists();
  251. if (amendExists) {
  252. FileUtils.delete(amendFile);
  253. }
  254. if (newHead == null && !amendExists) {
  255. // continueRebase() returns null only if no commit was
  256. // neccessary. This means that no changes where left over
  257. // after resolving all conflicts. In this case, cgit stops
  258. // and displays a nice message to the user, telling him to
  259. // either do changes or skip the commit instead of continue.
  260. return RebaseResult.NOTHING_TO_COMMIT_RESULT;
  261. }
  262. }
  263. if (operation == Operation.SKIP)
  264. newHead = checkoutCurrentHead();
  265. List<RebaseTodoLine> steps = repo.readRebaseTodo(
  266. rebaseState.getPath(GIT_REBASE_TODO), false);
  267. if (steps.size() == 0) {
  268. return finishRebase(walk.parseCommit(repo.resolve(Constants.HEAD)), false);
  269. }
  270. if (isInteractive()) {
  271. interactiveHandler.prepareSteps(steps);
  272. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  273. steps, false);
  274. }
  275. checkSteps(steps);
  276. for (int i = 0; i < steps.size(); i++) {
  277. RebaseTodoLine step = steps.get(i);
  278. popSteps(1);
  279. RebaseResult result = processStep(step, true);
  280. if (result != null) {
  281. return result;
  282. }
  283. }
  284. return finishRebase(newHead, lastStepWasForward);
  285. } catch (CheckoutConflictException cce) {
  286. return RebaseResult.conflicts(cce.getConflictingPaths());
  287. } catch (IOException ioe) {
  288. throw new JGitInternalException(ioe.getMessage(), ioe);
  289. }
  290. }
  291. private RebaseResult processStep(RebaseTodoLine step, boolean shouldPick)
  292. throws IOException, GitAPIException {
  293. if (Action.COMMENT.equals(step.getAction()))
  294. return null;
  295. ObjectReader or = repo.newObjectReader();
  296. Collection<ObjectId> ids = or.resolve(step.getCommit());
  297. if (ids.size() != 1)
  298. throw new JGitInternalException(
  299. "Could not resolve uniquely the abbreviated object ID");
  300. RevCommit commitToPick = walk.parseCommit(ids.iterator().next());
  301. if (shouldPick) {
  302. if (monitor.isCancelled())
  303. return RebaseResult.result(Status.STOPPED, commitToPick);
  304. RebaseResult result = cherryPickCommit(commitToPick);
  305. if (result != null)
  306. return result;
  307. }
  308. boolean isSquash = false;
  309. switch (step.getAction()) {
  310. case PICK:
  311. return null; // continue rebase process on pick command
  312. case REWORD:
  313. String oldMessage = commitToPick.getFullMessage();
  314. String newMessage = interactiveHandler
  315. .modifyCommitMessage(oldMessage);
  316. newHead = new Git(repo).commit().setMessage(newMessage)
  317. .setAmend(true).call();
  318. return null;
  319. case EDIT:
  320. rebaseState.createFile(AMEND, commitToPick.name());
  321. return stop(commitToPick, Status.EDIT);
  322. case COMMENT:
  323. break;
  324. case SQUASH:
  325. isSquash = true;
  326. //$FALL-THROUGH$
  327. case FIXUP:
  328. resetSoftToParent();
  329. List<RebaseTodoLine> steps = repo.readRebaseTodo(
  330. rebaseState.getPath(GIT_REBASE_TODO), false);
  331. RebaseTodoLine nextStep = steps.size() > 0 ? steps.get(0) : null;
  332. File messageFixupFile = rebaseState.getFile(MESSAGE_FIXUP);
  333. File messageSquashFile = rebaseState.getFile(MESSAGE_SQUASH);
  334. if (isSquash && messageFixupFile.exists())
  335. messageFixupFile.delete();
  336. newHead = doSquashFixup(isSquash, commitToPick, nextStep,
  337. messageFixupFile, messageSquashFile);
  338. }
  339. return null;
  340. }
  341. private RebaseResult cherryPickCommit(RevCommit commitToPick)
  342. throws IOException, GitAPIException, NoMessageException,
  343. UnmergedPathsException, ConcurrentRefUpdateException,
  344. WrongRepositoryStateException, NoHeadException {
  345. try {
  346. monitor.beginTask(MessageFormat.format(
  347. JGitText.get().applyingCommit,
  348. commitToPick.getShortMessage()), ProgressMonitor.UNKNOWN);
  349. // if the first parent of commitToPick is the current HEAD,
  350. // we do a fast-forward instead of cherry-pick to avoid
  351. // unnecessary object rewriting
  352. newHead = tryFastForward(commitToPick);
  353. lastStepWasForward = newHead != null;
  354. if (!lastStepWasForward) {
  355. // TODO if the content of this commit is already merged
  356. // here we should skip this step in order to avoid
  357. // confusing pseudo-changed
  358. String ourCommitName = getOurCommitName();
  359. CherryPickResult cherryPickResult = new Git(repo).cherryPick()
  360. .include(commitToPick).setOurCommitName(ourCommitName)
  361. .setReflogPrefix("rebase:").call(); //$NON-NLS-1$
  362. switch (cherryPickResult.getStatus()) {
  363. case FAILED:
  364. if (operation == Operation.BEGIN)
  365. return abort(RebaseResult.failed(cherryPickResult
  366. .getFailingPaths()));
  367. else
  368. return stop(commitToPick, Status.STOPPED);
  369. case CONFLICTING:
  370. return stop(commitToPick, Status.STOPPED);
  371. case OK:
  372. newHead = cherryPickResult.getNewHead();
  373. }
  374. }
  375. return null;
  376. } finally {
  377. monitor.endTask();
  378. }
  379. }
  380. private RebaseResult finishRebase(RevCommit newHead,
  381. boolean lastStepWasForward) throws IOException {
  382. String headName = rebaseState.readFile(HEAD_NAME);
  383. updateHead(headName, newHead, upstreamCommit);
  384. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  385. if (lastStepWasForward || newHead == null)
  386. return RebaseResult.FAST_FORWARD_RESULT;
  387. return RebaseResult.OK_RESULT;
  388. }
  389. private void checkSteps(List<RebaseTodoLine> steps)
  390. throws InvalidRebaseStepException, IOException {
  391. if (steps.isEmpty())
  392. return;
  393. if (RebaseTodoLine.Action.SQUASH.equals(steps.get(0).getAction())
  394. || RebaseTodoLine.Action.FIXUP.equals(steps.get(0).getAction())) {
  395. if (!rebaseState.getFile(DONE).exists()
  396. || rebaseState.readFile(DONE).trim().length() == 0) {
  397. throw new InvalidRebaseStepException(MessageFormat.format(
  398. JGitText.get().cannotSquashFixupWithoutPreviousCommit,
  399. steps.get(0).getAction().name()));
  400. }
  401. }
  402. }
  403. private RevCommit doSquashFixup(boolean isSquash, RevCommit commitToPick,
  404. RebaseTodoLine nextStep, File messageFixup, File messageSquash)
  405. throws IOException, GitAPIException {
  406. if (!messageSquash.exists()) {
  407. // init squash/fixup sequence
  408. ObjectId headId = repo.resolve(Constants.HEAD);
  409. RevCommit previousCommit = walk.parseCommit(headId);
  410. initializeSquashFixupFile(MESSAGE_SQUASH,
  411. previousCommit.getFullMessage());
  412. if (!isSquash)
  413. initializeSquashFixupFile(MESSAGE_FIXUP,
  414. previousCommit.getFullMessage());
  415. }
  416. String currSquashMessage = rebaseState
  417. .readFile(MESSAGE_SQUASH);
  418. int count = parseSquashFixupSequenceCount(currSquashMessage) + 1;
  419. String content = composeSquashMessage(isSquash,
  420. commitToPick, currSquashMessage, count);
  421. rebaseState.createFile(MESSAGE_SQUASH, content);
  422. if (messageFixup.exists())
  423. rebaseState.createFile(MESSAGE_FIXUP, content);
  424. return squashIntoPrevious(
  425. !messageFixup.exists(),
  426. nextStep);
  427. }
  428. private void resetSoftToParent() throws IOException,
  429. GitAPIException, CheckoutConflictException {
  430. Ref orig_head = repo.getRef(Constants.ORIG_HEAD);
  431. ObjectId orig_headId = orig_head.getObjectId();
  432. try {
  433. // we have already commited the cherry-picked commit.
  434. // what we need is to have changes introduced by this
  435. // commit to be on the index
  436. // resetting is a workaround
  437. Git.wrap(repo).reset().setMode(ResetType.SOFT)
  438. .setRef("HEAD~1").call(); //$NON-NLS-1$
  439. } finally {
  440. // set ORIG_HEAD back to where we started because soft
  441. // reset moved it
  442. repo.writeOrigHead(orig_headId);
  443. }
  444. }
  445. private RevCommit squashIntoPrevious(boolean sequenceContainsSquash,
  446. RebaseTodoLine nextStep)
  447. throws IOException, GitAPIException {
  448. RevCommit newHead;
  449. String commitMessage = rebaseState
  450. .readFile(MESSAGE_SQUASH);
  451. if (nextStep == null
  452. || ((nextStep.getAction() != Action.FIXUP) && (nextStep
  453. .getAction() != Action.SQUASH))) {
  454. // this is the last step in this sequence
  455. if (sequenceContainsSquash) {
  456. commitMessage = interactiveHandler
  457. .modifyCommitMessage(commitMessage);
  458. }
  459. newHead = new Git(repo).commit()
  460. .setMessage(stripCommentLines(commitMessage))
  461. .setAmend(true).call();
  462. rebaseState.getFile(MESSAGE_SQUASH).delete();
  463. rebaseState.getFile(MESSAGE_FIXUP).delete();
  464. } else {
  465. // Next step is either Squash or Fixup
  466. newHead = new Git(repo).commit()
  467. .setMessage(commitMessage).setAmend(true)
  468. .call();
  469. }
  470. return newHead;
  471. }
  472. private static String stripCommentLines(String commitMessage) {
  473. StringBuilder result = new StringBuilder();
  474. for (String line : commitMessage.split("\n")) { //$NON-NLS-1$
  475. if (!line.trim().startsWith("#")) //$NON-NLS-1$
  476. result.append(line).append("\n"); //$NON-NLS-1$
  477. }
  478. if (!commitMessage.endsWith("\n")) //$NON-NLS-1$
  479. result.deleteCharAt(result.length() - 1);
  480. return result.toString();
  481. }
  482. @SuppressWarnings("nls")
  483. private static String composeSquashMessage(boolean isSquash,
  484. RevCommit commitToPick, String currSquashMessage, int count) {
  485. StringBuilder sb = new StringBuilder();
  486. String ordinal = getOrdinal(count);
  487. sb.setLength(0);
  488. sb.append("# This is a combination of ").append(count)
  489. .append(" commits.\n");
  490. if (isSquash) {
  491. sb.append("# This is the ").append(count).append(ordinal)
  492. .append(" commit message:\n");
  493. sb.append(commitToPick.getFullMessage());
  494. } else {
  495. sb.append("# The ").append(count).append(ordinal)
  496. .append(" commit message will be skipped:\n# ");
  497. sb.append(commitToPick.getFullMessage().replaceAll("([\n\r])",
  498. "$1# "));
  499. }
  500. // Add the previous message without header (i.e first line)
  501. sb.append("\n");
  502. sb.append(currSquashMessage.substring(currSquashMessage.indexOf("\n") + 1));
  503. return sb.toString();
  504. }
  505. private static String getOrdinal(int count) {
  506. switch (count % 10) {
  507. case 1:
  508. return "st"; //$NON-NLS-1$
  509. case 2:
  510. return "nd"; //$NON-NLS-1$
  511. case 3:
  512. return "rd"; //$NON-NLS-1$
  513. default:
  514. return "th"; //$NON-NLS-1$
  515. }
  516. }
  517. /**
  518. * Parse the count from squashed commit messages
  519. *
  520. * @param currSquashMessage
  521. * the squashed commit message to be parsed
  522. * @return the count of squashed messages in the given string
  523. */
  524. static int parseSquashFixupSequenceCount(String currSquashMessage) {
  525. String regex = "This is a combination of (.*) commits"; //$NON-NLS-1$
  526. String firstLine = currSquashMessage.substring(0,
  527. currSquashMessage.indexOf("\n")); //$NON-NLS-1$
  528. Pattern pattern = Pattern.compile(regex);
  529. Matcher matcher = pattern.matcher(firstLine);
  530. if (!matcher.find())
  531. throw new IllegalArgumentException();
  532. return Integer.parseInt(matcher.group(1));
  533. }
  534. private void initializeSquashFixupFile(String messageFile,
  535. String fullMessage) throws IOException {
  536. rebaseState
  537. .createFile(
  538. messageFile,
  539. "# This is a combination of 1 commits.\n# The first commit's message is:\n" + fullMessage); //$NON-NLS-1$);
  540. }
  541. private String getOurCommitName() {
  542. // If onto is different from upstream, this should say "onto", but
  543. // RebaseCommand doesn't support a different "onto" at the moment.
  544. String ourCommitName = "Upstream, based on " //$NON-NLS-1$
  545. + Repository.shortenRefName(upstreamCommitName);
  546. return ourCommitName;
  547. }
  548. private void updateHead(String headName, RevCommit newHead, RevCommit onto)
  549. throws IOException {
  550. // point the previous head (if any) to the new commit
  551. if (headName.startsWith(Constants.R_REFS)) {
  552. RefUpdate rup = repo.updateRef(headName);
  553. rup.setNewObjectId(newHead);
  554. rup.setRefLogMessage("rebase finished: " + headName + " onto " //$NON-NLS-1$ //$NON-NLS-2$
  555. + onto.getName(), false);
  556. Result res = rup.forceUpdate();
  557. switch (res) {
  558. case FAST_FORWARD:
  559. case FORCED:
  560. case NO_CHANGE:
  561. break;
  562. default:
  563. throw new JGitInternalException("Updating HEAD failed");
  564. }
  565. rup = repo.updateRef(Constants.HEAD);
  566. rup.setRefLogMessage("rebase finished: returning to " + headName, //$NON-NLS-1$
  567. false);
  568. res = rup.link(headName);
  569. switch (res) {
  570. case FAST_FORWARD:
  571. case FORCED:
  572. case NO_CHANGE:
  573. break;
  574. default:
  575. throw new JGitInternalException("Updating HEAD failed");
  576. }
  577. }
  578. }
  579. private RevCommit checkoutCurrentHead() throws IOException, NoHeadException {
  580. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  581. if (headTree == null)
  582. throw new NoHeadException(
  583. JGitText.get().cannotRebaseWithoutCurrentHead);
  584. DirCache dc = repo.lockDirCache();
  585. try {
  586. DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
  587. dco.setFailOnConflict(false);
  588. boolean needsDeleteFiles = dco.checkout();
  589. if (needsDeleteFiles) {
  590. List<String> fileList = dco.getToBeDeleted();
  591. for (String filePath : fileList) {
  592. File fileToDelete = new File(repo.getWorkTree(), filePath);
  593. if (fileToDelete.exists())
  594. FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
  595. | FileUtils.RETRY);
  596. }
  597. }
  598. } finally {
  599. dc.unlock();
  600. }
  601. RevWalk rw = new RevWalk(repo);
  602. RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
  603. rw.release();
  604. return commit;
  605. }
  606. /**
  607. * @return the commit if we had to do a commit, otherwise null
  608. * @throws GitAPIException
  609. * @throws IOException
  610. */
  611. private RevCommit continueRebase() throws GitAPIException, IOException {
  612. // if there are still conflicts, we throw a specific Exception
  613. DirCache dc = repo.readDirCache();
  614. boolean hasUnmergedPaths = dc.hasUnmergedPaths();
  615. if (hasUnmergedPaths)
  616. throw new UnmergedPathsException();
  617. // determine whether we need to commit
  618. TreeWalk treeWalk = new TreeWalk(repo);
  619. treeWalk.reset();
  620. treeWalk.setRecursive(true);
  621. treeWalk.addTree(new DirCacheIterator(dc));
  622. ObjectId id = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  623. if (id == null)
  624. throw new NoHeadException(
  625. JGitText.get().cannotRebaseWithoutCurrentHead);
  626. treeWalk.addTree(id);
  627. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  628. boolean needsCommit = treeWalk.next();
  629. treeWalk.release();
  630. if (needsCommit) {
  631. CommitCommand commit = new Git(repo).commit();
  632. commit.setMessage(rebaseState.readFile(MESSAGE));
  633. commit.setAuthor(parseAuthor());
  634. return commit.call();
  635. }
  636. return null;
  637. }
  638. private PersonIdent parseAuthor() throws IOException {
  639. File authorScriptFile = rebaseState.getFile(AUTHOR_SCRIPT);
  640. byte[] raw;
  641. try {
  642. raw = IO.readFully(authorScriptFile);
  643. } catch (FileNotFoundException notFound) {
  644. return null;
  645. }
  646. return parseAuthor(raw);
  647. }
  648. private RebaseResult stop(RevCommit commitToPick, RebaseResult.Status status)
  649. throws IOException {
  650. PersonIdent author = commitToPick.getAuthorIdent();
  651. String authorScript = toAuthorScript(author);
  652. rebaseState.createFile(AUTHOR_SCRIPT, authorScript);
  653. rebaseState.createFile(MESSAGE, commitToPick.getFullMessage());
  654. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  655. DiffFormatter df = new DiffFormatter(bos);
  656. df.setRepository(repo);
  657. df.format(commitToPick.getParent(0), commitToPick);
  658. rebaseState.createFile(PATCH, new String(bos.toByteArray(),
  659. Constants.CHARACTER_ENCODING));
  660. rebaseState.createFile(STOPPED_SHA,
  661. repo.newObjectReader()
  662. .abbreviate(
  663. commitToPick).name());
  664. // Remove cherry pick state file created by CherryPickCommand, it's not
  665. // needed for rebase
  666. repo.writeCherryPickHead(null);
  667. return RebaseResult.result(status, commitToPick);
  668. }
  669. String toAuthorScript(PersonIdent author) {
  670. StringBuilder sb = new StringBuilder(100);
  671. sb.append(GIT_AUTHOR_NAME);
  672. sb.append("='"); //$NON-NLS-1$
  673. sb.append(author.getName());
  674. sb.append("'\n"); //$NON-NLS-1$
  675. sb.append(GIT_AUTHOR_EMAIL);
  676. sb.append("='"); //$NON-NLS-1$
  677. sb.append(author.getEmailAddress());
  678. sb.append("'\n"); //$NON-NLS-1$
  679. // the command line uses the "external String"
  680. // representation for date and timezone
  681. sb.append(GIT_AUTHOR_DATE);
  682. sb.append("='"); //$NON-NLS-1$
  683. sb.append("@"); // @ for time in seconds since 1970 //$NON-NLS-1$
  684. String externalString = author.toExternalString();
  685. sb
  686. .append(externalString.substring(externalString
  687. .lastIndexOf('>') + 2));
  688. sb.append("'\n"); //$NON-NLS-1$
  689. return sb.toString();
  690. }
  691. /**
  692. * Removes the number of lines given in the parameter from the
  693. * <code>git-rebase-todo</code> file but preserves comments and other lines
  694. * that can not be parsed as steps
  695. *
  696. * @param numSteps
  697. * @throws IOException
  698. */
  699. private void popSteps(int numSteps) throws IOException {
  700. if (numSteps == 0)
  701. return;
  702. List<RebaseTodoLine> todoLines = new LinkedList<RebaseTodoLine>();
  703. List<RebaseTodoLine> poppedLines = new LinkedList<RebaseTodoLine>();
  704. for (RebaseTodoLine line : repo.readRebaseTodo(
  705. rebaseState.getPath(GIT_REBASE_TODO), true)) {
  706. if (poppedLines.size() >= numSteps
  707. || RebaseTodoLine.Action.COMMENT.equals(line.getAction()))
  708. todoLines.add(line);
  709. else
  710. poppedLines.add(line);
  711. }
  712. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  713. todoLines, false);
  714. if (poppedLines.size() > 0) {
  715. repo.writeRebaseTodoFile(rebaseState.getPath(DONE), poppedLines,
  716. true);
  717. }
  718. }
  719. private RebaseResult initFilesAndRewind() throws IOException,
  720. GitAPIException {
  721. // we need to store everything into files so that we can implement
  722. // --skip, --continue, and --abort
  723. Ref head = repo.getRef(Constants.HEAD);
  724. if (head == null || head.getObjectId() == null)
  725. throw new RefNotFoundException(MessageFormat.format(
  726. JGitText.get().refNotResolved, Constants.HEAD));
  727. String headName;
  728. if (head.isSymbolic())
  729. headName = head.getTarget().getName();
  730. else
  731. headName = head.getObjectId().getName();
  732. ObjectId headId = head.getObjectId();
  733. if (headId == null)
  734. throw new RefNotFoundException(MessageFormat.format(
  735. JGitText.get().refNotResolved, Constants.HEAD));
  736. RevCommit headCommit = walk.lookupCommit(headId);
  737. RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());
  738. if (!isInteractive() && walk.isMergedInto(upstream, headCommit))
  739. return RebaseResult.UP_TO_DATE_RESULT;
  740. else if (!isInteractive() && walk.isMergedInto(headCommit, upstream)) {
  741. // head is already merged into upstream, fast-foward
  742. monitor.beginTask(MessageFormat.format(
  743. JGitText.get().resettingHead,
  744. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  745. checkoutCommit(headName, upstreamCommit);
  746. monitor.endTask();
  747. updateHead(headName, upstreamCommit, upstream);
  748. return RebaseResult.FAST_FORWARD_RESULT;
  749. }
  750. monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
  751. ProgressMonitor.UNKNOWN);
  752. // determine the commits to be applied
  753. LogCommand cmd = new Git(repo).log().addRange(upstreamCommit,
  754. headCommit);
  755. Iterable<RevCommit> commitsToUse = cmd.call();
  756. List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
  757. for (RevCommit commit : commitsToUse) {
  758. if (commit.getParentCount() != 1)
  759. continue;
  760. cherryPickList.add(commit);
  761. }
  762. Collections.reverse(cherryPickList);
  763. // create the folder for the meta information
  764. FileUtils.mkdir(rebaseState.getDir());
  765. repo.writeOrigHead(headId);
  766. rebaseState.createFile(REBASE_HEAD, headId.name());
  767. rebaseState.createFile(HEAD_NAME, headName);
  768. rebaseState.createFile(ONTO, upstreamCommit.name());
  769. rebaseState.createFile(ONTO_NAME, upstreamCommitName);
  770. rebaseState.createFile(INTERACTIVE, ""); //$NON-NLS-1$
  771. ArrayList<RebaseTodoLine> toDoSteps = new ArrayList<RebaseTodoLine>();
  772. toDoSteps.add(new RebaseTodoLine("# Created by EGit: rebasing " + headId.name() //$NON-NLS-1$
  773. + " onto " + upstreamCommit.name())); //$NON-NLS-1$
  774. ObjectReader reader = walk.getObjectReader();
  775. for (RevCommit commit : cherryPickList)
  776. toDoSteps.add(new RebaseTodoLine(Action.PICK, reader
  777. .abbreviate(commit), commit.getShortMessage()));
  778. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  779. toDoSteps, false);
  780. monitor.endTask();
  781. // we rewind to the upstream commit
  782. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  783. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  784. boolean checkoutOk = false;
  785. try {
  786. checkoutOk = checkoutCommit(headName, upstreamCommit);
  787. } finally {
  788. if (!checkoutOk)
  789. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  790. }
  791. monitor.endTask();
  792. return null;
  793. }
  794. private boolean isInteractive() {
  795. return interactiveHandler != null;
  796. }
  797. /**
  798. * checks if we can fast-forward and returns the new head if it is possible
  799. *
  800. * @param newCommit
  801. * @return the new head, or null
  802. * @throws IOException
  803. * @throws GitAPIException
  804. */
  805. public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
  806. GitAPIException {
  807. Ref head = repo.getRef(Constants.HEAD);
  808. if (head == null || head.getObjectId() == null)
  809. throw new RefNotFoundException(MessageFormat.format(
  810. JGitText.get().refNotResolved, Constants.HEAD));
  811. ObjectId headId = head.getObjectId();
  812. if (headId == null)
  813. throw new RefNotFoundException(MessageFormat.format(
  814. JGitText.get().refNotResolved, Constants.HEAD));
  815. RevCommit headCommit = walk.lookupCommit(headId);
  816. if (walk.isMergedInto(newCommit, headCommit))
  817. return newCommit;
  818. String headName;
  819. if (head.isSymbolic())
  820. headName = head.getTarget().getName();
  821. else
  822. headName = head.getObjectId().getName();
  823. return tryFastForward(headName, headCommit, newCommit);
  824. }
  825. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  826. RevCommit newCommit) throws IOException, GitAPIException {
  827. boolean tryRebase = false;
  828. for (RevCommit parentCommit : newCommit.getParents())
  829. if (parentCommit.equals(oldCommit))
  830. tryRebase = true;
  831. if (!tryRebase)
  832. return null;
  833. CheckoutCommand co = new CheckoutCommand(repo);
  834. try {
  835. co.setName(newCommit.name()).call();
  836. if (headName.startsWith(Constants.R_HEADS)) {
  837. RefUpdate rup = repo.updateRef(headName);
  838. rup.setExpectedOldObjectId(oldCommit);
  839. rup.setNewObjectId(newCommit);
  840. rup.setRefLogMessage("Fast-foward from " + oldCommit.name() //$NON-NLS-1$
  841. + " to " + newCommit.name(), false); //$NON-NLS-1$
  842. Result res = rup.update(walk);
  843. switch (res) {
  844. case FAST_FORWARD:
  845. case NO_CHANGE:
  846. case FORCED:
  847. break;
  848. default:
  849. throw new IOException("Could not fast-forward"); //$NON-NLS-1$
  850. }
  851. }
  852. return newCommit;
  853. } catch (RefAlreadyExistsException e) {
  854. throw new JGitInternalException(e.getMessage(), e);
  855. } catch (RefNotFoundException e) {
  856. throw new JGitInternalException(e.getMessage(), e);
  857. } catch (InvalidRefNameException e) {
  858. throw new JGitInternalException(e.getMessage(), e);
  859. } catch (CheckoutConflictException e) {
  860. throw new JGitInternalException(e.getMessage(), e);
  861. }
  862. }
  863. private void checkParameters() throws WrongRepositoryStateException {
  864. if (this.operation == Operation.PROCESS_STEPS) {
  865. if (rebaseState.getFile(DONE).exists())
  866. throw new WrongRepositoryStateException(MessageFormat.format(
  867. JGitText.get().wrongRepositoryState, repo
  868. .getRepositoryState().name()));
  869. }
  870. if (this.operation != Operation.BEGIN) {
  871. // these operations are only possible while in a rebasing state
  872. switch (repo.getRepositoryState()) {
  873. case REBASING_INTERACTIVE:
  874. case REBASING:
  875. case REBASING_REBASING:
  876. case REBASING_MERGE:
  877. break;
  878. default:
  879. throw new WrongRepositoryStateException(MessageFormat.format(
  880. JGitText.get().wrongRepositoryState, repo
  881. .getRepositoryState().name()));
  882. }
  883. } else
  884. switch (repo.getRepositoryState()) {
  885. case SAFE:
  886. if (this.upstreamCommit == null)
  887. throw new JGitInternalException(MessageFormat
  888. .format(JGitText.get().missingRequiredParameter,
  889. "upstream"));
  890. return;
  891. default:
  892. throw new WrongRepositoryStateException(MessageFormat.format(
  893. JGitText.get().wrongRepositoryState, repo
  894. .getRepositoryState().name()));
  895. }
  896. }
  897. private RebaseResult abort(RebaseResult result) throws IOException {
  898. try {
  899. ObjectId origHead = repo.readOrigHead();
  900. String commitId = origHead != null ? origHead.name() : null;
  901. monitor.beginTask(MessageFormat.format(
  902. JGitText.get().abortingRebase, commitId),
  903. ProgressMonitor.UNKNOWN);
  904. DirCacheCheckout dco;
  905. if (commitId == null)
  906. throw new JGitInternalException(
  907. JGitText.get().abortingRebaseFailedNoOrigHead);
  908. ObjectId id = repo.resolve(commitId);
  909. RevCommit commit = walk.parseCommit(id);
  910. if (result.getStatus().equals(Status.FAILED)) {
  911. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  912. dco = new DirCacheCheckout(repo, head.getTree(),
  913. repo.lockDirCache(), commit.getTree());
  914. } else {
  915. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  916. commit.getTree());
  917. }
  918. dco.setFailOnConflict(false);
  919. dco.checkout();
  920. walk.release();
  921. } finally {
  922. monitor.endTask();
  923. }
  924. try {
  925. String headName = rebaseState.readFile(HEAD_NAME);
  926. if (headName.startsWith(Constants.R_REFS)) {
  927. monitor.beginTask(MessageFormat.format(
  928. JGitText.get().resettingHead, headName),
  929. ProgressMonitor.UNKNOWN);
  930. // update the HEAD
  931. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  932. refUpdate.setRefLogMessage("rebase: aborting", false); //$NON-NLS-1$
  933. Result res = refUpdate.link(headName);
  934. switch (res) {
  935. case FAST_FORWARD:
  936. case FORCED:
  937. case NO_CHANGE:
  938. break;
  939. default:
  940. throw new JGitInternalException(
  941. JGitText.get().abortingRebaseFailed);
  942. }
  943. }
  944. // cleanup the files
  945. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  946. repo.writeCherryPickHead(null);
  947. return result;
  948. } finally {
  949. monitor.endTask();
  950. }
  951. }
  952. private boolean checkoutCommit(String headName, RevCommit commit)
  953. throws IOException,
  954. CheckoutConflictException {
  955. try {
  956. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  957. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  958. repo.lockDirCache(), commit.getTree());
  959. dco.setFailOnConflict(true);
  960. try {
  961. dco.checkout();
  962. } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  963. throw new CheckoutConflictException(dco.getConflicts(), cce);
  964. }
  965. // update the HEAD
  966. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  967. refUpdate.setExpectedOldObjectId(head);
  968. refUpdate.setNewObjectId(commit);
  969. refUpdate.setRefLogMessage(
  970. "checkout: moving from " //$NON-NLS-1$
  971. + Repository.shortenRefName(headName)
  972. + " to " + commit.getName(), false); //$NON-NLS-1$
  973. Result res = refUpdate.forceUpdate();
  974. switch (res) {
  975. case FAST_FORWARD:
  976. case NO_CHANGE:
  977. case FORCED:
  978. break;
  979. default:
  980. throw new IOException("Could not rewind to upstream commit");
  981. }
  982. } finally {
  983. walk.release();
  984. monitor.endTask();
  985. }
  986. return true;
  987. }
  988. /**
  989. * @param upstream
  990. * the upstream commit
  991. * @return {@code this}
  992. */
  993. public RebaseCommand setUpstream(RevCommit upstream) {
  994. this.upstreamCommit = upstream;
  995. this.upstreamCommitName = upstream.name();
  996. return this;
  997. }
  998. /**
  999. * @param upstream
  1000. * id of the upstream commit
  1001. * @return {@code this}
  1002. */
  1003. public RebaseCommand setUpstream(AnyObjectId upstream) {
  1004. try {
  1005. this.upstreamCommit = walk.parseCommit(upstream);
  1006. this.upstreamCommitName = upstream.name();
  1007. } catch (IOException e) {
  1008. throw new JGitInternalException(MessageFormat.format(
  1009. JGitText.get().couldNotReadObjectWhileParsingCommit,
  1010. upstream.name()), e);
  1011. }
  1012. return this;
  1013. }
  1014. /**
  1015. * @param upstream
  1016. * the upstream branch
  1017. * @return {@code this}
  1018. * @throws RefNotFoundException
  1019. */
  1020. public RebaseCommand setUpstream(String upstream)
  1021. throws RefNotFoundException {
  1022. try {
  1023. ObjectId upstreamId = repo.resolve(upstream);
  1024. if (upstreamId == null)
  1025. throw new RefNotFoundException(MessageFormat.format(JGitText
  1026. .get().refNotResolved, upstream));
  1027. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  1028. upstreamCommitName = upstream;
  1029. return this;
  1030. } catch (IOException ioe) {
  1031. throw new JGitInternalException(ioe.getMessage(), ioe);
  1032. }
  1033. }
  1034. /**
  1035. * Optionally override the name of the upstream. If this is used, it has to
  1036. * come after any {@link #setUpstream} call.
  1037. *
  1038. * @param upstreamName
  1039. * the name which will be used to refer to upstream in conflicts
  1040. * @return {@code this}
  1041. */
  1042. public RebaseCommand setUpstreamName(String upstreamName) {
  1043. if (upstreamCommit == null) {
  1044. throw new IllegalStateException(
  1045. "setUpstreamName must be called after setUpstream.");
  1046. }
  1047. this.upstreamCommitName = upstreamName;
  1048. return this;
  1049. }
  1050. /**
  1051. * @param operation
  1052. * the operation to perform
  1053. * @return {@code this}
  1054. */
  1055. public RebaseCommand setOperation(Operation operation) {
  1056. this.operation = operation;
  1057. return this;
  1058. }
  1059. /**
  1060. * @param monitor
  1061. * a progress monitor
  1062. * @return this instance
  1063. */
  1064. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  1065. this.monitor = monitor;
  1066. return this;
  1067. }
  1068. /**
  1069. * Enables interactive rebase
  1070. * <p>
  1071. * Does not stop after initialization of interactive rebase. This is
  1072. * equivalent to
  1073. * {@link RebaseCommand#runInteractively(InteractiveHandler, boolean)
  1074. * runInteractively(handler, false)};
  1075. * </p>
  1076. *
  1077. * @param handler
  1078. * @return this
  1079. */
  1080. public RebaseCommand runInteractively(InteractiveHandler handler) {
  1081. return runInteractively(handler, false);
  1082. }
  1083. /**
  1084. * Enables interactive rebase
  1085. * <p>
  1086. * If stopAfterRebaseInteractiveInitialization is {@code true} the rebase
  1087. * stops after initialization of interactive rebase returning
  1088. * {@link RebaseResult#INTERACTIVE_PREPARED_RESULT}
  1089. * </p>
  1090. *
  1091. * @param handler
  1092. * @param stopAfterRebaseInteractiveInitialization
  1093. * if {@code true} the rebase stops after initialization
  1094. * @return this instance
  1095. * @since 3.2
  1096. */
  1097. public RebaseCommand runInteractively(InteractiveHandler handler,
  1098. final boolean stopAfterRebaseInteractiveInitialization) {
  1099. this.stopAfterInitialization = stopAfterRebaseInteractiveInitialization;
  1100. this.interactiveHandler = handler;
  1101. return this;
  1102. }
  1103. /**
  1104. * Allows configure rebase interactive process and modify commit message
  1105. */
  1106. public interface InteractiveHandler {
  1107. /**
  1108. * Given list of {@code steps} should be modified according to user
  1109. * rebase configuration
  1110. * @param steps
  1111. * initial configuration of rebase interactive
  1112. */
  1113. void prepareSteps(List<RebaseTodoLine> steps);
  1114. /**
  1115. * Used for editing commit message on REWORD
  1116. *
  1117. * @param commit
  1118. * @return new commit message
  1119. */
  1120. String modifyCommitMessage(String commit);
  1121. }
  1122. PersonIdent parseAuthor(byte[] raw) {
  1123. if (raw.length == 0)
  1124. return null;
  1125. Map<String, String> keyValueMap = new HashMap<String, String>();
  1126. for (int p = 0; p < raw.length;) {
  1127. int end = RawParseUtils.nextLF(raw, p);
  1128. if (end == p)
  1129. break;
  1130. int equalsIndex = RawParseUtils.next(raw, p, '=');
  1131. if (equalsIndex == end)
  1132. break;
  1133. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  1134. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  1135. p = end;
  1136. keyValueMap.put(key, value);
  1137. }
  1138. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  1139. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  1140. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  1141. // the time is saved as <seconds since 1970> <timezone offset>
  1142. int timeStart = 0;
  1143. if (time.startsWith("@")) //$NON-NLS-1$
  1144. timeStart = 1;
  1145. else
  1146. timeStart = 0;
  1147. long when = Long
  1148. .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
  1149. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  1150. int multiplier = -1;
  1151. if (tzOffsetString.charAt(0) == '+')
  1152. multiplier = 1;
  1153. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  1154. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  1155. // this is in format (+/-)HHMM (hours and minutes)
  1156. // we need to convert into minutes
  1157. int tz = (hours * 60 + minutes) * multiplier;
  1158. if (name != null && email != null)
  1159. return new PersonIdent(name, email, when, tz);
  1160. return null;
  1161. }
  1162. private static class RebaseState {
  1163. private final File repoDirectory;
  1164. private File dir;
  1165. public RebaseState(File repoDirectory) {
  1166. this.repoDirectory = repoDirectory;
  1167. }
  1168. public File getDir() {
  1169. if (dir == null) {
  1170. File rebaseApply = new File(repoDirectory, REBASE_APPLY);
  1171. if (rebaseApply.exists()) {
  1172. dir = rebaseApply;
  1173. } else {
  1174. File rebaseMerge = new File(repoDirectory, REBASE_MERGE);
  1175. dir = rebaseMerge;
  1176. }
  1177. }
  1178. return dir;
  1179. }
  1180. public String readFile(String name) throws IOException {
  1181. return readFile(getDir(), name);
  1182. }
  1183. public void createFile(String name, String content) throws IOException {
  1184. createFile(getDir(), name, content);
  1185. }
  1186. public File getFile(String name) {
  1187. return new File(getDir(), name);
  1188. }
  1189. public String getPath(String name) {
  1190. return (getDir().getName() + "/" + name); //$NON-NLS-1$
  1191. }
  1192. private static String readFile(File directory, String fileName)
  1193. throws IOException {
  1194. byte[] content = IO.readFully(new File(directory, fileName));
  1195. // strip off the last LF
  1196. int end = RawParseUtils.prevLF(content, content.length);
  1197. return RawParseUtils.decode(content, 0, end + 1);
  1198. }
  1199. private static void createFile(File parentDir, String name,
  1200. String content)
  1201. throws IOException {
  1202. File file = new File(parentDir, name);
  1203. FileOutputStream fos = new FileOutputStream(file);
  1204. try {
  1205. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1206. fos.write('\n');
  1207. } finally {
  1208. fos.close();
  1209. }
  1210. }
  1211. }
  1212. }