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

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