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

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