RebaseCommand.java

  1. /*
  2.  * Copyright (C) 2010, 2013 Mathias Kinzler <mathias.kinzler@sap.com>
  3.  * Copyright (C) 2016, Laurent Delaigue <laurent.delaigue@obeo.fr> and others
  4.  *
  5.  * This program and the accompanying materials are made available under the
  6.  * terms of the Eclipse Distribution License v. 1.0 which is available at
  7.  * https://www.eclipse.org/org/documents/edl-v10.php.
  8.  *
  9.  * SPDX-License-Identifier: BSD-3-Clause
  10.  */
  11. package org.eclipse.jgit.api;

  12. import static java.nio.charset.StandardCharsets.UTF_8;

  13. import java.io.ByteArrayOutputStream;
  14. import java.io.File;
  15. import java.io.FileNotFoundException;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import java.text.MessageFormat;
  19. import java.util.ArrayList;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashMap;
  23. import java.util.Iterator;
  24. import java.util.LinkedList;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.regex.Matcher;
  28. import java.util.regex.Pattern;

  29. import org.eclipse.jgit.api.RebaseResult.Status;
  30. import org.eclipse.jgit.api.ResetCommand.ResetType;
  31. import org.eclipse.jgit.api.errors.CheckoutConflictException;
  32. import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException;
  33. import org.eclipse.jgit.api.errors.GitAPIException;
  34. import org.eclipse.jgit.api.errors.InvalidRebaseStepException;
  35. import org.eclipse.jgit.api.errors.InvalidRefNameException;
  36. import org.eclipse.jgit.api.errors.JGitInternalException;
  37. import org.eclipse.jgit.api.errors.NoHeadException;
  38. import org.eclipse.jgit.api.errors.NoMessageException;
  39. import org.eclipse.jgit.api.errors.RefAlreadyExistsException;
  40. import org.eclipse.jgit.api.errors.RefNotFoundException;
  41. import org.eclipse.jgit.api.errors.StashApplyFailureException;
  42. import org.eclipse.jgit.api.errors.UnmergedPathsException;
  43. import org.eclipse.jgit.api.errors.WrongRepositoryStateException;
  44. import org.eclipse.jgit.diff.DiffFormatter;
  45. import org.eclipse.jgit.dircache.DirCache;
  46. import org.eclipse.jgit.dircache.DirCacheCheckout;
  47. import org.eclipse.jgit.dircache.DirCacheIterator;
  48. import org.eclipse.jgit.errors.RevisionSyntaxException;
  49. import org.eclipse.jgit.internal.JGitText;
  50. import org.eclipse.jgit.lib.AbbreviatedObjectId;
  51. import org.eclipse.jgit.lib.AnyObjectId;
  52. import org.eclipse.jgit.lib.ConfigConstants;
  53. import org.eclipse.jgit.lib.Constants;
  54. import org.eclipse.jgit.lib.NullProgressMonitor;
  55. import org.eclipse.jgit.lib.ObjectId;
  56. import org.eclipse.jgit.lib.ObjectReader;
  57. import org.eclipse.jgit.lib.PersonIdent;
  58. import org.eclipse.jgit.lib.ProgressMonitor;
  59. import org.eclipse.jgit.lib.RebaseTodoLine;
  60. import org.eclipse.jgit.lib.RebaseTodoLine.Action;
  61. import org.eclipse.jgit.lib.Ref;
  62. import org.eclipse.jgit.lib.RefUpdate;
  63. import org.eclipse.jgit.lib.RefUpdate.Result;
  64. import org.eclipse.jgit.lib.Repository;
  65. import org.eclipse.jgit.merge.MergeStrategy;
  66. import org.eclipse.jgit.revwalk.RevCommit;
  67. import org.eclipse.jgit.revwalk.RevSort;
  68. import org.eclipse.jgit.revwalk.RevWalk;
  69. import org.eclipse.jgit.revwalk.filter.RevFilter;
  70. import org.eclipse.jgit.submodule.SubmoduleWalk.IgnoreSubmoduleMode;
  71. import org.eclipse.jgit.treewalk.TreeWalk;
  72. import org.eclipse.jgit.treewalk.filter.TreeFilter;
  73. import org.eclipse.jgit.util.FileUtils;
  74. import org.eclipse.jgit.util.IO;
  75. import org.eclipse.jgit.util.RawParseUtils;

  76. /**
  77.  * A class used to execute a {@code Rebase} command. It has setters for all
  78.  * supported options and arguments of this command and a {@link #call()} method
  79.  * to finally execute the command. Each instance of this class should only be
  80.  * used for one invocation of the command (means: one call to {@link #call()})
  81.  * <p>
  82.  *
  83.  * @see <a
  84.  *      href="http://www.kernel.org/pub/software/scm/git/docs/git-rebase.html"
  85.  *      >Git documentation about Rebase</a>
  86.  */
  87. public class RebaseCommand extends GitCommand<RebaseResult> {
  88.     /**
  89.      * The name of the "rebase-merge" folder for interactive rebases.
  90.      */
  91.     public static final String REBASE_MERGE = "rebase-merge"; //$NON-NLS-1$

  92.     /**
  93.      * The name of the "rebase-apply" folder for non-interactive rebases.
  94.      */
  95.     private static final String REBASE_APPLY = "rebase-apply"; //$NON-NLS-1$

  96.     /**
  97.      * The name of the "stopped-sha" file
  98.      */
  99.     public static final String STOPPED_SHA = "stopped-sha"; //$NON-NLS-1$

  100.     private static final String AUTHOR_SCRIPT = "author-script"; //$NON-NLS-1$

  101.     private static final String DONE = "done"; //$NON-NLS-1$

  102.     private static final String GIT_AUTHOR_DATE = "GIT_AUTHOR_DATE"; //$NON-NLS-1$

  103.     private static final String GIT_AUTHOR_EMAIL = "GIT_AUTHOR_EMAIL"; //$NON-NLS-1$

  104.     private static final String GIT_AUTHOR_NAME = "GIT_AUTHOR_NAME"; //$NON-NLS-1$

  105.     private static final String GIT_REBASE_TODO = "git-rebase-todo"; //$NON-NLS-1$

  106.     private static final String HEAD_NAME = "head-name"; //$NON-NLS-1$

  107.     private static final String INTERACTIVE = "interactive"; //$NON-NLS-1$

  108.     private static final String QUIET = "quiet"; //$NON-NLS-1$

  109.     private static final String MESSAGE = "message"; //$NON-NLS-1$

  110.     private static final String ONTO = "onto"; //$NON-NLS-1$

  111.     private static final String ONTO_NAME = "onto_name"; //$NON-NLS-1$

  112.     private static final String PATCH = "patch"; //$NON-NLS-1$

  113.     private static final String REBASE_HEAD = "orig-head"; //$NON-NLS-1$

  114.     /** Pre git 1.7.6 file name for {@link #REBASE_HEAD}. */
  115.     private static final String REBASE_HEAD_LEGACY = "head"; //$NON-NLS-1$

  116.     private static final String AMEND = "amend"; //$NON-NLS-1$

  117.     private static final String MESSAGE_FIXUP = "message-fixup"; //$NON-NLS-1$

  118.     private static final String MESSAGE_SQUASH = "message-squash"; //$NON-NLS-1$

  119.     private static final String AUTOSTASH = "autostash"; //$NON-NLS-1$

  120.     private static final String AUTOSTASH_MSG = "On {0}: autostash"; //$NON-NLS-1$

  121.     /**
  122.      * The folder containing the hashes of (potentially) rewritten commits when
  123.      * --preserve-merges is used.
  124.      * <p>
  125.      * Native git rebase --merge uses a <em>file</em> of that name to record
  126.      * commits to copy notes at the end of the whole rebase.
  127.      * </p>
  128.      */
  129.     private static final String REWRITTEN = "rewritten"; //$NON-NLS-1$

  130.     /**
  131.      * File containing the current commit(s) to cherry pick when --preserve-merges
  132.      * is used.
  133.      */
  134.     private static final String CURRENT_COMMIT = "current-commit"; //$NON-NLS-1$

  135.     private static final String REFLOG_PREFIX = "rebase:"; //$NON-NLS-1$

  136.     /**
  137.      * The available operations
  138.      */
  139.     public enum Operation {
  140.         /**
  141.          * Initiates rebase
  142.          */
  143.         BEGIN,
  144.         /**
  145.          * Continues after a conflict resolution
  146.          */
  147.         CONTINUE,
  148.         /**
  149.          * Skips the "current" commit
  150.          */
  151.         SKIP,
  152.         /**
  153.          * Aborts and resets the current rebase
  154.          */
  155.         ABORT,
  156.         /**
  157.          * Starts processing steps
  158.          * @since 3.2
  159.          */
  160.         PROCESS_STEPS;
  161.     }

  162.     private Operation operation = Operation.BEGIN;

  163.     private RevCommit upstreamCommit;

  164.     private String upstreamCommitName;

  165.     private ProgressMonitor monitor = NullProgressMonitor.INSTANCE;

  166.     private final RevWalk walk;

  167.     private final RebaseState rebaseState;

  168.     private InteractiveHandler interactiveHandler;

  169.     private boolean stopAfterInitialization = false;

  170.     private RevCommit newHead;

  171.     private boolean lastStepWasForward;

  172.     private MergeStrategy strategy = MergeStrategy.RECURSIVE;

  173.     private boolean preserveMerges = false;

  174.     /**
  175.      * <p>
  176.      * Constructor for RebaseCommand.
  177.      * </p>
  178.      *
  179.      * @param repo
  180.      *            the {@link org.eclipse.jgit.lib.Repository}
  181.      */
  182.     protected RebaseCommand(Repository repo) {
  183.         super(repo);
  184.         walk = new RevWalk(repo);
  185.         rebaseState = new RebaseState(repo.getDirectory());
  186.     }

  187.     /**
  188.      * {@inheritDoc}
  189.      * <p>
  190.      * Executes the {@code Rebase} command with all the options and parameters
  191.      * collected by the setter methods of this class. Each instance of this
  192.      * class should only be used for one invocation of the command. Don't call
  193.      * this method twice on an instance.
  194.      */
  195.     @Override
  196.     public RebaseResult call() throws GitAPIException, NoHeadException,
  197.             RefNotFoundException, WrongRepositoryStateException {
  198.         newHead = null;
  199.         lastStepWasForward = false;
  200.         checkCallable();
  201.         checkParameters();
  202.         try {
  203.             switch (operation) {
  204.             case ABORT:
  205.                 try {
  206.                     return abort(RebaseResult.ABORTED_RESULT);
  207.                 } catch (IOException ioe) {
  208.                     throw new JGitInternalException(ioe.getMessage(), ioe);
  209.                 }
  210.             case PROCESS_STEPS:
  211.             case SKIP:
  212.             case CONTINUE:
  213.                 String upstreamCommitId = rebaseState.readFile(ONTO);
  214.                 try {
  215.                     upstreamCommitName = rebaseState.readFile(ONTO_NAME);
  216.                 } catch (FileNotFoundException e) {
  217.                     // Fall back to commit ID if file doesn't exist (e.g. rebase
  218.                     // was started by C Git)
  219.                     upstreamCommitName = upstreamCommitId;
  220.                 }
  221.                 this.upstreamCommit = walk.parseCommit(repo
  222.                         .resolve(upstreamCommitId));
  223.                 preserveMerges = rebaseState.getRewrittenDir().isDirectory();
  224.                 break;
  225.             case BEGIN:
  226.                 autoStash();
  227.                 if (stopAfterInitialization
  228.                         || !walk.isMergedInto(
  229.                                 walk.parseCommit(repo.resolve(Constants.HEAD)),
  230.                                 upstreamCommit)) {
  231.                     org.eclipse.jgit.api.Status status = Git.wrap(repo)
  232.                             .status().setIgnoreSubmodules(IgnoreSubmoduleMode.ALL).call();
  233.                     if (status.hasUncommittedChanges()) {
  234.                         List<String> list = new ArrayList<>();
  235.                         list.addAll(status.getUncommittedChanges());
  236.                         return RebaseResult.uncommittedChanges(list);
  237.                     }
  238.                 }
  239.                 RebaseResult res = initFilesAndRewind();
  240.                 if (stopAfterInitialization)
  241.                     return RebaseResult.INTERACTIVE_PREPARED_RESULT;
  242.                 if (res != null) {
  243.                     autoStashApply();
  244.                     if (rebaseState.getDir().exists())
  245.                         FileUtils.delete(rebaseState.getDir(),
  246.                                 FileUtils.RECURSIVE);
  247.                     return res;
  248.                 }
  249.             }

  250.             if (monitor.isCancelled())
  251.                 return abort(RebaseResult.ABORTED_RESULT);

  252.             if (operation == Operation.CONTINUE) {
  253.                 newHead = continueRebase();
  254.                 List<RebaseTodoLine> doneLines = repo.readRebaseTodo(
  255.                         rebaseState.getPath(DONE), true);
  256.                 RebaseTodoLine step = doneLines.get(doneLines.size() - 1);
  257.                 if (newHead != null
  258.                         && step.getAction() != Action.PICK) {
  259.                     RebaseTodoLine newStep = new RebaseTodoLine(
  260.                             step.getAction(),
  261.                             AbbreviatedObjectId.fromObjectId(newHead),
  262.                             step.getShortMessage());
  263.                     RebaseResult result = processStep(newStep, false);
  264.                     if (result != null)
  265.                         return result;
  266.                 }
  267.                 File amendFile = rebaseState.getFile(AMEND);
  268.                 boolean amendExists = amendFile.exists();
  269.                 if (amendExists) {
  270.                     FileUtils.delete(amendFile);
  271.                 }
  272.                 if (newHead == null && !amendExists) {
  273.                     // continueRebase() returns null only if no commit was
  274.                     // neccessary. This means that no changes where left over
  275.                     // after resolving all conflicts. In this case, cgit stops
  276.                     // and displays a nice message to the user, telling him to
  277.                     // either do changes or skip the commit instead of continue.
  278.                     return RebaseResult.NOTHING_TO_COMMIT_RESULT;
  279.                 }
  280.             }

  281.             if (operation == Operation.SKIP)
  282.                 newHead = checkoutCurrentHead();

  283.             List<RebaseTodoLine> steps = repo.readRebaseTodo(
  284.                     rebaseState.getPath(GIT_REBASE_TODO), false);
  285.             if (steps.isEmpty()) {
  286.                 return finishRebase(walk.parseCommit(repo.resolve(Constants.HEAD)), false);
  287.             }
  288.             if (isInteractive()) {
  289.                 interactiveHandler.prepareSteps(steps);
  290.                 repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  291.                         steps, false);
  292.             }
  293.             checkSteps(steps);
  294.             for (RebaseTodoLine step : steps) {
  295.                 popSteps(1);
  296.                 RebaseResult result = processStep(step, true);
  297.                 if (result != null) {
  298.                     return result;
  299.                 }
  300.             }
  301.             return finishRebase(newHead, lastStepWasForward);
  302.         } catch (CheckoutConflictException cce) {
  303.             return RebaseResult.conflicts(cce.getConflictingPaths());
  304.         } catch (IOException ioe) {
  305.             throw new JGitInternalException(ioe.getMessage(), ioe);
  306.         }
  307.     }

  308.     private void autoStash() throws GitAPIException, IOException {
  309.         if (repo.getConfig().getBoolean(ConfigConstants.CONFIG_REBASE_SECTION,
  310.                 ConfigConstants.CONFIG_KEY_AUTOSTASH, false)) {
  311.             String message = MessageFormat.format(
  312.                             AUTOSTASH_MSG,
  313.                             Repository
  314.                                     .shortenRefName(getHeadName(getHead())));
  315.             RevCommit stashCommit = Git.wrap(repo).stashCreate().setRef(null)
  316.                     .setWorkingDirectoryMessage(
  317.                             message)
  318.                     .call();
  319.             if (stashCommit != null) {
  320.                 FileUtils.mkdir(rebaseState.getDir());
  321.                 rebaseState.createFile(AUTOSTASH, stashCommit.getName());
  322.             }
  323.         }
  324.     }

  325.     private boolean autoStashApply() throws IOException, GitAPIException {
  326.         boolean conflicts = false;
  327.         if (rebaseState.getFile(AUTOSTASH).exists()) {
  328.             String stash = rebaseState.readFile(AUTOSTASH);
  329.             try (Git git = Git.wrap(repo)) {
  330.                 git.stashApply().setStashRef(stash)
  331.                         .ignoreRepositoryState(true).setStrategy(strategy)
  332.                         .call();
  333.             } catch (StashApplyFailureException e) {
  334.                 conflicts = true;
  335.                 try (RevWalk rw = new RevWalk(repo)) {
  336.                     ObjectId stashId = repo.resolve(stash);
  337.                     RevCommit commit = rw.parseCommit(stashId);
  338.                     updateStashRef(commit, commit.getAuthorIdent(),
  339.                             commit.getShortMessage());
  340.                 }
  341.             }
  342.         }
  343.         return conflicts;
  344.     }

  345.     private void updateStashRef(ObjectId commitId, PersonIdent refLogIdent,
  346.             String refLogMessage) throws IOException {
  347.         Ref currentRef = repo.exactRef(Constants.R_STASH);
  348.         RefUpdate refUpdate = repo.updateRef(Constants.R_STASH);
  349.         refUpdate.setNewObjectId(commitId);
  350.         refUpdate.setRefLogIdent(refLogIdent);
  351.         refUpdate.setRefLogMessage(refLogMessage, false);
  352.         refUpdate.setForceRefLog(true);
  353.         if (currentRef != null)
  354.             refUpdate.setExpectedOldObjectId(currentRef.getObjectId());
  355.         else
  356.             refUpdate.setExpectedOldObjectId(ObjectId.zeroId());
  357.         refUpdate.forceUpdate();
  358.     }

  359.     private RebaseResult processStep(RebaseTodoLine step, boolean shouldPick)
  360.             throws IOException, GitAPIException {
  361.         if (Action.COMMENT.equals(step.getAction()))
  362.             return null;
  363.         if (preserveMerges
  364.                 && shouldPick
  365.                 && (Action.EDIT.equals(step.getAction()) || Action.PICK
  366.                         .equals(step.getAction()))) {
  367.             writeRewrittenHashes();
  368.         }
  369.         ObjectReader or = repo.newObjectReader();

  370.         Collection<ObjectId> ids = or.resolve(step.getCommit());
  371.         if (ids.size() != 1)
  372.             throw new JGitInternalException(
  373.                     JGitText.get().cannotResolveUniquelyAbbrevObjectId);
  374.         RevCommit commitToPick = walk.parseCommit(ids.iterator().next());
  375.         if (shouldPick) {
  376.             if (monitor.isCancelled())
  377.                 return RebaseResult.result(Status.STOPPED, commitToPick);
  378.             RebaseResult result = cherryPickCommit(commitToPick);
  379.             if (result != null)
  380.                 return result;
  381.         }
  382.         boolean isSquash = false;
  383.         switch (step.getAction()) {
  384.         case PICK:
  385.             return null; // continue rebase process on pick command
  386.         case REWORD:
  387.             String oldMessage = commitToPick.getFullMessage();
  388.             String newMessage = interactiveHandler
  389.                     .modifyCommitMessage(oldMessage);
  390.             try (Git git = new Git(repo)) {
  391.                 newHead = git.commit().setMessage(newMessage).setAmend(true)
  392.                         .setNoVerify(true).call();
  393.             }
  394.             return null;
  395.         case EDIT:
  396.             rebaseState.createFile(AMEND, commitToPick.name());
  397.             return stop(commitToPick, Status.EDIT);
  398.         case COMMENT:
  399.             break;
  400.         case SQUASH:
  401.             isSquash = true;
  402.             //$FALL-THROUGH$
  403.         case FIXUP:
  404.             resetSoftToParent();
  405.             List<RebaseTodoLine> steps = repo.readRebaseTodo(
  406.                     rebaseState.getPath(GIT_REBASE_TODO), false);
  407.             RebaseTodoLine nextStep = steps.isEmpty() ? null : steps.get(0);
  408.             File messageFixupFile = rebaseState.getFile(MESSAGE_FIXUP);
  409.             File messageSquashFile = rebaseState.getFile(MESSAGE_SQUASH);
  410.             if (isSquash && messageFixupFile.exists())
  411.                 messageFixupFile.delete();
  412.             newHead = doSquashFixup(isSquash, commitToPick, nextStep,
  413.                     messageFixupFile, messageSquashFile);
  414.         }
  415.         return null;
  416.     }

  417.     private RebaseResult cherryPickCommit(RevCommit commitToPick)
  418.             throws IOException, GitAPIException, NoMessageException,
  419.             UnmergedPathsException, ConcurrentRefUpdateException,
  420.             WrongRepositoryStateException, NoHeadException {
  421.         try {
  422.             monitor.beginTask(MessageFormat.format(
  423.                     JGitText.get().applyingCommit,
  424.                     commitToPick.getShortMessage()), ProgressMonitor.UNKNOWN);
  425.             if (preserveMerges) {
  426.                 return cherryPickCommitPreservingMerges(commitToPick);
  427.             }
  428.             return cherryPickCommitFlattening(commitToPick);
  429.         } finally {
  430.             monitor.endTask();
  431.         }
  432.     }

  433.     private RebaseResult cherryPickCommitFlattening(RevCommit commitToPick)
  434.             throws IOException, GitAPIException, NoMessageException,
  435.             UnmergedPathsException, ConcurrentRefUpdateException,
  436.             WrongRepositoryStateException, NoHeadException {
  437.         // If the first parent of commitToPick is the current HEAD,
  438.         // we do a fast-forward instead of cherry-pick to avoid
  439.         // unnecessary object rewriting
  440.         newHead = tryFastForward(commitToPick);
  441.         lastStepWasForward = newHead != null;
  442.         if (!lastStepWasForward) {
  443.             // TODO if the content of this commit is already merged
  444.             // here we should skip this step in order to avoid
  445.             // confusing pseudo-changed
  446.             String ourCommitName = getOurCommitName();
  447.             try (Git git = new Git(repo)) {
  448.                 CherryPickResult cherryPickResult = git.cherryPick()
  449.                     .include(commitToPick).setOurCommitName(ourCommitName)
  450.                     .setReflogPrefix(REFLOG_PREFIX).setStrategy(strategy)
  451.                     .call();
  452.                 switch (cherryPickResult.getStatus()) {
  453.                 case FAILED:
  454.                     if (operation == Operation.BEGIN) {
  455.                         return abort(RebaseResult
  456.                                 .failed(cherryPickResult.getFailingPaths()));
  457.                     }
  458.                     return stop(commitToPick, Status.STOPPED);
  459.                 case CONFLICTING:
  460.                     return stop(commitToPick, Status.STOPPED);
  461.                 case OK:
  462.                     newHead = cherryPickResult.getNewHead();
  463.                 }
  464.             }
  465.         }
  466.         return null;
  467.     }

  468.     private RebaseResult cherryPickCommitPreservingMerges(RevCommit commitToPick)
  469.             throws IOException, GitAPIException, NoMessageException,
  470.             UnmergedPathsException, ConcurrentRefUpdateException,
  471.             WrongRepositoryStateException, NoHeadException {

  472.         writeCurrentCommit(commitToPick);

  473.         List<RevCommit> newParents = getNewParents(commitToPick);
  474.         boolean otherParentsUnchanged = true;
  475.         for (int i = 1; i < commitToPick.getParentCount(); i++)
  476.             otherParentsUnchanged &= newParents.get(i).equals(
  477.                     commitToPick.getParent(i));
  478.         // If the first parent of commitToPick is the current HEAD,
  479.         // we do a fast-forward instead of cherry-pick to avoid
  480.         // unnecessary object rewriting
  481.         newHead = otherParentsUnchanged ? tryFastForward(commitToPick) : null;
  482.         lastStepWasForward = newHead != null;
  483.         if (!lastStepWasForward) {
  484.             ObjectId headId = getHead().getObjectId();
  485.             // getHead() checks for null
  486.             assert headId != null;
  487.             if (!AnyObjectId.isEqual(headId, newParents.get(0)))
  488.                 checkoutCommit(headId.getName(), newParents.get(0));

  489.             // Use the cherry-pick strategy if all non-first parents did not
  490.             // change. This is different from C Git, which always uses the merge
  491.             // strategy (see below).
  492.             try (Git git = new Git(repo)) {
  493.                 if (otherParentsUnchanged) {
  494.                     boolean isMerge = commitToPick.getParentCount() > 1;
  495.                     String ourCommitName = getOurCommitName();
  496.                     CherryPickCommand pickCommand = git.cherryPick()
  497.                             .include(commitToPick)
  498.                             .setOurCommitName(ourCommitName)
  499.                             .setReflogPrefix(REFLOG_PREFIX)
  500.                             .setStrategy(strategy);
  501.                     if (isMerge) {
  502.                         pickCommand.setMainlineParentNumber(1);
  503.                         // We write a MERGE_HEAD and later commit explicitly
  504.                         pickCommand.setNoCommit(true);
  505.                         writeMergeInfo(commitToPick, newParents);
  506.                     }
  507.                     CherryPickResult cherryPickResult = pickCommand.call();
  508.                     switch (cherryPickResult.getStatus()) {
  509.                     case FAILED:
  510.                         if (operation == Operation.BEGIN) {
  511.                             return abort(RebaseResult.failed(
  512.                                     cherryPickResult.getFailingPaths()));
  513.                         }
  514.                         return stop(commitToPick, Status.STOPPED);
  515.                     case CONFLICTING:
  516.                         return stop(commitToPick, Status.STOPPED);
  517.                     case OK:
  518.                         if (isMerge) {
  519.                             // Commit the merge (setup above using
  520.                             // writeMergeInfo())
  521.                             CommitCommand commit = git.commit();
  522.                             commit.setAuthor(commitToPick.getAuthorIdent());
  523.                             commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$
  524.                                     + commitToPick.getShortMessage());
  525.                             newHead = commit.call();
  526.                         } else
  527.                             newHead = cherryPickResult.getNewHead();
  528.                         break;
  529.                     }
  530.                 } else {
  531.                     // Use the merge strategy to redo merges, which had some of
  532.                     // their non-first parents rewritten
  533.                     MergeCommand merge = git.merge()
  534.                             .setFastForward(MergeCommand.FastForwardMode.NO_FF)
  535.                             .setProgressMonitor(monitor)
  536.                             .setCommit(false);
  537.                     for (int i = 1; i < commitToPick.getParentCount(); i++)
  538.                         merge.include(newParents.get(i));
  539.                     MergeResult mergeResult = merge.call();
  540.                     if (mergeResult.getMergeStatus().isSuccessful()) {
  541.                         CommitCommand commit = git.commit();
  542.                         commit.setAuthor(commitToPick.getAuthorIdent());
  543.                         commit.setMessage(commitToPick.getFullMessage());
  544.                         commit.setReflogComment(REFLOG_PREFIX + " " //$NON-NLS-1$
  545.                                 + commitToPick.getShortMessage());
  546.                         newHead = commit.call();
  547.                     } else {
  548.                         if (operation == Operation.BEGIN && mergeResult
  549.                                 .getMergeStatus() == MergeResult.MergeStatus.FAILED)
  550.                             return abort(RebaseResult
  551.                                     .failed(mergeResult.getFailingPaths()));
  552.                         return stop(commitToPick, Status.STOPPED);
  553.                     }
  554.                 }
  555.             }
  556.         }
  557.         return null;
  558.     }

  559.     // Prepare MERGE_HEAD and message for the next commit
  560.     private void writeMergeInfo(RevCommit commitToPick,
  561.             List<RevCommit> newParents) throws IOException {
  562.         repo.writeMergeHeads(newParents.subList(1, newParents.size()));
  563.         repo.writeMergeCommitMsg(commitToPick.getFullMessage());
  564.     }

  565.     // Get the rewritten equivalents for the parents of the given commit
  566.     private List<RevCommit> getNewParents(RevCommit commitToPick)
  567.             throws IOException {
  568.         List<RevCommit> newParents = new ArrayList<>();
  569.         for (int p = 0; p < commitToPick.getParentCount(); p++) {
  570.             String parentHash = commitToPick.getParent(p).getName();
  571.             if (!new File(rebaseState.getRewrittenDir(), parentHash).exists())
  572.                 newParents.add(commitToPick.getParent(p));
  573.             else {
  574.                 String newParent = RebaseState.readFile(
  575.                         rebaseState.getRewrittenDir(), parentHash);
  576.                 if (newParent.length() == 0)
  577.                     newParents.add(walk.parseCommit(repo
  578.                             .resolve(Constants.HEAD)));
  579.                 else
  580.                     newParents.add(walk.parseCommit(ObjectId
  581.                             .fromString(newParent)));
  582.             }
  583.         }
  584.         return newParents;
  585.     }

  586.     private void writeCurrentCommit(RevCommit commit) throws IOException {
  587.         RebaseState.appendToFile(rebaseState.getFile(CURRENT_COMMIT),
  588.                 commit.name());
  589.     }

  590.     private void writeRewrittenHashes() throws RevisionSyntaxException,
  591.             IOException, RefNotFoundException {
  592.         File currentCommitFile = rebaseState.getFile(CURRENT_COMMIT);
  593.         if (!currentCommitFile.exists())
  594.             return;

  595.         ObjectId headId = getHead().getObjectId();
  596.         // getHead() checks for null
  597.         assert headId != null;
  598.         String head = headId.getName();
  599.         String currentCommits = rebaseState.readFile(CURRENT_COMMIT);
  600.         for (String current : currentCommits.split("\n")) //$NON-NLS-1$
  601.             RebaseState
  602.                     .createFile(rebaseState.getRewrittenDir(), current, head);
  603.         FileUtils.delete(currentCommitFile);
  604.     }

  605.     private RebaseResult finishRebase(RevCommit finalHead,
  606.             boolean lastStepIsForward) throws IOException, GitAPIException {
  607.         String headName = rebaseState.readFile(HEAD_NAME);
  608.         updateHead(headName, finalHead, upstreamCommit);
  609.         boolean stashConflicts = autoStashApply();
  610.         getRepository().autoGC(monitor);
  611.         FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  612.         if (stashConflicts)
  613.             return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
  614.         if (lastStepIsForward || finalHead == null)
  615.             return RebaseResult.FAST_FORWARD_RESULT;
  616.         return RebaseResult.OK_RESULT;
  617.     }

  618.     private void checkSteps(List<RebaseTodoLine> steps)
  619.             throws InvalidRebaseStepException, IOException {
  620.         if (steps.isEmpty())
  621.             return;
  622.         if (RebaseTodoLine.Action.SQUASH.equals(steps.get(0).getAction())
  623.                 || RebaseTodoLine.Action.FIXUP.equals(steps.get(0).getAction())) {
  624.             if (!rebaseState.getFile(DONE).exists()
  625.                     || rebaseState.readFile(DONE).trim().length() == 0) {
  626.                 throw new InvalidRebaseStepException(MessageFormat.format(
  627.                         JGitText.get().cannotSquashFixupWithoutPreviousCommit,
  628.                         steps.get(0).getAction().name()));
  629.             }
  630.         }

  631.     }

  632.     private RevCommit doSquashFixup(boolean isSquash, RevCommit commitToPick,
  633.             RebaseTodoLine nextStep, File messageFixup, File messageSquash)
  634.             throws IOException, GitAPIException {

  635.         if (!messageSquash.exists()) {
  636.             // init squash/fixup sequence
  637.             ObjectId headId = repo.resolve(Constants.HEAD);
  638.             RevCommit previousCommit = walk.parseCommit(headId);

  639.             initializeSquashFixupFile(MESSAGE_SQUASH,
  640.                     previousCommit.getFullMessage());
  641.             if (!isSquash)
  642.                 initializeSquashFixupFile(MESSAGE_FIXUP,
  643.                     previousCommit.getFullMessage());
  644.         }
  645.         String currSquashMessage = rebaseState
  646.                 .readFile(MESSAGE_SQUASH);

  647.         int count = parseSquashFixupSequenceCount(currSquashMessage) + 1;

  648.         String content = composeSquashMessage(isSquash,
  649.                 commitToPick, currSquashMessage, count);
  650.         rebaseState.createFile(MESSAGE_SQUASH, content);
  651.         if (messageFixup.exists())
  652.             rebaseState.createFile(MESSAGE_FIXUP, content);

  653.         return squashIntoPrevious(
  654.                 !messageFixup.exists(),
  655.                 nextStep);
  656.     }

  657.     private void resetSoftToParent() throws IOException,
  658.             GitAPIException, CheckoutConflictException {
  659.         Ref ref = repo.exactRef(Constants.ORIG_HEAD);
  660.         ObjectId orig_head = ref == null ? null : ref.getObjectId();
  661.         try (Git git = Git.wrap(repo)) {
  662.             // we have already committed the cherry-picked commit.
  663.             // what we need is to have changes introduced by this
  664.             // commit to be on the index
  665.             // resetting is a workaround
  666.             git.reset().setMode(ResetType.SOFT)
  667.                     .setRef("HEAD~1").call(); //$NON-NLS-1$
  668.         } finally {
  669.             // set ORIG_HEAD back to where we started because soft
  670.             // reset moved it
  671.             repo.writeOrigHead(orig_head);
  672.         }
  673.     }

  674.     private RevCommit squashIntoPrevious(boolean sequenceContainsSquash,
  675.             RebaseTodoLine nextStep)
  676.             throws IOException, GitAPIException {
  677.         RevCommit retNewHead;
  678.         String commitMessage = rebaseState
  679.                 .readFile(MESSAGE_SQUASH);

  680.         try (Git git = new Git(repo)) {
  681.             if (nextStep == null || ((nextStep.getAction() != Action.FIXUP)
  682.                     && (nextStep.getAction() != Action.SQUASH))) {
  683.                 // this is the last step in this sequence
  684.                 if (sequenceContainsSquash) {
  685.                     commitMessage = interactiveHandler
  686.                             .modifyCommitMessage(commitMessage);
  687.                 }
  688.                 retNewHead = git.commit()
  689.                         .setMessage(stripCommentLines(commitMessage))
  690.                         .setAmend(true).setNoVerify(true).call();
  691.                 rebaseState.getFile(MESSAGE_SQUASH).delete();
  692.                 rebaseState.getFile(MESSAGE_FIXUP).delete();

  693.             } else {
  694.                 // Next step is either Squash or Fixup
  695.                 retNewHead = git.commit().setMessage(commitMessage)
  696.                         .setAmend(true).setNoVerify(true).call();
  697.             }
  698.         }
  699.         return retNewHead;
  700.     }

  701.     private static String stripCommentLines(String commitMessage) {
  702.         StringBuilder result = new StringBuilder();
  703.         for (String line : commitMessage.split("\n")) { //$NON-NLS-1$
  704.             if (!line.trim().startsWith("#")) //$NON-NLS-1$
  705.                 result.append(line).append("\n"); //$NON-NLS-1$
  706.         }
  707.         if (!commitMessage.endsWith("\n")) { //$NON-NLS-1$
  708.             int bufferSize = result.length();
  709.             if (bufferSize > 0 && result.charAt(bufferSize - 1) == '\n') {
  710.                 result.deleteCharAt(bufferSize - 1);
  711.             }
  712.         }
  713.         return result.toString();
  714.     }

  715.     @SuppressWarnings("nls")
  716.     private static String composeSquashMessage(boolean isSquash,
  717.             RevCommit commitToPick, String currSquashMessage, int count) {
  718.         StringBuilder sb = new StringBuilder();
  719.         String ordinal = getOrdinal(count);
  720.         sb.setLength(0);
  721.         sb.append("# This is a combination of ").append(count)
  722.                 .append(" commits.\n");
  723.         // Add the previous message without header (i.e first line)
  724.         sb.append(currSquashMessage
  725.                 .substring(currSquashMessage.indexOf('\n') + 1));
  726.         sb.append("\n");
  727.         if (isSquash) {
  728.             sb.append("# This is the ").append(count).append(ordinal)
  729.                     .append(" commit message:\n");
  730.             sb.append(commitToPick.getFullMessage());
  731.         } else {
  732.             sb.append("# The ").append(count).append(ordinal)
  733.                     .append(" commit message will be skipped:\n# ");
  734.             sb.append(commitToPick.getFullMessage().replaceAll("([\n\r])",
  735.                     "$1# "));
  736.         }
  737.         return sb.toString();
  738.     }

  739.     private static String getOrdinal(int count) {
  740.         switch (count % 10) {
  741.         case 1:
  742.             return "st"; //$NON-NLS-1$
  743.         case 2:
  744.             return "nd"; //$NON-NLS-1$
  745.         case 3:
  746.             return "rd"; //$NON-NLS-1$
  747.         default:
  748.             return "th"; //$NON-NLS-1$
  749.         }
  750.     }

  751.     /**
  752.      * Parse the count from squashed commit messages
  753.      *
  754.      * @param currSquashMessage
  755.      *            the squashed commit message to be parsed
  756.      * @return the count of squashed messages in the given string
  757.      */
  758.     static int parseSquashFixupSequenceCount(String currSquashMessage) {
  759.         String regex = "This is a combination of (.*) commits"; //$NON-NLS-1$
  760.         String firstLine = currSquashMessage.substring(0,
  761.                 currSquashMessage.indexOf('\n'));
  762.         Pattern pattern = Pattern.compile(regex);
  763.         Matcher matcher = pattern.matcher(firstLine);
  764.         if (!matcher.find())
  765.             throw new IllegalArgumentException();
  766.         return Integer.parseInt(matcher.group(1));
  767.     }

  768.     private void initializeSquashFixupFile(String messageFile,
  769.             String fullMessage) throws IOException {
  770.         rebaseState
  771.                 .createFile(
  772.                         messageFile,
  773.                         "# This is a combination of 1 commits.\n# The first commit's message is:\n" + fullMessage); //$NON-NLS-1$);
  774.     }

  775.     private String getOurCommitName() {
  776.         // If onto is different from upstream, this should say "onto", but
  777.         // RebaseCommand doesn't support a different "onto" at the moment.
  778.         String ourCommitName = "Upstream, based on " //$NON-NLS-1$
  779.                 + Repository.shortenRefName(upstreamCommitName);
  780.         return ourCommitName;
  781.     }

  782.     private void updateHead(String headName, RevCommit aNewHead, RevCommit onto)
  783.             throws IOException {
  784.         // point the previous head (if any) to the new commit

  785.         if (headName.startsWith(Constants.R_REFS)) {
  786.             RefUpdate rup = repo.updateRef(headName);
  787.             rup.setNewObjectId(aNewHead);
  788.             rup.setRefLogMessage("rebase finished: " + headName + " onto " //$NON-NLS-1$ //$NON-NLS-2$
  789.                     + onto.getName(), false);
  790.             Result res = rup.forceUpdate();
  791.             switch (res) {
  792.             case FAST_FORWARD:
  793.             case FORCED:
  794.             case NO_CHANGE:
  795.                 break;
  796.             default:
  797.                 throw new JGitInternalException(
  798.                         JGitText.get().updatingHeadFailed);
  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(
  811.                         JGitText.get().updatingHeadFailed);
  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.             dco.setProgressMonitor(monitor);
  825.             boolean needsDeleteFiles = dco.checkout();
  826.             if (needsDeleteFiles) {
  827.                 List<String> fileList = dco.getToBeDeleted();
  828.                 for (String filePath : fileList) {
  829.                     File fileToDelete = new File(repo.getWorkTree(), filePath);
  830.                     if (repo.getFS().exists(fileToDelete))
  831.                         FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
  832.                                 | FileUtils.RETRY);
  833.                 }
  834.             }
  835.         } finally {
  836.             dc.unlock();
  837.         }
  838.         try (RevWalk rw = new RevWalk(repo)) {
  839.             RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
  840.             return commit;
  841.         }
  842.     }

  843.     /**
  844.      * @return the commit if we had to do a commit, otherwise null
  845.      * @throws GitAPIException
  846.      * @throws IOException
  847.      */
  848.     private RevCommit continueRebase() throws GitAPIException, IOException {
  849.         // if there are still conflicts, we throw a specific Exception
  850.         DirCache dc = repo.readDirCache();
  851.         boolean hasUnmergedPaths = dc.hasUnmergedPaths();
  852.         if (hasUnmergedPaths)
  853.             throw new UnmergedPathsException();

  854.         // determine whether we need to commit
  855.         boolean needsCommit;
  856.         try (TreeWalk treeWalk = new TreeWalk(repo)) {
  857.             treeWalk.reset();
  858.             treeWalk.setRecursive(true);
  859.             treeWalk.addTree(new DirCacheIterator(dc));
  860.             ObjectId id = repo.resolve(Constants.HEAD + "^{tree}"); //$NON-NLS-1$
  861.             if (id == null)
  862.                 throw new NoHeadException(
  863.                         JGitText.get().cannotRebaseWithoutCurrentHead);

  864.             treeWalk.addTree(id);

  865.             treeWalk.setFilter(TreeFilter.ANY_DIFF);

  866.             needsCommit = treeWalk.next();
  867.         }
  868.         if (needsCommit) {
  869.             try (Git git = new Git(repo)) {
  870.                 CommitCommand commit = git.commit();
  871.                 commit.setMessage(rebaseState.readFile(MESSAGE));
  872.                 commit.setAuthor(parseAuthor());
  873.                 return commit.call();
  874.             }
  875.         }
  876.         return null;
  877.     }

  878.     private PersonIdent parseAuthor() throws IOException {
  879.         File authorScriptFile = rebaseState.getFile(AUTHOR_SCRIPT);
  880.         byte[] raw;
  881.         try {
  882.             raw = IO.readFully(authorScriptFile);
  883.         } catch (FileNotFoundException notFound) {
  884.             if (authorScriptFile.exists()) {
  885.                 throw notFound;
  886.             }
  887.             return null;
  888.         }
  889.         return parseAuthor(raw);
  890.     }

  891.     private RebaseResult stop(RevCommit commitToPick, RebaseResult.Status status)
  892.             throws IOException {
  893.         PersonIdent author = commitToPick.getAuthorIdent();
  894.         String authorScript = toAuthorScript(author);
  895.         rebaseState.createFile(AUTHOR_SCRIPT, authorScript);
  896.         rebaseState.createFile(MESSAGE, commitToPick.getFullMessage());
  897.         ByteArrayOutputStream bos = new ByteArrayOutputStream();
  898.         try (DiffFormatter df = new DiffFormatter(bos)) {
  899.             df.setRepository(repo);
  900.             df.format(commitToPick.getParent(0), commitToPick);
  901.         }
  902.         rebaseState.createFile(PATCH, new String(bos.toByteArray(), UTF_8));
  903.         rebaseState.createFile(STOPPED_SHA,
  904.                 repo.newObjectReader()
  905.                 .abbreviate(
  906.                 commitToPick).name());
  907.         // Remove cherry pick state file created by CherryPickCommand, it's not
  908.         // needed for rebase
  909.         repo.writeCherryPickHead(null);
  910.         return RebaseResult.result(status, commitToPick);
  911.     }

  912.     String toAuthorScript(PersonIdent author) {
  913.         StringBuilder sb = new StringBuilder(100);
  914.         sb.append(GIT_AUTHOR_NAME);
  915.         sb.append("='"); //$NON-NLS-1$
  916.         sb.append(author.getName());
  917.         sb.append("'\n"); //$NON-NLS-1$
  918.         sb.append(GIT_AUTHOR_EMAIL);
  919.         sb.append("='"); //$NON-NLS-1$
  920.         sb.append(author.getEmailAddress());
  921.         sb.append("'\n"); //$NON-NLS-1$
  922.         // the command line uses the "external String"
  923.         // representation for date and timezone
  924.         sb.append(GIT_AUTHOR_DATE);
  925.         sb.append("='"); //$NON-NLS-1$
  926.         sb.append("@"); // @ for time in seconds since 1970 //$NON-NLS-1$
  927.         String externalString = author.toExternalString();
  928.         sb
  929.                 .append(externalString.substring(externalString
  930.                         .lastIndexOf('>') + 2));
  931.         sb.append("'\n"); //$NON-NLS-1$
  932.         return sb.toString();
  933.     }

  934.     /**
  935.      * Removes the number of lines given in the parameter from the
  936.      * <code>git-rebase-todo</code> file but preserves comments and other lines
  937.      * that can not be parsed as steps
  938.      *
  939.      * @param numSteps
  940.      * @throws IOException
  941.      */
  942.     private void popSteps(int numSteps) throws IOException {
  943.         if (numSteps == 0)
  944.             return;
  945.         List<RebaseTodoLine> todoLines = new LinkedList<>();
  946.         List<RebaseTodoLine> poppedLines = new LinkedList<>();

  947.         for (RebaseTodoLine line : repo.readRebaseTodo(
  948.                 rebaseState.getPath(GIT_REBASE_TODO), true)) {
  949.             if (poppedLines.size() >= numSteps
  950.                     || RebaseTodoLine.Action.COMMENT.equals(line.getAction()))
  951.                 todoLines.add(line);
  952.             else
  953.                 poppedLines.add(line);
  954.         }

  955.         repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  956.                 todoLines, false);
  957.         if (!poppedLines.isEmpty()) {
  958.             repo.writeRebaseTodoFile(rebaseState.getPath(DONE), poppedLines,
  959.                     true);
  960.         }
  961.     }

  962.     private RebaseResult initFilesAndRewind() throws IOException,
  963.             GitAPIException {
  964.         // we need to store everything into files so that we can implement
  965.         // --skip, --continue, and --abort

  966.         Ref head = getHead();

  967.         ObjectId headId = head.getObjectId();
  968.         if (headId == null) {
  969.             throw new RefNotFoundException(MessageFormat.format(
  970.                     JGitText.get().refNotResolved, Constants.HEAD));
  971.         }
  972.         String headName = getHeadName(head);
  973.         RevCommit headCommit = walk.lookupCommit(headId);
  974.         RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());

  975.         if (!isInteractive() && walk.isMergedInto(upstream, headCommit))
  976.             return RebaseResult.UP_TO_DATE_RESULT;
  977.         else if (!isInteractive() && walk.isMergedInto(headCommit, upstream)) {
  978.             // head is already merged into upstream, fast-foward
  979.             monitor.beginTask(MessageFormat.format(
  980.                     JGitText.get().resettingHead,
  981.                     upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  982.             checkoutCommit(headName, upstreamCommit);
  983.             monitor.endTask();

  984.             updateHead(headName, upstreamCommit, upstream);
  985.             return RebaseResult.FAST_FORWARD_RESULT;
  986.         }

  987.         monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
  988.                 ProgressMonitor.UNKNOWN);

  989.         // create the folder for the meta information
  990.         FileUtils.mkdir(rebaseState.getDir(), true);

  991.         repo.writeOrigHead(headId);
  992.         rebaseState.createFile(REBASE_HEAD, headId.name());
  993.         rebaseState.createFile(REBASE_HEAD_LEGACY, headId.name());
  994.         rebaseState.createFile(HEAD_NAME, headName);
  995.         rebaseState.createFile(ONTO, upstreamCommit.name());
  996.         rebaseState.createFile(ONTO_NAME, upstreamCommitName);
  997.         if (isInteractive() || preserveMerges) {
  998.             // --preserve-merges is an interactive mode for native git. Without
  999.             // this, native git rebase --continue after a conflict would fall
  1000.             // into merge mode.
  1001.             rebaseState.createFile(INTERACTIVE, ""); //$NON-NLS-1$
  1002.         }
  1003.         rebaseState.createFile(QUIET, ""); //$NON-NLS-1$

  1004.         ArrayList<RebaseTodoLine> toDoSteps = new ArrayList<>();
  1005.         toDoSteps.add(new RebaseTodoLine("# Created by EGit: rebasing " + headId.name() //$NON-NLS-1$
  1006.                         + " onto " + upstreamCommit.name())); //$NON-NLS-1$
  1007.         // determine the commits to be applied
  1008.         List<RevCommit> cherryPickList = calculatePickList(headCommit);
  1009.         ObjectReader reader = walk.getObjectReader();
  1010.         for (RevCommit commit : cherryPickList)
  1011.             toDoSteps.add(new RebaseTodoLine(Action.PICK, reader
  1012.                     .abbreviate(commit), commit.getShortMessage()));
  1013.         repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
  1014.                 toDoSteps, false);

  1015.         monitor.endTask();

  1016.         // we rewind to the upstream commit
  1017.         monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
  1018.                 upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
  1019.         boolean checkoutOk = false;
  1020.         try {
  1021.             checkoutOk = checkoutCommit(headName, upstreamCommit);
  1022.         } finally {
  1023.             if (!checkoutOk)
  1024.                 FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1025.         }
  1026.         monitor.endTask();

  1027.         return null;
  1028.     }

  1029.     private List<RevCommit> calculatePickList(RevCommit headCommit)
  1030.             throws GitAPIException, NoHeadException, IOException {
  1031.         List<RevCommit> cherryPickList = new ArrayList<>();
  1032.         try (RevWalk r = new RevWalk(repo)) {
  1033.             r.sort(RevSort.TOPO_KEEP_BRANCH_TOGETHER, true);
  1034.             r.sort(RevSort.COMMIT_TIME_DESC, true);
  1035.             r.markUninteresting(r.lookupCommit(upstreamCommit));
  1036.             r.markStart(r.lookupCommit(headCommit));
  1037.             Iterator<RevCommit> commitsToUse = r.iterator();
  1038.             while (commitsToUse.hasNext()) {
  1039.                 RevCommit commit = commitsToUse.next();
  1040.                 if (preserveMerges || commit.getParentCount() == 1) {
  1041.                     cherryPickList.add(commit);
  1042.                 }
  1043.             }
  1044.         }
  1045.         Collections.reverse(cherryPickList);

  1046.         if (preserveMerges) {
  1047.             // When preserving merges we only rewrite commits which have at
  1048.             // least one parent that is itself rewritten (or a merge base)
  1049.             File rewrittenDir = rebaseState.getRewrittenDir();
  1050.             FileUtils.mkdir(rewrittenDir, false);
  1051.             walk.reset();
  1052.             walk.setRevFilter(RevFilter.MERGE_BASE);
  1053.             walk.markStart(upstreamCommit);
  1054.             walk.markStart(headCommit);
  1055.             RevCommit base;
  1056.             while ((base = walk.next()) != null)
  1057.                 RebaseState.createFile(rewrittenDir, base.getName(),
  1058.                         upstreamCommit.getName());

  1059.             Iterator<RevCommit> iterator = cherryPickList.iterator();
  1060.             pickLoop: while(iterator.hasNext()){
  1061.                 RevCommit commit = iterator.next();
  1062.                 for (int i = 0; i < commit.getParentCount(); i++) {
  1063.                     boolean parentRewritten = new File(rewrittenDir, commit
  1064.                             .getParent(i).getName()).exists();
  1065.                     if (parentRewritten) {
  1066.                         new File(rewrittenDir, commit.getName()).createNewFile();
  1067.                         continue pickLoop;
  1068.                     }
  1069.                 }
  1070.                 // commit is only merged in, needs not be rewritten
  1071.                 iterator.remove();
  1072.             }
  1073.         }
  1074.         return cherryPickList;
  1075.     }

  1076.     private static String getHeadName(Ref head) {
  1077.         String headName;
  1078.         if (head.isSymbolic()) {
  1079.             headName = head.getTarget().getName();
  1080.         } else {
  1081.             ObjectId headId = head.getObjectId();
  1082.             // the callers are checking this already
  1083.             assert headId != null;
  1084.             headName = headId.getName();
  1085.         }
  1086.         return headName;
  1087.     }

  1088.     private Ref getHead() throws IOException, RefNotFoundException {
  1089.         Ref head = repo.exactRef(Constants.HEAD);
  1090.         if (head == null || head.getObjectId() == null)
  1091.             throw new RefNotFoundException(MessageFormat.format(
  1092.                     JGitText.get().refNotResolved, Constants.HEAD));
  1093.         return head;
  1094.     }

  1095.     private boolean isInteractive() {
  1096.         return interactiveHandler != null;
  1097.     }

  1098.     /**
  1099.      * Check if we can fast-forward and returns the new head if it is possible
  1100.      *
  1101.      * @param newCommit
  1102.      *            a {@link org.eclipse.jgit.revwalk.RevCommit} object to check
  1103.      *            if we can fast-forward to.
  1104.      * @return the new head, or null
  1105.      * @throws java.io.IOException
  1106.      * @throws org.eclipse.jgit.api.errors.GitAPIException
  1107.      */
  1108.     public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
  1109.             GitAPIException {
  1110.         Ref head = getHead();

  1111.         ObjectId headId = head.getObjectId();
  1112.         if (headId == null)
  1113.             throw new RefNotFoundException(MessageFormat.format(
  1114.                     JGitText.get().refNotResolved, Constants.HEAD));
  1115.         RevCommit headCommit = walk.lookupCommit(headId);
  1116.         if (walk.isMergedInto(newCommit, headCommit))
  1117.             return newCommit;

  1118.         String headName = getHeadName(head);
  1119.         return tryFastForward(headName, headCommit, newCommit);
  1120.     }

  1121.     private RevCommit tryFastForward(String headName, RevCommit oldCommit,
  1122.             RevCommit newCommit) throws IOException, GitAPIException {
  1123.         boolean tryRebase = false;
  1124.         for (RevCommit parentCommit : newCommit.getParents())
  1125.             if (parentCommit.equals(oldCommit))
  1126.                 tryRebase = true;
  1127.         if (!tryRebase)
  1128.             return null;

  1129.         CheckoutCommand co = new CheckoutCommand(repo);
  1130.         try {
  1131.             co.setProgressMonitor(monitor);
  1132.             co.setName(newCommit.name()).call();
  1133.             if (headName.startsWith(Constants.R_HEADS)) {
  1134.                 RefUpdate rup = repo.updateRef(headName);
  1135.                 rup.setExpectedOldObjectId(oldCommit);
  1136.                 rup.setNewObjectId(newCommit);
  1137.                 rup.setRefLogMessage("Fast-forward from " + oldCommit.name() //$NON-NLS-1$
  1138.                         + " to " + newCommit.name(), false); //$NON-NLS-1$
  1139.                 Result res = rup.update(walk);
  1140.                 switch (res) {
  1141.                 case FAST_FORWARD:
  1142.                 case NO_CHANGE:
  1143.                 case FORCED:
  1144.                     break;
  1145.                 default:
  1146.                     throw new IOException("Could not fast-forward"); //$NON-NLS-1$
  1147.                 }
  1148.             }
  1149.             return newCommit;
  1150.         } catch (RefAlreadyExistsException | RefNotFoundException
  1151.                 | InvalidRefNameException | CheckoutConflictException e) {
  1152.             throw new JGitInternalException(e.getMessage(), e);
  1153.         }
  1154.     }

  1155.     private void checkParameters() throws WrongRepositoryStateException {
  1156.         if (this.operation == Operation.PROCESS_STEPS) {
  1157.             if (rebaseState.getFile(DONE).exists())
  1158.                 throw new WrongRepositoryStateException(MessageFormat.format(
  1159.                         JGitText.get().wrongRepositoryState, repo
  1160.                                 .getRepositoryState().name()));
  1161.         }
  1162.         if (this.operation != Operation.BEGIN) {
  1163.             // these operations are only possible while in a rebasing state
  1164.             switch (repo.getRepositoryState()) {
  1165.             case REBASING_INTERACTIVE:
  1166.             case REBASING:
  1167.             case REBASING_REBASING:
  1168.             case REBASING_MERGE:
  1169.                 break;
  1170.             default:
  1171.                 throw new WrongRepositoryStateException(MessageFormat.format(
  1172.                         JGitText.get().wrongRepositoryState, repo
  1173.                                 .getRepositoryState().name()));
  1174.             }
  1175.         } else
  1176.             switch (repo.getRepositoryState()) {
  1177.             case SAFE:
  1178.                 if (this.upstreamCommit == null)
  1179.                     throw new JGitInternalException(MessageFormat
  1180.                             .format(JGitText.get().missingRequiredParameter,
  1181.                                     "upstream")); //$NON-NLS-1$
  1182.                 return;
  1183.             default:
  1184.                 throw new WrongRepositoryStateException(MessageFormat.format(
  1185.                         JGitText.get().wrongRepositoryState, repo
  1186.                                 .getRepositoryState().name()));

  1187.             }
  1188.     }

  1189.     private RebaseResult abort(RebaseResult result) throws IOException,
  1190.             GitAPIException {
  1191.         ObjectId origHead = getOriginalHead();
  1192.         try {
  1193.             String commitId = origHead != null ? origHead.name() : null;
  1194.             monitor.beginTask(MessageFormat.format(
  1195.                     JGitText.get().abortingRebase, commitId),
  1196.                     ProgressMonitor.UNKNOWN);

  1197.             DirCacheCheckout dco;
  1198.             if (commitId == null)
  1199.                 throw new JGitInternalException(
  1200.                         JGitText.get().abortingRebaseFailedNoOrigHead);
  1201.             ObjectId id = repo.resolve(commitId);
  1202.             RevCommit commit = walk.parseCommit(id);
  1203.             if (result.getStatus().equals(Status.FAILED)) {
  1204.                 RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1205.                 dco = new DirCacheCheckout(repo, head.getTree(),
  1206.                         repo.lockDirCache(), commit.getTree());
  1207.             } else {
  1208.                 dco = new DirCacheCheckout(repo, repo.lockDirCache(),
  1209.                         commit.getTree());
  1210.             }
  1211.             dco.setFailOnConflict(false);
  1212.             dco.checkout();
  1213.             walk.close();
  1214.         } finally {
  1215.             monitor.endTask();
  1216.         }
  1217.         try {
  1218.             String headName = rebaseState.readFile(HEAD_NAME);
  1219.                 monitor.beginTask(MessageFormat.format(
  1220.                         JGitText.get().resettingHead, headName),
  1221.                         ProgressMonitor.UNKNOWN);

  1222.             Result res = null;
  1223.             RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
  1224.             refUpdate.setRefLogMessage("rebase: aborting", false); //$NON-NLS-1$
  1225.             if (headName.startsWith(Constants.R_REFS)) {
  1226.                 // update the HEAD
  1227.                 res = refUpdate.link(headName);
  1228.             } else {
  1229.                 refUpdate.setNewObjectId(origHead);
  1230.                 res = refUpdate.forceUpdate();

  1231.             }
  1232.             switch (res) {
  1233.             case FAST_FORWARD:
  1234.             case FORCED:
  1235.             case NO_CHANGE:
  1236.                 break;
  1237.             default:
  1238.                 throw new JGitInternalException(
  1239.                         JGitText.get().abortingRebaseFailed);
  1240.             }
  1241.             boolean stashConflicts = autoStashApply();
  1242.             // cleanup the files
  1243.             FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
  1244.             repo.writeCherryPickHead(null);
  1245.             repo.writeMergeHeads(null);
  1246.             if (stashConflicts)
  1247.                 return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
  1248.             return result;

  1249.         } finally {
  1250.             monitor.endTask();
  1251.         }
  1252.     }

  1253.     private ObjectId getOriginalHead() throws IOException {
  1254.         try {
  1255.             return ObjectId.fromString(rebaseState.readFile(REBASE_HEAD));
  1256.         } catch (FileNotFoundException e) {
  1257.             try {
  1258.                 return ObjectId
  1259.                         .fromString(rebaseState.readFile(REBASE_HEAD_LEGACY));
  1260.             } catch (FileNotFoundException ex) {
  1261.                 return repo.readOrigHead();
  1262.             }
  1263.         }
  1264.     }

  1265.     private boolean checkoutCommit(String headName, RevCommit commit)
  1266.             throws IOException,
  1267.             CheckoutConflictException {
  1268.         try {
  1269.             RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
  1270.             DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
  1271.                     repo.lockDirCache(), commit.getTree());
  1272.             dco.setFailOnConflict(true);
  1273.             dco.setProgressMonitor(monitor);
  1274.             try {
  1275.                 dco.checkout();
  1276.             } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
  1277.                 throw new CheckoutConflictException(dco.getConflicts(), cce);
  1278.             }
  1279.             // update the HEAD
  1280.             RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
  1281.             refUpdate.setExpectedOldObjectId(head);
  1282.             refUpdate.setNewObjectId(commit);
  1283.             refUpdate.setRefLogMessage(
  1284.                     "checkout: moving from " //$NON-NLS-1$
  1285.                             + Repository.shortenRefName(headName)
  1286.                             + " to " + commit.getName(), false); //$NON-NLS-1$
  1287.             Result res = refUpdate.forceUpdate();
  1288.             switch (res) {
  1289.             case FAST_FORWARD:
  1290.             case NO_CHANGE:
  1291.             case FORCED:
  1292.                 break;
  1293.             default:
  1294.                 throw new IOException(
  1295.                         JGitText.get().couldNotRewindToUpstreamCommit);
  1296.             }
  1297.         } finally {
  1298.             walk.close();
  1299.             monitor.endTask();
  1300.         }
  1301.         return true;
  1302.     }


  1303.     /**
  1304.      * Set upstream {@code RevCommit}
  1305.      *
  1306.      * @param upstream
  1307.      *            the upstream commit
  1308.      * @return {@code this}
  1309.      */
  1310.     public RebaseCommand setUpstream(RevCommit upstream) {
  1311.         this.upstreamCommit = upstream;
  1312.         this.upstreamCommitName = upstream.name();
  1313.         return this;
  1314.     }

  1315.     /**
  1316.      * Set the upstream commit
  1317.      *
  1318.      * @param upstream
  1319.      *            id of the upstream commit
  1320.      * @return {@code this}
  1321.      */
  1322.     public RebaseCommand setUpstream(AnyObjectId upstream) {
  1323.         try {
  1324.             this.upstreamCommit = walk.parseCommit(upstream);
  1325.             this.upstreamCommitName = upstream.name();
  1326.         } catch (IOException e) {
  1327.             throw new JGitInternalException(MessageFormat.format(
  1328.                     JGitText.get().couldNotReadObjectWhileParsingCommit,
  1329.                     upstream.name()), e);
  1330.         }
  1331.         return this;
  1332.     }

  1333.     /**
  1334.      * Set the upstream branch
  1335.      *
  1336.      * @param upstream
  1337.      *            the name of the upstream branch
  1338.      * @return {@code this}
  1339.      * @throws org.eclipse.jgit.api.errors.RefNotFoundException
  1340.      */
  1341.     public RebaseCommand setUpstream(String upstream)
  1342.             throws RefNotFoundException {
  1343.         try {
  1344.             ObjectId upstreamId = repo.resolve(upstream);
  1345.             if (upstreamId == null)
  1346.                 throw new RefNotFoundException(MessageFormat.format(JGitText
  1347.                         .get().refNotResolved, upstream));
  1348.             upstreamCommit = walk.parseCommit(repo.resolve(upstream));
  1349.             upstreamCommitName = upstream;
  1350.             return this;
  1351.         } catch (IOException ioe) {
  1352.             throw new JGitInternalException(ioe.getMessage(), ioe);
  1353.         }
  1354.     }

  1355.     /**
  1356.      * Optionally override the name of the upstream. If this is used, it has to
  1357.      * come after any {@link #setUpstream} call.
  1358.      *
  1359.      * @param upstreamName
  1360.      *            the name which will be used to refer to upstream in conflicts
  1361.      * @return {@code this}
  1362.      */
  1363.     public RebaseCommand setUpstreamName(String upstreamName) {
  1364.         if (upstreamCommit == null) {
  1365.             throw new IllegalStateException(
  1366.                     "setUpstreamName must be called after setUpstream."); //$NON-NLS-1$
  1367.         }
  1368.         this.upstreamCommitName = upstreamName;
  1369.         return this;
  1370.     }

  1371.     /**
  1372.      * Set the operation to execute during rebase
  1373.      *
  1374.      * @param operation
  1375.      *            the operation to perform
  1376.      * @return {@code this}
  1377.      */
  1378.     public RebaseCommand setOperation(Operation operation) {
  1379.         this.operation = operation;
  1380.         return this;
  1381.     }

  1382.     /**
  1383.      * Set progress monitor
  1384.      *
  1385.      * @param monitor
  1386.      *            a progress monitor
  1387.      * @return this instance
  1388.      */
  1389.     public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
  1390.         if (monitor == null) {
  1391.             monitor = NullProgressMonitor.INSTANCE;
  1392.         }
  1393.         this.monitor = monitor;
  1394.         return this;
  1395.     }

  1396.     /**
  1397.      * Enable interactive rebase
  1398.      * <p>
  1399.      * Does not stop after initialization of interactive rebase. This is
  1400.      * equivalent to
  1401.      * {@link org.eclipse.jgit.api.RebaseCommand#runInteractively(InteractiveHandler, boolean)
  1402.      * runInteractively(handler, false)};
  1403.      * </p>
  1404.      *
  1405.      * @param handler
  1406.      *            the
  1407.      *            {@link org.eclipse.jgit.api.RebaseCommand.InteractiveHandler}
  1408.      *            to use
  1409.      * @return this
  1410.      */
  1411.     public RebaseCommand runInteractively(InteractiveHandler handler) {
  1412.         return runInteractively(handler, false);
  1413.     }

  1414.     /**
  1415.      * Enable interactive rebase
  1416.      * <p>
  1417.      * If stopAfterRebaseInteractiveInitialization is {@code true} the rebase
  1418.      * stops after initialization of interactive rebase returning
  1419.      * {@link org.eclipse.jgit.api.RebaseResult#INTERACTIVE_PREPARED_RESULT}
  1420.      * </p>
  1421.      *
  1422.      * @param handler
  1423.      *            the
  1424.      *            {@link org.eclipse.jgit.api.RebaseCommand.InteractiveHandler}
  1425.      *            to use
  1426.      * @param stopAfterRebaseInteractiveInitialization
  1427.      *            if {@code true} the rebase stops after initialization
  1428.      * @return this instance
  1429.      * @since 3.2
  1430.      */
  1431.     public RebaseCommand runInteractively(InteractiveHandler handler,
  1432.             final boolean stopAfterRebaseInteractiveInitialization) {
  1433.         this.stopAfterInitialization = stopAfterRebaseInteractiveInitialization;
  1434.         this.interactiveHandler = handler;
  1435.         return this;
  1436.     }

  1437.     /**
  1438.      * Set the <code>MergeStrategy</code>.
  1439.      *
  1440.      * @param strategy
  1441.      *            The merge strategy to use during this rebase operation.
  1442.      * @return {@code this}
  1443.      * @since 3.4
  1444.      */
  1445.     public RebaseCommand setStrategy(MergeStrategy strategy) {
  1446.         this.strategy = strategy;
  1447.         return this;
  1448.     }

  1449.     /**
  1450.      * Whether to preserve merges during rebase
  1451.      *
  1452.      * @param preserve
  1453.      *            {@code true} to re-create merges during rebase. Defaults to
  1454.      *            {@code false}, a flattening rebase.
  1455.      * @return {@code this}
  1456.      * @since 3.5
  1457.      */
  1458.     public RebaseCommand setPreserveMerges(boolean preserve) {
  1459.         this.preserveMerges = preserve;
  1460.         return this;
  1461.     }

  1462.     /**
  1463.      * Allows configure rebase interactive process and modify commit message
  1464.      */
  1465.     public interface InteractiveHandler {
  1466.         /**
  1467.          * Given list of {@code steps} should be modified according to user
  1468.          * rebase configuration
  1469.          * @param steps
  1470.          *            initial configuration of rebase interactive
  1471.          */
  1472.         void prepareSteps(List<RebaseTodoLine> steps);

  1473.         /**
  1474.          * Used for editing commit message on REWORD
  1475.          *
  1476.          * @param commit
  1477.          * @return new commit message
  1478.          */
  1479.         String modifyCommitMessage(String commit);
  1480.     }


  1481.     PersonIdent parseAuthor(byte[] raw) {
  1482.         if (raw.length == 0)
  1483.             return null;

  1484.         Map<String, String> keyValueMap = new HashMap<>();
  1485.         for (int p = 0; p < raw.length;) {
  1486.             int end = RawParseUtils.nextLF(raw, p);
  1487.             if (end == p)
  1488.                 break;
  1489.             int equalsIndex = RawParseUtils.next(raw, p, '=');
  1490.             if (equalsIndex == end)
  1491.                 break;
  1492.             String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
  1493.             String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
  1494.             p = end;
  1495.             keyValueMap.put(key, value);
  1496.         }

  1497.         String name = keyValueMap.get(GIT_AUTHOR_NAME);
  1498.         String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
  1499.         String time = keyValueMap.get(GIT_AUTHOR_DATE);

  1500.         // the time is saved as <seconds since 1970> <timezone offset>
  1501.         int timeStart = 0;
  1502.         if (time.startsWith("@")) //$NON-NLS-1$
  1503.             timeStart = 1;
  1504.         else
  1505.             timeStart = 0;
  1506.         long when = Long
  1507.                 .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
  1508.         String tzOffsetString = time.substring(time.indexOf(' ') + 1);
  1509.         int multiplier = -1;
  1510.         if (tzOffsetString.charAt(0) == '+')
  1511.             multiplier = 1;
  1512.         int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
  1513.         int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
  1514.         // this is in format (+/-)HHMM (hours and minutes)
  1515.         // we need to convert into minutes
  1516.         int tz = (hours * 60 + minutes) * multiplier;
  1517.         if (name != null && email != null)
  1518.             return new PersonIdent(name, email, when, tz);
  1519.         return null;
  1520.     }

  1521.     private static class RebaseState {

  1522.         private final File repoDirectory;
  1523.         private File dir;

  1524.         public RebaseState(File repoDirectory) {
  1525.             this.repoDirectory = repoDirectory;
  1526.         }

  1527.         public File getDir() {
  1528.             if (dir == null) {
  1529.                 File rebaseApply = new File(repoDirectory, REBASE_APPLY);
  1530.                 if (rebaseApply.exists()) {
  1531.                     dir = rebaseApply;
  1532.                 } else {
  1533.                     File rebaseMerge = new File(repoDirectory, REBASE_MERGE);
  1534.                     dir = rebaseMerge;
  1535.                 }
  1536.             }
  1537.             return dir;
  1538.         }

  1539.         /**
  1540.          * @return Directory with rewritten commit hashes, usually exists if
  1541.          *         {@link RebaseCommand#preserveMerges} is true
  1542.          **/
  1543.         public File getRewrittenDir() {
  1544.             return new File(getDir(), REWRITTEN);
  1545.         }

  1546.         public String readFile(String name) throws IOException {
  1547.             try {
  1548.                 return readFile(getDir(), name);
  1549.             } catch (FileNotFoundException e) {
  1550.                 if (ONTO_NAME.equals(name)) {
  1551.                     // Older JGit mistakenly wrote a file "onto-name" instead of
  1552.                     // "onto_name". Try that wrong name just in case somebody
  1553.                     // upgraded while a rebase started by JGit was in progress.
  1554.                     File oldFile = getFile(ONTO_NAME.replace('_', '-'));
  1555.                     if (oldFile.exists()) {
  1556.                         return readFile(oldFile);
  1557.                     }
  1558.                 }
  1559.                 throw e;
  1560.             }
  1561.         }

  1562.         public void createFile(String name, String content) throws IOException {
  1563.             createFile(getDir(), name, content);
  1564.         }

  1565.         public File getFile(String name) {
  1566.             return new File(getDir(), name);
  1567.         }

  1568.         public String getPath(String name) {
  1569.             return (getDir().getName() + "/" + name); //$NON-NLS-1$
  1570.         }

  1571.         private static String readFile(File file) throws IOException {
  1572.             byte[] content = IO.readFully(file);
  1573.             // strip off the last LF
  1574.             int end = RawParseUtils.prevLF(content, content.length);
  1575.             return RawParseUtils.decode(content, 0, end + 1);
  1576.         }

  1577.         private static String readFile(File directory, String fileName)
  1578.                 throws IOException {
  1579.             return readFile(new File(directory, fileName));
  1580.         }

  1581.         private static void createFile(File parentDir, String name,
  1582.                 String content)
  1583.                 throws IOException {
  1584.             File file = new File(parentDir, name);
  1585.             try (FileOutputStream fos = new FileOutputStream(file)) {
  1586.                 fos.write(content.getBytes(UTF_8));
  1587.                 fos.write('\n');
  1588.             }
  1589.         }

  1590.         private static void appendToFile(File file, String content)
  1591.                 throws IOException {
  1592.             try (FileOutputStream fos = new FileOutputStream(file, true)) {
  1593.                 fos.write(content.getBytes(UTF_8));
  1594.                 fos.write('\n');
  1595.             }
  1596.         }
  1597.     }
  1598. }