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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686
  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).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).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()
  703. .setMessage(commitMessage).setAmend(true)
  704. .call();
  705. }
  706. return retNewHead;
  707. }
  708. private static String stripCommentLines(String commitMessage) {
  709. StringBuilder result = new StringBuilder();
  710. for (String line : commitMessage.split("\n")) { //$NON-NLS-1$
  711. if (!line.trim().startsWith("#")) //$NON-NLS-1$
  712. result.append(line).append("\n"); //$NON-NLS-1$
  713. }
  714. if (!commitMessage.endsWith("\n")) //$NON-NLS-1$
  715. result.deleteCharAt(result.length() - 1);
  716. return result.toString();
  717. }
  718. @SuppressWarnings("nls")
  719. private static String composeSquashMessage(boolean isSquash,
  720. RevCommit commitToPick, String currSquashMessage, int count) {
  721. StringBuilder sb = new StringBuilder();
  722. String ordinal = getOrdinal(count);
  723. sb.setLength(0);
  724. sb.append("# This is a combination of ").append(count)
  725. .append(" commits.\n");
  726. // Add the previous message without header (i.e first line)
  727. sb.append(currSquashMessage.substring(currSquashMessage.indexOf("\n") + 1));
  728. sb.append("\n");
  729. if (isSquash) {
  730. sb.append("# This is the ").append(count).append(ordinal)
  731. .append(" commit message:\n");
  732. sb.append(commitToPick.getFullMessage());
  733. } else {
  734. sb.append("# The ").append(count).append(ordinal)
  735. .append(" commit message will be skipped:\n# ");
  736. sb.append(commitToPick.getFullMessage().replaceAll("([\n\r])",
  737. "$1# "));
  738. }
  739. return sb.toString();
  740. }
  741. private static String getOrdinal(int count) {
  742. switch (count % 10) {
  743. case 1:
  744. return "st"; //$NON-NLS-1$
  745. case 2:
  746. return "nd"; //$NON-NLS-1$
  747. case 3:
  748. return "rd"; //$NON-NLS-1$
  749. default:
  750. return "th"; //$NON-NLS-1$
  751. }
  752. }
  753. /**
  754. * Parse the count from squashed commit messages
  755. *
  756. * @param currSquashMessage
  757. * the squashed commit message to be parsed
  758. * @return the count of squashed messages in the given string
  759. */
  760. static int parseSquashFixupSequenceCount(String currSquashMessage) {
  761. String regex = "This is a combination of (.*) commits"; //$NON-NLS-1$
  762. String firstLine = currSquashMessage.substring(0,
  763. currSquashMessage.indexOf("\n")); //$NON-NLS-1$
  764. Pattern pattern = Pattern.compile(regex);
  765. Matcher matcher = pattern.matcher(firstLine);
  766. if (!matcher.find())
  767. throw new IllegalArgumentException();
  768. return Integer.parseInt(matcher.group(1));
  769. }
  770. private void initializeSquashFixupFile(String messageFile,
  771. String fullMessage) throws IOException {
  772. rebaseState
  773. .createFile(
  774. messageFile,
  775. "# This is a combination of 1 commits.\n# The first commit's message is:\n" + fullMessage); //$NON-NLS-1$);
  776. }
  777. private String getOurCommitName() {
  778. // If onto is different from upstream, this should say "onto", but
  779. // RebaseCommand doesn't support a different "onto" at the moment.
  780. String ourCommitName = "Upstream, based on " //$NON-NLS-1$
  781. + Repository.shortenRefName(upstreamCommitName);
  782. return ourCommitName;
  783. }
  784. private void updateHead(String headName, RevCommit aNewHead, RevCommit onto)
  785. throws IOException {
  786. // point the previous head (if any) to the new commit
  787. if (headName.startsWith(Constants.R_REFS)) {
  788. RefUpdate rup = repo.updateRef(headName);
  789. rup.setNewObjectId(aNewHead);
  790. rup.setRefLogMessage("rebase finished: " + headName + " onto " //$NON-NLS-1$ //$NON-NLS-2$
  791. + onto.getName(), false);
  792. Result res = rup.forceUpdate();
  793. switch (res) {
  794. case FAST_FORWARD:
  795. case FORCED:
  796. case NO_CHANGE:
  797. break;
  798. default:
  799. throw new JGitInternalException("Updating HEAD failed");
  800. }
  801. rup = repo.updateRef(Constants.HEAD);
  802. rup.setRefLogMessage("rebase finished: returning to " + headName, //$NON-NLS-1$
  803. false);
  804. res = rup.link(headName);
  805. switch (res) {
  806. case FAST_FORWARD:
  807. case FORCED:
  808. case NO_CHANGE:
  809. break;
  810. default:
  811. throw new JGitInternalException("Updating HEAD failed");
  812. }
  813. }
  814. }
  815. private RevCommit checkoutCurrentHead() throws IOException, NoHeadException {
  816. ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  817. if (headTree == null)
  818. throw new NoHeadException(
  819. JGitText.get().cannotRebaseWithoutCurrentHead);
  820. DirCache dc = repo.lockDirCache();
  821. try {
  822. DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
  823. dco.setFailOnConflict(false);
  824. boolean needsDeleteFiles = dco.checkout();
  825. if (needsDeleteFiles) {
  826. List<String> fileList = dco.getToBeDeleted();
  827. for (String filePath : fileList) {
  828. File fileToDelete = new File(repo.getWorkTree(), filePath);
  829. if (repo.getFS().exists(fileToDelete))
  830. FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
  831. | FileUtils.RETRY);
  832. }
  833. }
  834. } finally {
  835. dc.unlock();
  836. }
  837. RevWalk rw = new RevWalk(repo);
  838. RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
  839. rw.release();
  840. return commit;
  841. }
  842. /**
  843. * @return the commit if we had to do a commit, otherwise null
  844. * @throws GitAPIException
  845. * @throws IOException
  846. */
  847. private RevCommit continueRebase() throws GitAPIException, IOException {
  848. // if there are still conflicts, we throw a specific Exception
  849. DirCache dc = repo.readDirCache();
  850. boolean hasUnmergedPaths = dc.hasUnmergedPaths();
  851. if (hasUnmergedPaths)
  852. throw new UnmergedPathsException();
  853. // determine whether we need to commit
  854. TreeWalk treeWalk = new TreeWalk(repo);
  855. treeWalk.reset();
  856. treeWalk.setRecursive(true);
  857. treeWalk.addTree(new DirCacheIterator(dc));
  858. ObjectId id = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  859. if (id == null)
  860. throw new NoHeadException(
  861. JGitText.get().cannotRebaseWithoutCurrentHead);
  862. treeWalk.addTree(id);
  863. treeWalk.setFilter(TreeFilter.ANY_DIFF);
  864. boolean needsCommit = treeWalk.next();
  865. treeWalk.release();
  866. if (needsCommit) {
  867. CommitCommand commit = new Git(repo).commit();
  868. commit.setMessage(rebaseState.readFile(MESSAGE));
  869. commit.setAuthor(parseAuthor());
  870. return commit.call();
  871. }
  872. return null;
  873. }
  874. private PersonIdent parseAuthor() throws IOException {
  875. File authorScriptFile = rebaseState.getFile(AUTHOR_SCRIPT);
  876. byte[] raw;
  877. try {
  878. raw = IO.readFully(authorScriptFile);
  879. } catch (FileNotFoundException notFound) {
  880. return null;
  881. }
  882. return parseAuthor(raw);
  883. }
  884. private RebaseResult stop(RevCommit commitToPick, RebaseResult.Status status)
  885. throws IOException {
  886. PersonIdent author = commitToPick.getAuthorIdent();
  887. String authorScript = toAuthorScript(author);
  888. rebaseState.createFile(AUTHOR_SCRIPT, authorScript);
  889. rebaseState.createFile(MESSAGE, commitToPick.getFullMessage());
  890. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  891. DiffFormatter df = new DiffFormatter(bos);
  892. df.setRepository(repo);
  893. df.format(commitToPick.getParent(0), commitToPick);
  894. rebaseState.createFile(PATCH, new String(bos.toByteArray(),
  895. Constants.CHARACTER_ENCODING));
  896. rebaseState.createFile(STOPPED_SHA,
  897. repo.newObjectReader()
  898. .abbreviate(
  899. commitToPick).name());
  900. // Remove cherry pick state file created by CherryPickCommand, it's not
  901. // needed for rebase
  902. repo.writeCherryPickHead(null);
  903. return RebaseResult.result(status, commitToPick);
  904. }
  905. String toAuthorScript(PersonIdent author) {
  906. StringBuilder sb = new StringBuilder(100);
  907. sb.append(GIT_AUTHOR_NAME);
  908. sb.append("='"); //$NON-NLS-1$
  909. sb.append(author.getName());
  910. sb.append("'\n"); //$NON-NLS-1$
  911. sb.append(GIT_AUTHOR_EMAIL);
  912. sb.append("='"); //$NON-NLS-1$
  913. sb.append(author.getEmailAddress());
  914. sb.append("'\n"); //$NON-NLS-1$
  915. // the command line uses the "external String"
  916. // representation for date and timezone
  917. sb.append(GIT_AUTHOR_DATE);
  918. sb.append("='"); //$NON-NLS-1$
  919. sb.append("@"); // @ for time in seconds since 1970 //$NON-NLS-1$
  920. String externalString = author.toExternalString();
  921. sb
  922. .append(externalString.substring(externalString
  923. .lastIndexOf('>') + 2));
  924. sb.append("'\n"); //$NON-NLS-1$
  925. return sb.toString();
  926. }
  927. /**
  928. * Removes the number of lines given in the parameter from the
  929. * <code>git-rebase-todo</code> file but preserves comments and other lines
  930. * that can not be parsed as steps
  931. *
  932. * @param numSteps
  933. * @throws IOException
  934. */
  935. private void popSteps(int numSteps) throws IOException {
  936. if (numSteps == 0)
  937. return;
  938. List<RebaseTodoLine> todoLines = new LinkedList<RebaseTodoLine>();
  939. List<RebaseTodoLine> poppedLines = new LinkedList<RebaseTodoLine>();
  940. for (RebaseTodoLine line : repo.readRebaseTodo(
  941. rebaseState.getPath(GIT_REBASE_TODO), true)) {
  942. if (poppedLines.size() >= numSteps
  943. || RebaseTodoLine.Action.COMMENT.equals(line.getAction()))
  944. todoLines.add(line);
  945. else
  946. poppedLines.add(line);
  947. }
  948. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  949. todoLines, false);
  950. if (poppedLines.size() > 0) {
  951. repo.writeRebaseTodoFile(rebaseState.getPath(DONE), poppedLines,
  952. true);
  953. }
  954. }
  955. private RebaseResult initFilesAndRewind() throws IOException,
  956. GitAPIException {
  957. // we need to store everything into files so that we can implement
  958. // --skip, --continue, and --abort
  959. Ref head = getHead();
  960. String headName = getHeadName(head);
  961. ObjectId headId = head.getObjectId();
  962. if (headId == null)
  963. throw new RefNotFoundException(MessageFormat.format(
  964. JGitText.get().refNotResolved, Constants.HEAD));
  965. RevCommit headCommit = walk.lookupCommit(headId);
  966. RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());
  967. if (!isInteractive() && walk.isMergedInto(upstream, headCommit))
  968. return RebaseResult.UP_TO_DATE_RESULT;
  969. else if (!isInteractive() && walk.isMergedInto(headCommit, upstream)) {
  970. // head is already merged into upstream, fast-foward
  971. monitor.beginTask(MessageFormat.format(
  972. JGitText.get().resettingHead,
  973. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  974. checkoutCommit(headName, upstreamCommit);
  975. monitor.endTask();
  976. updateHead(headName, upstreamCommit, upstream);
  977. return RebaseResult.FAST_FORWARD_RESULT;
  978. }
  979. monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
  980. ProgressMonitor.UNKNOWN);
  981. // create the folder for the meta information
  982. FileUtils.mkdir(rebaseState.getDir(), true);
  983. repo.writeOrigHead(headId);
  984. rebaseState.createFile(REBASE_HEAD, headId.name());
  985. rebaseState.createFile(HEAD_NAME, headName);
  986. rebaseState.createFile(ONTO, upstreamCommit.name());
  987. rebaseState.createFile(ONTO_NAME, upstreamCommitName);
  988. rebaseState.createFile(INTERACTIVE, ""); //$NON-NLS-1$
  989. rebaseState.createFile(QUIET, ""); //$NON-NLS-1$
  990. ArrayList<RebaseTodoLine> toDoSteps = new ArrayList<RebaseTodoLine>();
  991. toDoSteps.add(new RebaseTodoLine("# Created by EGit: rebasing " + headId.name() //$NON-NLS-1$
  992. + " onto " + upstreamCommit.name())); //$NON-NLS-1$
  993. // determine the commits to be applied
  994. List<RevCommit> cherryPickList = calculatePickList(headCommit);
  995. ObjectReader reader = walk.getObjectReader();
  996. for (RevCommit commit : cherryPickList)
  997. toDoSteps.add(new RebaseTodoLine(Action.PICK, reader
  998. .abbreviate(commit), commit.getShortMessage()));
  999. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  1000. toDoSteps, false);
  1001. monitor.endTask();
  1002. // we rewind to the upstream commit
  1003. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  1004. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  1005. boolean checkoutOk = false;
  1006. try {
  1007. checkoutOk = checkoutCommit(headName, upstreamCommit);
  1008. } finally {
  1009. if (!checkoutOk)
  1010. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1011. }
  1012. monitor.endTask();
  1013. return null;
  1014. }
  1015. private List<RevCommit> calculatePickList(RevCommit headCommit)
  1016. throws GitAPIException, NoHeadException, IOException {
  1017. LogCommand cmd = new Git(repo).log().addRange(upstreamCommit,
  1018. headCommit);
  1019. Iterable<RevCommit> commitsToUse = cmd.call();
  1020. List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
  1021. for (RevCommit commit : commitsToUse) {
  1022. if (preserveMerges || commit.getParentCount() == 1)
  1023. cherryPickList.add(commit);
  1024. }
  1025. Collections.reverse(cherryPickList);
  1026. if (preserveMerges) {
  1027. // When preserving merges we only rewrite commits which have at
  1028. // least one parent that is itself rewritten (or a merge base)
  1029. File rewrittenDir = rebaseState.getRewrittenDir();
  1030. FileUtils.mkdir(rewrittenDir, false);
  1031. walk.reset();
  1032. walk.setRevFilter(RevFilter.MERGE_BASE);
  1033. walk.markStart(upstreamCommit);
  1034. walk.markStart(headCommit);
  1035. RevCommit base;
  1036. while ((base = walk.next()) != null)
  1037. RebaseState.createFile(rewrittenDir, base.getName(),
  1038. upstreamCommit.getName());
  1039. Iterator<RevCommit> iterator = cherryPickList.iterator();
  1040. pickLoop: while(iterator.hasNext()){
  1041. RevCommit commit = iterator.next();
  1042. for (int i = 0; i < commit.getParentCount(); i++) {
  1043. boolean parentRewritten = new File(rewrittenDir, commit
  1044. .getParent(i).getName()).exists();
  1045. if (parentRewritten) {
  1046. new File(rewrittenDir, commit.getName()).createNewFile();
  1047. continue pickLoop;
  1048. }
  1049. }
  1050. // commit is only merged in, needs not be rewritten
  1051. iterator.remove();
  1052. }
  1053. }
  1054. return cherryPickList;
  1055. }
  1056. private static String getHeadName(Ref head) {
  1057. String headName;
  1058. if (head.isSymbolic())
  1059. headName = head.getTarget().getName();
  1060. else
  1061. headName = head.getObjectId().getName();
  1062. return headName;
  1063. }
  1064. private Ref getHead() throws IOException, RefNotFoundException {
  1065. Ref head = repo.getRef(Constants.HEAD);
  1066. if (head == null || head.getObjectId() == null)
  1067. throw new RefNotFoundException(MessageFormat.format(
  1068. JGitText.get().refNotResolved, Constants.HEAD));
  1069. return head;
  1070. }
  1071. private boolean isInteractive() {
  1072. return interactiveHandler != null;
  1073. }
  1074. /**
  1075. * checks if we can fast-forward and returns the new head if it is possible
  1076. *
  1077. * @param newCommit
  1078. * @return the new head, or null
  1079. * @throws IOException
  1080. * @throws GitAPIException
  1081. */
  1082. public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
  1083. GitAPIException {
  1084. Ref head = getHead();
  1085. ObjectId headId = head.getObjectId();
  1086. if (headId == null)
  1087. throw new RefNotFoundException(MessageFormat.format(
  1088. JGitText.get().refNotResolved, Constants.HEAD));
  1089. RevCommit headCommit = walk.lookupCommit(headId);
  1090. if (walk.isMergedInto(newCommit, headCommit))
  1091. return newCommit;
  1092. String headName = getHeadName(head);
  1093. return tryFastForward(headName, headCommit, newCommit);
  1094. }
  1095. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  1096. RevCommit newCommit) throws IOException, GitAPIException {
  1097. boolean tryRebase = false;
  1098. for (RevCommit parentCommit : newCommit.getParents())
  1099. if (parentCommit.equals(oldCommit))
  1100. tryRebase = true;
  1101. if (!tryRebase)
  1102. return null;
  1103. CheckoutCommand co = new CheckoutCommand(repo);
  1104. try {
  1105. co.setName(newCommit.name()).call();
  1106. if (headName.startsWith(Constants.R_HEADS)) {
  1107. RefUpdate rup = repo.updateRef(headName);
  1108. rup.setExpectedOldObjectId(oldCommit);
  1109. rup.setNewObjectId(newCommit);
  1110. rup.setRefLogMessage("Fast-foward from " + oldCommit.name() //$NON-NLS-1$
  1111. + " to " + newCommit.name(), false); //$NON-NLS-1$
  1112. Result res = rup.update(walk);
  1113. switch (res) {
  1114. case FAST_FORWARD:
  1115. case NO_CHANGE:
  1116. case FORCED:
  1117. break;
  1118. default:
  1119. throw new IOException("Could not fast-forward"); //$NON-NLS-1$
  1120. }
  1121. }
  1122. return newCommit;
  1123. } catch (RefAlreadyExistsException e) {
  1124. throw new JGitInternalException(e.getMessage(), e);
  1125. } catch (RefNotFoundException e) {
  1126. throw new JGitInternalException(e.getMessage(), e);
  1127. } catch (InvalidRefNameException e) {
  1128. throw new JGitInternalException(e.getMessage(), e);
  1129. } catch (CheckoutConflictException e) {
  1130. throw new JGitInternalException(e.getMessage(), e);
  1131. }
  1132. }
  1133. private void checkParameters() throws WrongRepositoryStateException {
  1134. if (this.operation == Operation.PROCESS_STEPS) {
  1135. if (rebaseState.getFile(DONE).exists())
  1136. throw new WrongRepositoryStateException(MessageFormat.format(
  1137. JGitText.get().wrongRepositoryState, repo
  1138. .getRepositoryState().name()));
  1139. }
  1140. if (this.operation != Operation.BEGIN) {
  1141. // these operations are only possible while in a rebasing state
  1142. switch (repo.getRepositoryState()) {
  1143. case REBASING_INTERACTIVE:
  1144. case REBASING:
  1145. case REBASING_REBASING:
  1146. case REBASING_MERGE:
  1147. break;
  1148. default:
  1149. throw new WrongRepositoryStateException(MessageFormat.format(
  1150. JGitText.get().wrongRepositoryState, repo
  1151. .getRepositoryState().name()));
  1152. }
  1153. } else
  1154. switch (repo.getRepositoryState()) {
  1155. case SAFE:
  1156. if (this.upstreamCommit == null)
  1157. throw new JGitInternalException(MessageFormat
  1158. .format(JGitText.get().missingRequiredParameter,
  1159. "upstream"));
  1160. return;
  1161. default:
  1162. throw new WrongRepositoryStateException(MessageFormat.format(
  1163. JGitText.get().wrongRepositoryState, repo
  1164. .getRepositoryState().name()));
  1165. }
  1166. }
  1167. private RebaseResult abort(RebaseResult result) throws IOException,
  1168. GitAPIException {
  1169. try {
  1170. ObjectId origHead = repo.readOrigHead();
  1171. String commitId = origHead != null ? origHead.name() : null;
  1172. monitor.beginTask(MessageFormat.format(
  1173. JGitText.get().abortingRebase, commitId),
  1174. ProgressMonitor.UNKNOWN);
  1175. DirCacheCheckout dco;
  1176. if (commitId == null)
  1177. throw new JGitInternalException(
  1178. JGitText.get().abortingRebaseFailedNoOrigHead);
  1179. ObjectId id = repo.resolve(commitId);
  1180. RevCommit commit = walk.parseCommit(id);
  1181. if (result.getStatus().equals(Status.FAILED)) {
  1182. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1183. dco = new DirCacheCheckout(repo, head.getTree(),
  1184. repo.lockDirCache(), commit.getTree());
  1185. } else {
  1186. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  1187. commit.getTree());
  1188. }
  1189. dco.setFailOnConflict(false);
  1190. dco.checkout();
  1191. walk.release();
  1192. } finally {
  1193. monitor.endTask();
  1194. }
  1195. try {
  1196. String headName = rebaseState.readFile(HEAD_NAME);
  1197. monitor.beginTask(MessageFormat.format(
  1198. JGitText.get().resettingHead, headName),
  1199. ProgressMonitor.UNKNOWN);
  1200. Result res = null;
  1201. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  1202. refUpdate.setRefLogMessage("rebase: aborting", false); //$NON-NLS-1$
  1203. if (headName.startsWith(Constants.R_REFS)) {
  1204. // update the HEAD
  1205. res = refUpdate.link(headName);
  1206. } else {
  1207. refUpdate.setNewObjectId(repo.readOrigHead());
  1208. res = refUpdate.forceUpdate();
  1209. }
  1210. switch (res) {
  1211. case FAST_FORWARD:
  1212. case FORCED:
  1213. case NO_CHANGE:
  1214. break;
  1215. default:
  1216. throw new JGitInternalException(
  1217. JGitText.get().abortingRebaseFailed);
  1218. }
  1219. boolean stashConflicts = autoStashApply();
  1220. // cleanup the files
  1221. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1222. repo.writeCherryPickHead(null);
  1223. repo.writeMergeHeads(null);
  1224. if (stashConflicts)
  1225. return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
  1226. return result;
  1227. } finally {
  1228. monitor.endTask();
  1229. }
  1230. }
  1231. private boolean checkoutCommit(String headName, RevCommit commit)
  1232. throws IOException,
  1233. CheckoutConflictException {
  1234. try {
  1235. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1236. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  1237. repo.lockDirCache(), commit.getTree());
  1238. dco.setFailOnConflict(true);
  1239. try {
  1240. dco.checkout();
  1241. } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  1242. throw new CheckoutConflictException(dco.getConflicts(), cce);
  1243. }
  1244. // update the HEAD
  1245. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  1246. refUpdate.setExpectedOldObjectId(head);
  1247. refUpdate.setNewObjectId(commit);
  1248. refUpdate.setRefLogMessage(
  1249. "checkout: moving from " //$NON-NLS-1$
  1250. + Repository.shortenRefName(headName)
  1251. + " to " + commit.getName(), false); //$NON-NLS-1$
  1252. Result res = refUpdate.forceUpdate();
  1253. switch (res) {
  1254. case FAST_FORWARD:
  1255. case NO_CHANGE:
  1256. case FORCED:
  1257. break;
  1258. default:
  1259. throw new IOException("Could not rewind to upstream commit");
  1260. }
  1261. } finally {
  1262. walk.release();
  1263. monitor.endTask();
  1264. }
  1265. return true;
  1266. }
  1267. /**
  1268. * @param upstream
  1269. * the upstream commit
  1270. * @return {@code this}
  1271. */
  1272. public RebaseCommand setUpstream(RevCommit upstream) {
  1273. this.upstreamCommit = upstream;
  1274. this.upstreamCommitName = upstream.name();
  1275. return this;
  1276. }
  1277. /**
  1278. * @param upstream
  1279. * id of the upstream commit
  1280. * @return {@code this}
  1281. */
  1282. public RebaseCommand setUpstream(AnyObjectId upstream) {
  1283. try {
  1284. this.upstreamCommit = walk.parseCommit(upstream);
  1285. this.upstreamCommitName = upstream.name();
  1286. } catch (IOException e) {
  1287. throw new JGitInternalException(MessageFormat.format(
  1288. JGitText.get().couldNotReadObjectWhileParsingCommit,
  1289. upstream.name()), e);
  1290. }
  1291. return this;
  1292. }
  1293. /**
  1294. * @param upstream
  1295. * the upstream branch
  1296. * @return {@code this}
  1297. * @throws RefNotFoundException
  1298. */
  1299. public RebaseCommand setUpstream(String upstream)
  1300. throws RefNotFoundException {
  1301. try {
  1302. ObjectId upstreamId = repo.resolve(upstream);
  1303. if (upstreamId == null)
  1304. throw new RefNotFoundException(MessageFormat.format(JGitText
  1305. .get().refNotResolved, upstream));
  1306. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  1307. upstreamCommitName = upstream;
  1308. return this;
  1309. } catch (IOException ioe) {
  1310. throw new JGitInternalException(ioe.getMessage(), ioe);
  1311. }
  1312. }
  1313. /**
  1314. * Optionally override the name of the upstream. If this is used, it has to
  1315. * come after any {@link #setUpstream} call.
  1316. *
  1317. * @param upstreamName
  1318. * the name which will be used to refer to upstream in conflicts
  1319. * @return {@code this}
  1320. */
  1321. public RebaseCommand setUpstreamName(String upstreamName) {
  1322. if (upstreamCommit == null) {
  1323. throw new IllegalStateException(
  1324. "setUpstreamName must be called after setUpstream.");
  1325. }
  1326. this.upstreamCommitName = upstreamName;
  1327. return this;
  1328. }
  1329. /**
  1330. * @param operation
  1331. * the operation to perform
  1332. * @return {@code this}
  1333. */
  1334. public RebaseCommand setOperation(Operation operation) {
  1335. this.operation = operation;
  1336. return this;
  1337. }
  1338. /**
  1339. * @param monitor
  1340. * a progress monitor
  1341. * @return this instance
  1342. */
  1343. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  1344. this.monitor = monitor;
  1345. return this;
  1346. }
  1347. /**
  1348. * Enables interactive rebase
  1349. * <p>
  1350. * Does not stop after initialization of interactive rebase. This is
  1351. * equivalent to
  1352. * {@link RebaseCommand#runInteractively(InteractiveHandler, boolean)
  1353. * runInteractively(handler, false)};
  1354. * </p>
  1355. *
  1356. * @param handler
  1357. * @return this
  1358. */
  1359. public RebaseCommand runInteractively(InteractiveHandler handler) {
  1360. return runInteractively(handler, false);
  1361. }
  1362. /**
  1363. * Enables interactive rebase
  1364. * <p>
  1365. * If stopAfterRebaseInteractiveInitialization is {@code true} the rebase
  1366. * stops after initialization of interactive rebase returning
  1367. * {@link RebaseResult#INTERACTIVE_PREPARED_RESULT}
  1368. * </p>
  1369. *
  1370. * @param handler
  1371. * @param stopAfterRebaseInteractiveInitialization
  1372. * if {@code true} the rebase stops after initialization
  1373. * @return this instance
  1374. * @since 3.2
  1375. */
  1376. public RebaseCommand runInteractively(InteractiveHandler handler,
  1377. final boolean stopAfterRebaseInteractiveInitialization) {
  1378. this.stopAfterInitialization = stopAfterRebaseInteractiveInitialization;
  1379. this.interactiveHandler = handler;
  1380. return this;
  1381. }
  1382. /**
  1383. * @param strategy
  1384. * The merge strategy to use during this rebase operation.
  1385. * @return {@code this}
  1386. * @since 3.4
  1387. */
  1388. public RebaseCommand setStrategy(MergeStrategy strategy) {
  1389. this.strategy = strategy;
  1390. return this;
  1391. }
  1392. /**
  1393. * @param preserve
  1394. * True to re-create merges during rebase. Defaults to false, a
  1395. * flattening rebase.
  1396. * @return {@code this}
  1397. * @since 3.5
  1398. */
  1399. public RebaseCommand setPreserveMerges(boolean preserve) {
  1400. this.preserveMerges = preserve;
  1401. return this;
  1402. }
  1403. /**
  1404. * Allows configure rebase interactive process and modify commit message
  1405. */
  1406. public interface InteractiveHandler {
  1407. /**
  1408. * Given list of {@code steps} should be modified according to user
  1409. * rebase configuration
  1410. * @param steps
  1411. * initial configuration of rebase interactive
  1412. */
  1413. void prepareSteps(List<RebaseTodoLine> steps);
  1414. /**
  1415. * Used for editing commit message on REWORD
  1416. *
  1417. * @param commit
  1418. * @return new commit message
  1419. */
  1420. String modifyCommitMessage(String commit);
  1421. }
  1422. PersonIdent parseAuthor(byte[] raw) {
  1423. if (raw.length == 0)
  1424. return null;
  1425. Map<String, String> keyValueMap = new HashMap<String, String>();
  1426. for (int p = 0; p < raw.length;) {
  1427. int end = RawParseUtils.nextLF(raw, p);
  1428. if (end == p)
  1429. break;
  1430. int equalsIndex = RawParseUtils.next(raw, p, '=');
  1431. if (equalsIndex == end)
  1432. break;
  1433. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  1434. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  1435. p = end;
  1436. keyValueMap.put(key, value);
  1437. }
  1438. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  1439. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  1440. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  1441. // the time is saved as <seconds since 1970> <timezone offset>
  1442. int timeStart = 0;
  1443. if (time.startsWith("@")) //$NON-NLS-1$
  1444. timeStart = 1;
  1445. else
  1446. timeStart = 0;
  1447. long when = Long
  1448. .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
  1449. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  1450. int multiplier = -1;
  1451. if (tzOffsetString.charAt(0) == '+')
  1452. multiplier = 1;
  1453. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  1454. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  1455. // this is in format (+/-)HHMM (hours and minutes)
  1456. // we need to convert into minutes
  1457. int tz = (hours * 60 + minutes) * multiplier;
  1458. if (name != null && email != null)
  1459. return new PersonIdent(name, email, when, tz);
  1460. return null;
  1461. }
  1462. private static class RebaseState {
  1463. private final File repoDirectory;
  1464. private File dir;
  1465. public RebaseState(File repoDirectory) {
  1466. this.repoDirectory = repoDirectory;
  1467. }
  1468. public File getDir() {
  1469. if (dir == null) {
  1470. File rebaseApply = new File(repoDirectory, REBASE_APPLY);
  1471. if (rebaseApply.exists()) {
  1472. dir = rebaseApply;
  1473. } else {
  1474. File rebaseMerge = new File(repoDirectory, REBASE_MERGE);
  1475. dir = rebaseMerge;
  1476. }
  1477. }
  1478. return dir;
  1479. }
  1480. /**
  1481. * @return Directory with rewritten commit hashes, usually exists if
  1482. * {@link RebaseCommand#preserveMerges} is true
  1483. **/
  1484. public File getRewrittenDir() {
  1485. return new File(getDir(), REWRITTEN);
  1486. }
  1487. public String readFile(String name) throws IOException {
  1488. return readFile(getDir(), name);
  1489. }
  1490. public void createFile(String name, String content) throws IOException {
  1491. createFile(getDir(), name, content);
  1492. }
  1493. public File getFile(String name) {
  1494. return new File(getDir(), name);
  1495. }
  1496. public String getPath(String name) {
  1497. return (getDir().getName() + "/" + name); //$NON-NLS-1$
  1498. }
  1499. private static String readFile(File directory, String fileName)
  1500. throws IOException {
  1501. byte[] content = IO.readFully(new File(directory, fileName));
  1502. // strip off the last LF
  1503. int end = RawParseUtils.prevLF(content, content.length);
  1504. return RawParseUtils.decode(content, 0, end + 1);
  1505. }
  1506. private static void createFile(File parentDir, String name,
  1507. String content)
  1508. throws IOException {
  1509. File file = new File(parentDir, name);
  1510. FileOutputStream fos = new FileOutputStream(file);
  1511. try {
  1512. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1513. fos.write('\n');
  1514. } finally {
  1515. fos.close();
  1516. }
  1517. }
  1518. private static void appendToFile(File file, String content)
  1519. throws IOException {
  1520. FileOutputStream fos = new FileOutputStream(file, true);
  1521. try {
  1522. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1523. fos.write('\n');
  1524. } finally {
  1525. fos.close();
  1526. }
  1527. }
  1528. }
  1529. }