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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  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. if (isInteractive()) {
  988. rebaseState.createFile(INTERACTIVE, ""); //$NON-NLS-1$
  989. }
  990. rebaseState.createFile(QUIET, ""); //$NON-NLS-1$
  991. ArrayList<RebaseTodoLine> toDoSteps = new ArrayList<RebaseTodoLine>();
  992. toDoSteps.add(new RebaseTodoLine("# Created by EGit: rebasing " + headId.name() //$NON-NLS-1$
  993. + " onto " + upstreamCommit.name())); //$NON-NLS-1$
  994. // determine the commits to be applied
  995. List<RevCommit> cherryPickList = calculatePickList(headCommit);
  996. ObjectReader reader = walk.getObjectReader();
  997. for (RevCommit commit : cherryPickList)
  998. toDoSteps.add(new RebaseTodoLine(Action.PICK, reader
  999. .abbreviate(commit), commit.getShortMessage()));
  1000. repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  1001. toDoSteps, false);
  1002. monitor.endTask();
  1003. // we rewind to the upstream commit
  1004. monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  1005. upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  1006. boolean checkoutOk = false;
  1007. try {
  1008. checkoutOk = checkoutCommit(headName, upstreamCommit);
  1009. } finally {
  1010. if (!checkoutOk)
  1011. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1012. }
  1013. monitor.endTask();
  1014. return null;
  1015. }
  1016. private List<RevCommit> calculatePickList(RevCommit headCommit)
  1017. throws GitAPIException, NoHeadException, IOException {
  1018. LogCommand cmd = new Git(repo).log().addRange(upstreamCommit,
  1019. headCommit);
  1020. Iterable<RevCommit> commitsToUse = cmd.call();
  1021. List<RevCommit> cherryPickList = new ArrayList<RevCommit>();
  1022. for (RevCommit commit : commitsToUse) {
  1023. if (preserveMerges || commit.getParentCount() == 1)
  1024. cherryPickList.add(commit);
  1025. }
  1026. Collections.reverse(cherryPickList);
  1027. if (preserveMerges) {
  1028. // When preserving merges we only rewrite commits which have at
  1029. // least one parent that is itself rewritten (or a merge base)
  1030. File rewrittenDir = rebaseState.getRewrittenDir();
  1031. FileUtils.mkdir(rewrittenDir, false);
  1032. walk.reset();
  1033. walk.setRevFilter(RevFilter.MERGE_BASE);
  1034. walk.markStart(upstreamCommit);
  1035. walk.markStart(headCommit);
  1036. RevCommit base;
  1037. while ((base = walk.next()) != null)
  1038. RebaseState.createFile(rewrittenDir, base.getName(),
  1039. upstreamCommit.getName());
  1040. Iterator<RevCommit> iterator = cherryPickList.iterator();
  1041. pickLoop: while(iterator.hasNext()){
  1042. RevCommit commit = iterator.next();
  1043. for (int i = 0; i < commit.getParentCount(); i++) {
  1044. boolean parentRewritten = new File(rewrittenDir, commit
  1045. .getParent(i).getName()).exists();
  1046. if (parentRewritten) {
  1047. new File(rewrittenDir, commit.getName()).createNewFile();
  1048. continue pickLoop;
  1049. }
  1050. }
  1051. // commit is only merged in, needs not be rewritten
  1052. iterator.remove();
  1053. }
  1054. }
  1055. return cherryPickList;
  1056. }
  1057. private static String getHeadName(Ref head) {
  1058. String headName;
  1059. if (head.isSymbolic())
  1060. headName = head.getTarget().getName();
  1061. else
  1062. headName = head.getObjectId().getName();
  1063. return headName;
  1064. }
  1065. private Ref getHead() throws IOException, RefNotFoundException {
  1066. Ref head = repo.getRef(Constants.HEAD);
  1067. if (head == null || head.getObjectId() == null)
  1068. throw new RefNotFoundException(MessageFormat.format(
  1069. JGitText.get().refNotResolved, Constants.HEAD));
  1070. return head;
  1071. }
  1072. private boolean isInteractive() {
  1073. return interactiveHandler != null;
  1074. }
  1075. /**
  1076. * checks if we can fast-forward and returns the new head if it is possible
  1077. *
  1078. * @param newCommit
  1079. * @return the new head, or null
  1080. * @throws IOException
  1081. * @throws GitAPIException
  1082. */
  1083. public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
  1084. GitAPIException {
  1085. Ref head = getHead();
  1086. ObjectId headId = head.getObjectId();
  1087. if (headId == null)
  1088. throw new RefNotFoundException(MessageFormat.format(
  1089. JGitText.get().refNotResolved, Constants.HEAD));
  1090. RevCommit headCommit = walk.lookupCommit(headId);
  1091. if (walk.isMergedInto(newCommit, headCommit))
  1092. return newCommit;
  1093. String headName = getHeadName(head);
  1094. return tryFastForward(headName, headCommit, newCommit);
  1095. }
  1096. private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  1097. RevCommit newCommit) throws IOException, GitAPIException {
  1098. boolean tryRebase = false;
  1099. for (RevCommit parentCommit : newCommit.getParents())
  1100. if (parentCommit.equals(oldCommit))
  1101. tryRebase = true;
  1102. if (!tryRebase)
  1103. return null;
  1104. CheckoutCommand co = new CheckoutCommand(repo);
  1105. try {
  1106. co.setName(newCommit.name()).call();
  1107. if (headName.startsWith(Constants.R_HEADS)) {
  1108. RefUpdate rup = repo.updateRef(headName);
  1109. rup.setExpectedOldObjectId(oldCommit);
  1110. rup.setNewObjectId(newCommit);
  1111. rup.setRefLogMessage("Fast-forward from " + oldCommit.name() //$NON-NLS-1$
  1112. + " to " + newCommit.name(), false); //$NON-NLS-1$
  1113. Result res = rup.update(walk);
  1114. switch (res) {
  1115. case FAST_FORWARD:
  1116. case NO_CHANGE:
  1117. case FORCED:
  1118. break;
  1119. default:
  1120. throw new IOException("Could not fast-forward"); //$NON-NLS-1$
  1121. }
  1122. }
  1123. return newCommit;
  1124. } catch (RefAlreadyExistsException e) {
  1125. throw new JGitInternalException(e.getMessage(), e);
  1126. } catch (RefNotFoundException e) {
  1127. throw new JGitInternalException(e.getMessage(), e);
  1128. } catch (InvalidRefNameException e) {
  1129. throw new JGitInternalException(e.getMessage(), e);
  1130. } catch (CheckoutConflictException e) {
  1131. throw new JGitInternalException(e.getMessage(), e);
  1132. }
  1133. }
  1134. private void checkParameters() throws WrongRepositoryStateException {
  1135. if (this.operation == Operation.PROCESS_STEPS) {
  1136. if (rebaseState.getFile(DONE).exists())
  1137. throw new WrongRepositoryStateException(MessageFormat.format(
  1138. JGitText.get().wrongRepositoryState, repo
  1139. .getRepositoryState().name()));
  1140. }
  1141. if (this.operation != Operation.BEGIN) {
  1142. // these operations are only possible while in a rebasing state
  1143. switch (repo.getRepositoryState()) {
  1144. case REBASING_INTERACTIVE:
  1145. case REBASING:
  1146. case REBASING_REBASING:
  1147. case REBASING_MERGE:
  1148. break;
  1149. default:
  1150. throw new WrongRepositoryStateException(MessageFormat.format(
  1151. JGitText.get().wrongRepositoryState, repo
  1152. .getRepositoryState().name()));
  1153. }
  1154. } else
  1155. switch (repo.getRepositoryState()) {
  1156. case SAFE:
  1157. if (this.upstreamCommit == null)
  1158. throw new JGitInternalException(MessageFormat
  1159. .format(JGitText.get().missingRequiredParameter,
  1160. "upstream"));
  1161. return;
  1162. default:
  1163. throw new WrongRepositoryStateException(MessageFormat.format(
  1164. JGitText.get().wrongRepositoryState, repo
  1165. .getRepositoryState().name()));
  1166. }
  1167. }
  1168. private RebaseResult abort(RebaseResult result) throws IOException,
  1169. GitAPIException {
  1170. try {
  1171. ObjectId origHead = repo.readOrigHead();
  1172. String commitId = origHead != null ? origHead.name() : null;
  1173. monitor.beginTask(MessageFormat.format(
  1174. JGitText.get().abortingRebase, commitId),
  1175. ProgressMonitor.UNKNOWN);
  1176. DirCacheCheckout dco;
  1177. if (commitId == null)
  1178. throw new JGitInternalException(
  1179. JGitText.get().abortingRebaseFailedNoOrigHead);
  1180. ObjectId id = repo.resolve(commitId);
  1181. RevCommit commit = walk.parseCommit(id);
  1182. if (result.getStatus().equals(Status.FAILED)) {
  1183. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1184. dco = new DirCacheCheckout(repo, head.getTree(),
  1185. repo.lockDirCache(), commit.getTree());
  1186. } else {
  1187. dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  1188. commit.getTree());
  1189. }
  1190. dco.setFailOnConflict(false);
  1191. dco.checkout();
  1192. walk.release();
  1193. } finally {
  1194. monitor.endTask();
  1195. }
  1196. try {
  1197. String headName = rebaseState.readFile(HEAD_NAME);
  1198. monitor.beginTask(MessageFormat.format(
  1199. JGitText.get().resettingHead, headName),
  1200. ProgressMonitor.UNKNOWN);
  1201. Result res = null;
  1202. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  1203. refUpdate.setRefLogMessage("rebase: aborting", false); //$NON-NLS-1$
  1204. if (headName.startsWith(Constants.R_REFS)) {
  1205. // update the HEAD
  1206. res = refUpdate.link(headName);
  1207. } else {
  1208. refUpdate.setNewObjectId(repo.readOrigHead());
  1209. res = refUpdate.forceUpdate();
  1210. }
  1211. switch (res) {
  1212. case FAST_FORWARD:
  1213. case FORCED:
  1214. case NO_CHANGE:
  1215. break;
  1216. default:
  1217. throw new JGitInternalException(
  1218. JGitText.get().abortingRebaseFailed);
  1219. }
  1220. boolean stashConflicts = autoStashApply();
  1221. // cleanup the files
  1222. FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1223. repo.writeCherryPickHead(null);
  1224. repo.writeMergeHeads(null);
  1225. if (stashConflicts)
  1226. return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
  1227. return result;
  1228. } finally {
  1229. monitor.endTask();
  1230. }
  1231. }
  1232. private boolean checkoutCommit(String headName, RevCommit commit)
  1233. throws IOException,
  1234. CheckoutConflictException {
  1235. try {
  1236. RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1237. DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  1238. repo.lockDirCache(), commit.getTree());
  1239. dco.setFailOnConflict(true);
  1240. try {
  1241. dco.checkout();
  1242. } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  1243. throw new CheckoutConflictException(dco.getConflicts(), cce);
  1244. }
  1245. // update the HEAD
  1246. RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  1247. refUpdate.setExpectedOldObjectId(head);
  1248. refUpdate.setNewObjectId(commit);
  1249. refUpdate.setRefLogMessage(
  1250. "checkout: moving from " //$NON-NLS-1$
  1251. + Repository.shortenRefName(headName)
  1252. + " to " + commit.getName(), false); //$NON-NLS-1$
  1253. Result res = refUpdate.forceUpdate();
  1254. switch (res) {
  1255. case FAST_FORWARD:
  1256. case NO_CHANGE:
  1257. case FORCED:
  1258. break;
  1259. default:
  1260. throw new IOException("Could not rewind to upstream commit");
  1261. }
  1262. } finally {
  1263. walk.release();
  1264. monitor.endTask();
  1265. }
  1266. return true;
  1267. }
  1268. /**
  1269. * @param upstream
  1270. * the upstream commit
  1271. * @return {@code this}
  1272. */
  1273. public RebaseCommand setUpstream(RevCommit upstream) {
  1274. this.upstreamCommit = upstream;
  1275. this.upstreamCommitName = upstream.name();
  1276. return this;
  1277. }
  1278. /**
  1279. * @param upstream
  1280. * id of the upstream commit
  1281. * @return {@code this}
  1282. */
  1283. public RebaseCommand setUpstream(AnyObjectId upstream) {
  1284. try {
  1285. this.upstreamCommit = walk.parseCommit(upstream);
  1286. this.upstreamCommitName = upstream.name();
  1287. } catch (IOException e) {
  1288. throw new JGitInternalException(MessageFormat.format(
  1289. JGitText.get().couldNotReadObjectWhileParsingCommit,
  1290. upstream.name()), e);
  1291. }
  1292. return this;
  1293. }
  1294. /**
  1295. * @param upstream
  1296. * the upstream branch
  1297. * @return {@code this}
  1298. * @throws RefNotFoundException
  1299. */
  1300. public RebaseCommand setUpstream(String upstream)
  1301. throws RefNotFoundException {
  1302. try {
  1303. ObjectId upstreamId = repo.resolve(upstream);
  1304. if (upstreamId == null)
  1305. throw new RefNotFoundException(MessageFormat.format(JGitText
  1306. .get().refNotResolved, upstream));
  1307. upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  1308. upstreamCommitName = upstream;
  1309. return this;
  1310. } catch (IOException ioe) {
  1311. throw new JGitInternalException(ioe.getMessage(), ioe);
  1312. }
  1313. }
  1314. /**
  1315. * Optionally override the name of the upstream. If this is used, it has to
  1316. * come after any {@link #setUpstream} call.
  1317. *
  1318. * @param upstreamName
  1319. * the name which will be used to refer to upstream in conflicts
  1320. * @return {@code this}
  1321. */
  1322. public RebaseCommand setUpstreamName(String upstreamName) {
  1323. if (upstreamCommit == null) {
  1324. throw new IllegalStateException(
  1325. "setUpstreamName must be called after setUpstream.");
  1326. }
  1327. this.upstreamCommitName = upstreamName;
  1328. return this;
  1329. }
  1330. /**
  1331. * @param operation
  1332. * the operation to perform
  1333. * @return {@code this}
  1334. */
  1335. public RebaseCommand setOperation(Operation operation) {
  1336. this.operation = operation;
  1337. return this;
  1338. }
  1339. /**
  1340. * @param monitor
  1341. * a progress monitor
  1342. * @return this instance
  1343. */
  1344. public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  1345. this.monitor = monitor;
  1346. return this;
  1347. }
  1348. /**
  1349. * Enables interactive rebase
  1350. * <p>
  1351. * Does not stop after initialization of interactive rebase. This is
  1352. * equivalent to
  1353. * {@link RebaseCommand#runInteractively(InteractiveHandler, boolean)
  1354. * runInteractively(handler, false)};
  1355. * </p>
  1356. *
  1357. * @param handler
  1358. * @return this
  1359. */
  1360. public RebaseCommand runInteractively(InteractiveHandler handler) {
  1361. return runInteractively(handler, false);
  1362. }
  1363. /**
  1364. * Enables interactive rebase
  1365. * <p>
  1366. * If stopAfterRebaseInteractiveInitialization is {@code true} the rebase
  1367. * stops after initialization of interactive rebase returning
  1368. * {@link RebaseResult#INTERACTIVE_PREPARED_RESULT}
  1369. * </p>
  1370. *
  1371. * @param handler
  1372. * @param stopAfterRebaseInteractiveInitialization
  1373. * if {@code true} the rebase stops after initialization
  1374. * @return this instance
  1375. * @since 3.2
  1376. */
  1377. public RebaseCommand runInteractively(InteractiveHandler handler,
  1378. final boolean stopAfterRebaseInteractiveInitialization) {
  1379. this.stopAfterInitialization = stopAfterRebaseInteractiveInitialization;
  1380. this.interactiveHandler = handler;
  1381. return this;
  1382. }
  1383. /**
  1384. * @param strategy
  1385. * The merge strategy to use during this rebase operation.
  1386. * @return {@code this}
  1387. * @since 3.4
  1388. */
  1389. public RebaseCommand setStrategy(MergeStrategy strategy) {
  1390. this.strategy = strategy;
  1391. return this;
  1392. }
  1393. /**
  1394. * @param preserve
  1395. * True to re-create merges during rebase. Defaults to false, a
  1396. * flattening rebase.
  1397. * @return {@code this}
  1398. * @since 3.5
  1399. */
  1400. public RebaseCommand setPreserveMerges(boolean preserve) {
  1401. this.preserveMerges = preserve;
  1402. return this;
  1403. }
  1404. /**
  1405. * Allows configure rebase interactive process and modify commit message
  1406. */
  1407. public interface InteractiveHandler {
  1408. /**
  1409. * Given list of {@code steps} should be modified according to user
  1410. * rebase configuration
  1411. * @param steps
  1412. * initial configuration of rebase interactive
  1413. */
  1414. void prepareSteps(List<RebaseTodoLine> steps);
  1415. /**
  1416. * Used for editing commit message on REWORD
  1417. *
  1418. * @param commit
  1419. * @return new commit message
  1420. */
  1421. String modifyCommitMessage(String commit);
  1422. }
  1423. PersonIdent parseAuthor(byte[] raw) {
  1424. if (raw.length == 0)
  1425. return null;
  1426. Map<String, String> keyValueMap = new HashMap<String, String>();
  1427. for (int p = 0; p < raw.length;) {
  1428. int end = RawParseUtils.nextLF(raw, p);
  1429. if (end == p)
  1430. break;
  1431. int equalsIndex = RawParseUtils.next(raw, p, '=');
  1432. if (equalsIndex == end)
  1433. break;
  1434. String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  1435. String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  1436. p = end;
  1437. keyValueMap.put(key, value);
  1438. }
  1439. String name = keyValueMap.get(GIT_AUTHOR_NAME);
  1440. String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  1441. String time = keyValueMap.get(GIT_AUTHOR_DATE);
  1442. // the time is saved as <seconds since 1970> <timezone offset>
  1443. int timeStart = 0;
  1444. if (time.startsWith("@")) //$NON-NLS-1$
  1445. timeStart = 1;
  1446. else
  1447. timeStart = 0;
  1448. long when = Long
  1449. .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
  1450. String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  1451. int multiplier = -1;
  1452. if (tzOffsetString.charAt(0) == '+')
  1453. multiplier = 1;
  1454. int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  1455. int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  1456. // this is in format (+/-)HHMM (hours and minutes)
  1457. // we need to convert into minutes
  1458. int tz = (hours * 60 + minutes) * multiplier;
  1459. if (name != null && email != null)
  1460. return new PersonIdent(name, email, when, tz);
  1461. return null;
  1462. }
  1463. private static class RebaseState {
  1464. private final File repoDirectory;
  1465. private File dir;
  1466. public RebaseState(File repoDirectory) {
  1467. this.repoDirectory = repoDirectory;
  1468. }
  1469. public File getDir() {
  1470. if (dir == null) {
  1471. File rebaseApply = new File(repoDirectory, REBASE_APPLY);
  1472. if (rebaseApply.exists()) {
  1473. dir = rebaseApply;
  1474. } else {
  1475. File rebaseMerge = new File(repoDirectory, REBASE_MERGE);
  1476. dir = rebaseMerge;
  1477. }
  1478. }
  1479. return dir;
  1480. }
  1481. /**
  1482. * @return Directory with rewritten commit hashes, usually exists if
  1483. * {@link RebaseCommand#preserveMerges} is true
  1484. **/
  1485. public File getRewrittenDir() {
  1486. return new File(getDir(), REWRITTEN);
  1487. }
  1488. public String readFile(String name) throws IOException {
  1489. return readFile(getDir(), name);
  1490. }
  1491. public void createFile(String name, String content) throws IOException {
  1492. createFile(getDir(), name, content);
  1493. }
  1494. public File getFile(String name) {
  1495. return new File(getDir(), name);
  1496. }
  1497. public String getPath(String name) {
  1498. return (getDir().getName() + "/" + name); //$NON-NLS-1$
  1499. }
  1500. private static String readFile(File directory, String fileName)
  1501. throws IOException {
  1502. byte[] content = IO.readFully(new File(directory, fileName));
  1503. // strip off the last LF
  1504. int end = RawParseUtils.prevLF(content, content.length);
  1505. return RawParseUtils.decode(content, 0, end + 1);
  1506. }
  1507. private static void createFile(File parentDir, String name,
  1508. String content)
  1509. throws IOException {
  1510. File file = new File(parentDir, name);
  1511. FileOutputStream fos = new FileOutputStream(file);
  1512. try {
  1513. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1514. fos.write('\n');
  1515. } finally {
  1516. fos.close();
  1517. }
  1518. }
  1519. private static void appendToFile(File file, String content)
  1520. throws IOException {
  1521. FileOutputStream fos = new FileOutputStream(file, true);
  1522. try {
  1523. fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
  1524. fos.write('\n');
  1525. } finally {
  1526. fos.close();
  1527. }
  1528. }
  1529. }
  1530. }