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

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