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

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