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