1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
112
113
114
115
116
117
118
119
120
121 public class RebaseCommand extends GitCommand<RebaseResult> {
122
123
124
125 public static final String REBASE_MERGE = "rebase-merge";
126
127
128
129
130 private static final String REBASE_APPLY = "rebase-apply";
131
132
133
134
135 public static final String STOPPED_SHA = "stopped-sha";
136
137 private static final String AUTHOR_SCRIPT = "author-script";
138
139 private static final String DONE = "done";
140
141 private static final String GIT_AUTHOR_DATE = "GIT_AUTHOR_DATE";
142
143 private static final String GIT_AUTHOR_EMAIL = "GIT_AUTHOR_EMAIL";
144
145 private static final String GIT_AUTHOR_NAME = "GIT_AUTHOR_NAME";
146
147 private static final String GIT_REBASE_TODO = "git-rebase-todo";
148
149 private static final String HEAD_NAME = "head-name";
150
151 private static final String INTERACTIVE = "interactive";
152
153 private static final String QUIET = "quiet";
154
155 private static final String MESSAGE = "message";
156
157 private static final String ONTO = "onto";
158
159 private static final String ONTO_NAME = "onto-name";
160
161 private static final String PATCH = "patch";
162
163 private static final String REBASE_HEAD = "head";
164
165 private static final String AMEND = "amend";
166
167 private static final String MESSAGE_FIXUP = "message-fixup";
168
169 private static final String MESSAGE_SQUASH = "message-squash";
170
171 private static final String AUTOSTASH = "autostash";
172
173 private static final String AUTOSTASH_MSG = "On {0}: autostash";
174
175
176
177
178
179 private static final String REWRITTEN = "rewritten";
180
181
182
183
184
185 private static final String CURRENT_COMMIT = "current-commit";
186
187 private static final String REFLOG_PREFIX = "rebase:";
188
189
190
191
192 public enum Operation {
193
194
195
196 BEGIN,
197
198
199
200 CONTINUE,
201
202
203
204 SKIP,
205
206
207
208 ABORT,
209
210
211
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
242
243 protected RebaseCommand(Repository repo) {
244 super(repo);
245 walk = new RevWalk(repo);
246 rebaseState = new RebaseState(repo.getDirectory());
247 }
248
249
250
251
252
253
254
255
256
257
258
259
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
278 case SKIP:
279
280 case CONTINUE:
281 String upstreamCommitId = rebaseState.readFile(ONTO);
282 try {
283 upstreamCommitName = rebaseState.readFile(ONTO_NAME);
284 } catch (FileNotFoundException e) {
285
286
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
344
345
346
347
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;
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
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
517
518
519 newHead = tryFastForward(commitToPick);
520 lastStepWasForward = newHead != null;
521 if (!lastStepWasForward) {
522
523
524
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
561
562
563 newHead = otherParentsUnchanged ? tryFastForward(commitToPick) : null;
564 lastStepWasForward = newHead != null;
565 if (!lastStepWasForward) {
566 ObjectId headId = getHead().getObjectId();
567
568 assert headId != null;
569 if (!AnyObjectId.equals(headId, newParents.get(0)))
570 checkoutCommit(headId.getName(), newParents.get(0));
571
572
573
574
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
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
603
604 CommitCommand commit = git.commit();
605 commit.setAuthor(commitToPick.getAuthorIdent());
606 commit.setReflogComment(REFLOG_PREFIX + " "
607 + commitToPick.getShortMessage());
608 newHead = commit.call();
609 } else
610 newHead = cherryPickResult.getNewHead();
611 break;
612 }
613 } else {
614
615
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 + " "
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
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
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
685 assert headId != null;
686 String head = headId.getName();
687 String currentCommits = rebaseState.readFile(CURRENT_COMMIT);
688 for (String current : currentCommits.split("\n"))
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
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
761
762
763
764 git.reset().setMode(ResetType.SOFT)
765 .setRef("HEAD~1").call();
766 } finally {
767
768
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
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
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")) {
806 if (!line.trim().startsWith("#"))
807 result.append(line).append("\n");
808 }
809 if (!commitMessage.endsWith("\n")) {
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
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";
846 case 2:
847 return "nd";
848 case 3:
849 return "rd";
850 default:
851 return "th";
852 }
853 }
854
855
856
857
858
859
860
861
862 static int parseSquashFixupSequenceCount(String currSquashMessage) {
863 String regex = "This is a combination of (.*) commits";
864 String firstLine = currSquashMessage.substring(0,
865 currSquashMessage.indexOf("\n"));
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);
879 }
880
881 private String getOurCommitName() {
882
883
884 String ourCommitName = "Upstream, based on "
885 + Repository.shortenRefName(upstreamCommitName);
886 return ourCommitName;
887 }
888
889 private void updateHead(String headName, RevCommit aNewHead, RevCommit onto)
890 throws IOException {
891
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 "
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,
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}");
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
954
955
956
957 private RevCommit continueRebase() throws GitAPIException, IOException {
958
959 DirCache dc = repo.readDirCache();
960 boolean hasUnmergedPaths = dc.hasUnmergedPaths();
961 if (hasUnmergedPaths)
962 throw new UnmergedPathsException();
963
964
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}");
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
1024
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("='");
1033 sb.append(author.getName());
1034 sb.append("'\n");
1035 sb.append(GIT_AUTHOR_EMAIL);
1036 sb.append("='");
1037 sb.append(author.getEmailAddress());
1038 sb.append("'\n");
1039
1040
1041 sb.append(GIT_AUTHOR_DATE);
1042 sb.append("='");
1043 sb.append("@");
1044 String externalString = author.toExternalString();
1045 sb
1046 .append(externalString.substring(externalString
1047 .lastIndexOf('>') + 2));
1048 sb.append("'\n");
1049 return sb.toString();
1050 }
1051
1052
1053
1054
1055
1056
1057
1058
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
1086
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
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
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, "");
1126 }
1127 rebaseState.createFile(QUIET, "");
1128
1129 ArrayList<RebaseTodoLine> toDoSteps = new ArrayList<>();
1130 toDoSteps.add(new RebaseTodoLine("# Created by EGit: rebasing " + headId.name()
1131 + " onto " + upstreamCommit.name()));
1132
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
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
1174
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
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
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
1231
1232
1233
1234
1235
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()
1270 + " to " + newCommit.name(), false);
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");
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
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"));
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);
1367 if (headName.startsWith(Constants.R_REFS)) {
1368
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
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
1412 RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
1413 refUpdate.setExpectedOldObjectId(head);
1414 refUpdate.setNewObjectId(commit);
1415 refUpdate.setRefLogMessage(
1416 "checkout: moving from "
1417 + Repository.shortenRefName(headName)
1418 + " to " + commit.getName(), false);
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
1439
1440
1441
1442 public RebaseCommand setUpstream(RevCommit upstream) {
1443 this.upstreamCommit = upstream;
1444 this.upstreamCommitName = upstream.name();
1445 return this;
1446 }
1447
1448
1449
1450
1451
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
1467
1468
1469
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
1488
1489
1490
1491
1492
1493
1494 public RebaseCommand setUpstreamName(String upstreamName) {
1495 if (upstreamCommit == null) {
1496 throw new IllegalStateException(
1497 "setUpstreamName must be called after setUpstream.");
1498 }
1499 this.upstreamCommitName = upstreamName;
1500 return this;
1501 }
1502
1503
1504
1505
1506
1507
1508 public RebaseCommand setOperation(Operation operation) {
1509 this.operation = operation;
1510 return this;
1511 }
1512
1513
1514
1515
1516
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
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538 public RebaseCommand runInteractively(InteractiveHandler handler) {
1539 return runInteractively(handler, false);
1540 }
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
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
1565
1566
1567
1568
1569 public RebaseCommand setStrategy(MergeStrategy strategy) {
1570 this.strategy = strategy;
1571 return this;
1572 }
1573
1574
1575
1576
1577
1578
1579
1580
1581 public RebaseCommand setPreserveMerges(boolean preserve) {
1582 this.preserveMerges = preserve;
1583 return this;
1584 }
1585
1586
1587
1588
1589 public interface InteractiveHandler {
1590
1591
1592
1593
1594
1595
1596 void prepareSteps(List<RebaseTodoLine> steps);
1597
1598
1599
1600
1601
1602
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
1631 int timeStart = 0;
1632 if (time.startsWith("@"))
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
1645
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
1676
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);
1696 }
1697
1698 private static String readFile(File directory, String fileName)
1699 throws IOException {
1700 byte[] content = IO.readFully(new File(directory, fileName));
1701
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 }