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
244
245
246
247
248 protected RebaseCommand(Repository repo) {
249 super(repo);
250 walk = new RevWalk(repo);
251 rebaseState = new RebaseState(repo.getDirectory());
252 }
253
254
255
256
257
258
259
260
261
262 @Override
263 public RebaseResult call() throws GitAPIException, NoHeadException,
264 RefNotFoundException, WrongRepositoryStateException {
265 newHead = null;
266 lastStepWasForward = false;
267 checkCallable();
268 checkParameters();
269 try {
270 switch (operation) {
271 case ABORT:
272 try {
273 return abort(RebaseResult.ABORTED_RESULT);
274 } catch (IOException ioe) {
275 throw new JGitInternalException(ioe.getMessage(), ioe);
276 }
277 case PROCESS_STEPS:
278
279 case SKIP:
280
281 case CONTINUE:
282 String upstreamCommitId = rebaseState.readFile(ONTO);
283 try {
284 upstreamCommitName = rebaseState.readFile(ONTO_NAME);
285 } catch (FileNotFoundException e) {
286
287
288 upstreamCommitName = upstreamCommitId;
289 }
290 this.upstreamCommit = walk.parseCommit(repo
291 .resolve(upstreamCommitId));
292 preserveMerges = rebaseState.getRewrittenDir().exists();
293 break;
294 case BEGIN:
295 autoStash();
296 if (stopAfterInitialization
297 || !walk.isMergedInto(
298 walk.parseCommit(repo.resolve(Constants.HEAD)),
299 upstreamCommit)) {
300 org.eclipse.jgit.api.Status status = Git.wrap(repo)
301 .status().setIgnoreSubmodules(IgnoreSubmoduleMode.ALL).call();
302 if (status.hasUncommittedChanges()) {
303 List<String> list = new ArrayList<>();
304 list.addAll(status.getUncommittedChanges());
305 return RebaseResult.uncommittedChanges(list);
306 }
307 }
308 RebaseResult res = initFilesAndRewind();
309 if (stopAfterInitialization)
310 return RebaseResult.INTERACTIVE_PREPARED_RESULT;
311 if (res != null) {
312 autoStashApply();
313 if (rebaseState.getDir().exists())
314 FileUtils.delete(rebaseState.getDir(),
315 FileUtils.RECURSIVE);
316 return res;
317 }
318 }
319
320 if (monitor.isCancelled())
321 return abort(RebaseResult.ABORTED_RESULT);
322
323 if (operation == Operation.CONTINUE) {
324 newHead = continueRebase();
325 List<RebaseTodoLine> doneLines = repo.readRebaseTodo(
326 rebaseState.getPath(DONE), true);
327 RebaseTodoLine step = doneLines.get(doneLines.size() - 1);
328 if (newHead != null
329 && step.getAction() != Action.PICK) {
330 RebaseTodoLine newStep = new RebaseTodoLine(
331 step.getAction(),
332 AbbreviatedObjectId.fromObjectId(newHead),
333 step.getShortMessage());
334 RebaseResult result = processStep(newStep, false);
335 if (result != null)
336 return result;
337 }
338 File amendFile = rebaseState.getFile(AMEND);
339 boolean amendExists = amendFile.exists();
340 if (amendExists) {
341 FileUtils.delete(amendFile);
342 }
343 if (newHead == null && !amendExists) {
344
345
346
347
348
349 return RebaseResult.NOTHING_TO_COMMIT_RESULT;
350 }
351 }
352
353 if (operation == Operation.SKIP)
354 newHead = checkoutCurrentHead();
355
356 List<RebaseTodoLine> steps = repo.readRebaseTodo(
357 rebaseState.getPath(GIT_REBASE_TODO), false);
358 if (steps.size() == 0) {
359 return finishRebase(walk.parseCommit(repo.resolve(Constants.HEAD)), false);
360 }
361 if (isInteractive()) {
362 interactiveHandler.prepareSteps(steps);
363 repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
364 steps, false);
365 }
366 checkSteps(steps);
367 for (int i = 0; i < steps.size(); i++) {
368 RebaseTodoLine step = steps.get(i);
369 popSteps(1);
370 RebaseResult result = processStep(step, true);
371 if (result != null) {
372 return result;
373 }
374 }
375 return finishRebase(newHead, lastStepWasForward);
376 } catch (CheckoutConflictException cce) {
377 return RebaseResult.conflicts(cce.getConflictingPaths());
378 } catch (IOException ioe) {
379 throw new JGitInternalException(ioe.getMessage(), ioe);
380 }
381 }
382
383 private void autoStash() throws GitAPIException, IOException {
384 if (repo.getConfig().getBoolean(ConfigConstants.CONFIG_REBASE_SECTION,
385 ConfigConstants.CONFIG_KEY_AUTOSTASH, false)) {
386 String message = MessageFormat.format(
387 AUTOSTASH_MSG,
388 Repository
389 .shortenRefName(getHeadName(getHead())));
390 RevCommit stashCommit = Git.wrap(repo).stashCreate().setRef(null)
391 .setWorkingDirectoryMessage(
392 message)
393 .call();
394 if (stashCommit != null) {
395 FileUtils.mkdir(rebaseState.getDir());
396 rebaseState.createFile(AUTOSTASH, stashCommit.getName());
397 }
398 }
399 }
400
401 private boolean autoStashApply() throws IOException, GitAPIException {
402 boolean conflicts = false;
403 if (rebaseState.getFile(AUTOSTASH).exists()) {
404 String stash = rebaseState.readFile(AUTOSTASH);
405 try (Git git = Git.wrap(repo)) {
406 git.stashApply().setStashRef(stash)
407 .ignoreRepositoryState(true).setStrategy(strategy)
408 .call();
409 } catch (StashApplyFailureException e) {
410 conflicts = true;
411 try (RevWalk rw = new RevWalk(repo)) {
412 ObjectId stashId = repo.resolve(stash);
413 RevCommit commit = rw.parseCommit(stashId);
414 updateStashRef(commit, commit.getAuthorIdent(),
415 commit.getShortMessage());
416 }
417 }
418 }
419 return conflicts;
420 }
421
422 private void updateStashRef(ObjectId commitId, PersonIdent refLogIdent,
423 String refLogMessage) throws IOException {
424 Ref currentRef = repo.exactRef(Constants.R_STASH);
425 RefUpdate refUpdate = repo.updateRef(Constants.R_STASH);
426 refUpdate.setNewObjectId(commitId);
427 refUpdate.setRefLogIdent(refLogIdent);
428 refUpdate.setRefLogMessage(refLogMessage, false);
429 refUpdate.setForceRefLog(true);
430 if (currentRef != null)
431 refUpdate.setExpectedOldObjectId(currentRef.getObjectId());
432 else
433 refUpdate.setExpectedOldObjectId(ObjectId.zeroId());
434 refUpdate.forceUpdate();
435 }
436
437 private RebaseResult processStep(RebaseTodoLine step, boolean shouldPick)
438 throws IOException, GitAPIException {
439 if (Action.COMMENT.equals(step.getAction()))
440 return null;
441 if (preserveMerges
442 && shouldPick
443 && (Action.EDIT.equals(step.getAction()) || Action.PICK
444 .equals(step.getAction()))) {
445 writeRewrittenHashes();
446 }
447 ObjectReader or = repo.newObjectReader();
448
449 Collection<ObjectId> ids = or.resolve(step.getCommit());
450 if (ids.size() != 1)
451 throw new JGitInternalException(
452 JGitText.get().cannotResolveUniquelyAbbrevObjectId);
453 RevCommit commitToPick = walk.parseCommit(ids.iterator().next());
454 if (shouldPick) {
455 if (monitor.isCancelled())
456 return RebaseResult.result(Status.STOPPED, commitToPick);
457 RebaseResult result = cherryPickCommit(commitToPick);
458 if (result != null)
459 return result;
460 }
461 boolean isSquash = false;
462 switch (step.getAction()) {
463 case PICK:
464 return null;
465 case REWORD:
466 String oldMessage = commitToPick.getFullMessage();
467 String newMessage = interactiveHandler
468 .modifyCommitMessage(oldMessage);
469 try (Git git = new Git(repo)) {
470 newHead = git.commit().setMessage(newMessage).setAmend(true)
471 .setNoVerify(true).call();
472 }
473 return null;
474 case EDIT:
475 rebaseState.createFile(AMEND, commitToPick.name());
476 return stop(commitToPick, Status.EDIT);
477 case COMMENT:
478 break;
479 case SQUASH:
480 isSquash = true;
481
482 case FIXUP:
483 resetSoftToParent();
484 List<RebaseTodoLine> steps = repo.readRebaseTodo(
485 rebaseState.getPath(GIT_REBASE_TODO), false);
486 RebaseTodoLine nextStep = steps.size() > 0 ? steps.get(0) : null;
487 File messageFixupFile = rebaseState.getFile(MESSAGE_FIXUP);
488 File messageSquashFile = rebaseState.getFile(MESSAGE_SQUASH);
489 if (isSquash && messageFixupFile.exists())
490 messageFixupFile.delete();
491 newHead = doSquashFixup(isSquash, commitToPick, nextStep,
492 messageFixupFile, messageSquashFile);
493 }
494 return null;
495 }
496
497 private RebaseResult cherryPickCommit(RevCommit commitToPick)
498 throws IOException, GitAPIException, NoMessageException,
499 UnmergedPathsException, ConcurrentRefUpdateException,
500 WrongRepositoryStateException, NoHeadException {
501 try {
502 monitor.beginTask(MessageFormat.format(
503 JGitText.get().applyingCommit,
504 commitToPick.getShortMessage()), ProgressMonitor.UNKNOWN);
505 if (preserveMerges)
506 return cherryPickCommitPreservingMerges(commitToPick);
507 else
508 return cherryPickCommitFlattening(commitToPick);
509 } finally {
510 monitor.endTask();
511 }
512 }
513
514 private RebaseResult cherryPickCommitFlattening(RevCommit commitToPick)
515 throws IOException, GitAPIException, NoMessageException,
516 UnmergedPathsException, ConcurrentRefUpdateException,
517 WrongRepositoryStateException, NoHeadException {
518
519
520
521 newHead = tryFastForward(commitToPick);
522 lastStepWasForward = newHead != null;
523 if (!lastStepWasForward) {
524
525
526
527 String ourCommitName = getOurCommitName();
528 try (Git git = new Git(repo)) {
529 CherryPickResult cherryPickResult = git.cherryPick()
530 .include(commitToPick).setOurCommitName(ourCommitName)
531 .setReflogPrefix(REFLOG_PREFIX).setStrategy(strategy)
532 .call();
533 switch (cherryPickResult.getStatus()) {
534 case FAILED:
535 if (operation == Operation.BEGIN)
536 return abort(RebaseResult
537 .failed(cherryPickResult.getFailingPaths()));
538 else
539 return stop(commitToPick, Status.STOPPED);
540 case CONFLICTING:
541 return stop(commitToPick, Status.STOPPED);
542 case OK:
543 newHead = cherryPickResult.getNewHead();
544 }
545 }
546 }
547 return null;
548 }
549
550 private RebaseResult cherryPickCommitPreservingMerges(RevCommit commitToPick)
551 throws IOException, GitAPIException, NoMessageException,
552 UnmergedPathsException, ConcurrentRefUpdateException,
553 WrongRepositoryStateException, NoHeadException {
554
555 writeCurrentCommit(commitToPick);
556
557 List<RevCommit> newParents = getNewParents(commitToPick);
558 boolean otherParentsUnchanged = true;
559 for (int i = 1; i < commitToPick.getParentCount(); i++)
560 otherParentsUnchanged &= newParents.get(i).equals(
561 commitToPick.getParent(i));
562
563
564
565 newHead = otherParentsUnchanged ? tryFastForward(commitToPick) : null;
566 lastStepWasForward = newHead != null;
567 if (!lastStepWasForward) {
568 ObjectId headId = getHead().getObjectId();
569
570 assert headId != null;
571 if (!AnyObjectId.equals(headId, newParents.get(0)))
572 checkoutCommit(headId.getName(), newParents.get(0));
573
574
575
576
577 try (Git git = new Git(repo)) {
578 if (otherParentsUnchanged) {
579 boolean isMerge = commitToPick.getParentCount() > 1;
580 String ourCommitName = getOurCommitName();
581 CherryPickCommand pickCommand = git.cherryPick()
582 .include(commitToPick)
583 .setOurCommitName(ourCommitName)
584 .setReflogPrefix(REFLOG_PREFIX)
585 .setStrategy(strategy);
586 if (isMerge) {
587 pickCommand.setMainlineParentNumber(1);
588
589 pickCommand.setNoCommit(true);
590 writeMergeInfo(commitToPick, newParents);
591 }
592 CherryPickResult cherryPickResult = pickCommand.call();
593 switch (cherryPickResult.getStatus()) {
594 case FAILED:
595 if (operation == Operation.BEGIN)
596 return abort(RebaseResult.failed(
597 cherryPickResult.getFailingPaths()));
598 else
599 return stop(commitToPick, Status.STOPPED);
600 case CONFLICTING:
601 return stop(commitToPick, Status.STOPPED);
602 case OK:
603 if (isMerge) {
604
605
606 CommitCommand commit = git.commit();
607 commit.setAuthor(commitToPick.getAuthorIdent());
608 commit.setReflogComment(REFLOG_PREFIX + " "
609 + commitToPick.getShortMessage());
610 newHead = commit.call();
611 } else
612 newHead = cherryPickResult.getNewHead();
613 break;
614 }
615 } else {
616
617
618 MergeCommand merge = git.merge()
619 .setFastForward(MergeCommand.FastForwardMode.NO_FF)
620 .setProgressMonitor(monitor)
621 .setCommit(false);
622 for (int i = 1; i < commitToPick.getParentCount(); i++)
623 merge.include(newParents.get(i));
624 MergeResult mergeResult = merge.call();
625 if (mergeResult.getMergeStatus().isSuccessful()) {
626 CommitCommand commit = git.commit();
627 commit.setAuthor(commitToPick.getAuthorIdent());
628 commit.setMessage(commitToPick.getFullMessage());
629 commit.setReflogComment(REFLOG_PREFIX + " "
630 + commitToPick.getShortMessage());
631 newHead = commit.call();
632 } else {
633 if (operation == Operation.BEGIN && mergeResult
634 .getMergeStatus() == MergeResult.MergeStatus.FAILED)
635 return abort(RebaseResult
636 .failed(mergeResult.getFailingPaths()));
637 return stop(commitToPick, Status.STOPPED);
638 }
639 }
640 }
641 }
642 return null;
643 }
644
645
646 private void writeMergeInfo(RevCommit commitToPick,
647 List<RevCommit> newParents) throws IOException {
648 repo.writeMergeHeads(newParents.subList(1, newParents.size()));
649 repo.writeMergeCommitMsg(commitToPick.getFullMessage());
650 }
651
652
653 private List<RevCommit> getNewParents(RevCommit commitToPick)
654 throws IOException {
655 List<RevCommit> newParents = new ArrayList<>();
656 for (int p = 0; p < commitToPick.getParentCount(); p++) {
657 String parentHash = commitToPick.getParent(p).getName();
658 if (!new File(rebaseState.getRewrittenDir(), parentHash).exists())
659 newParents.add(commitToPick.getParent(p));
660 else {
661 String newParent = RebaseState.readFile(
662 rebaseState.getRewrittenDir(), parentHash);
663 if (newParent.length() == 0)
664 newParents.add(walk.parseCommit(repo
665 .resolve(Constants.HEAD)));
666 else
667 newParents.add(walk.parseCommit(ObjectId
668 .fromString(newParent)));
669 }
670 }
671 return newParents;
672 }
673
674 private void writeCurrentCommit(RevCommit commit) throws IOException {
675 RebaseState.appendToFile(rebaseState.getFile(CURRENT_COMMIT),
676 commit.name());
677 }
678
679 private void writeRewrittenHashes() throws RevisionSyntaxException,
680 IOException, RefNotFoundException {
681 File currentCommitFile = rebaseState.getFile(CURRENT_COMMIT);
682 if (!currentCommitFile.exists())
683 return;
684
685 ObjectId headId = getHead().getObjectId();
686
687 assert headId != null;
688 String head = headId.getName();
689 String currentCommits = rebaseState.readFile(CURRENT_COMMIT);
690 for (String current : currentCommits.split("\n"))
691 RebaseState
692 .createFile(rebaseState.getRewrittenDir(), current, head);
693 FileUtils.delete(currentCommitFile);
694 }
695
696 private RebaseResult finishRebase(RevCommit finalHead,
697 boolean lastStepIsForward) throws IOException, GitAPIException {
698 String headName = rebaseState.readFile(HEAD_NAME);
699 updateHead(headName, finalHead, upstreamCommit);
700 boolean stashConflicts = autoStashApply();
701 getRepository().autoGC(monitor);
702 FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
703 if (stashConflicts)
704 return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
705 if (lastStepIsForward || finalHead == null)
706 return RebaseResult.FAST_FORWARD_RESULT;
707 return RebaseResult.OK_RESULT;
708 }
709
710 private void checkSteps(List<RebaseTodoLine> steps)
711 throws InvalidRebaseStepException, IOException {
712 if (steps.isEmpty())
713 return;
714 if (RebaseTodoLine.Action.SQUASH.equals(steps.get(0).getAction())
715 || RebaseTodoLine.Action.FIXUP.equals(steps.get(0).getAction())) {
716 if (!rebaseState.getFile(DONE).exists()
717 || rebaseState.readFile(DONE).trim().length() == 0) {
718 throw new InvalidRebaseStepException(MessageFormat.format(
719 JGitText.get().cannotSquashFixupWithoutPreviousCommit,
720 steps.get(0).getAction().name()));
721 }
722 }
723
724 }
725
726 private RevCommit doSquashFixup(boolean isSquash, RevCommit commitToPick,
727 RebaseTodoLine nextStep, File messageFixup, File messageSquash)
728 throws IOException, GitAPIException {
729
730 if (!messageSquash.exists()) {
731
732 ObjectId headId = repo.resolve(Constants.HEAD);
733 RevCommit previousCommit = walk.parseCommit(headId);
734
735 initializeSquashFixupFile(MESSAGE_SQUASH,
736 previousCommit.getFullMessage());
737 if (!isSquash)
738 initializeSquashFixupFile(MESSAGE_FIXUP,
739 previousCommit.getFullMessage());
740 }
741 String currSquashMessage = rebaseState
742 .readFile(MESSAGE_SQUASH);
743
744 int count = parseSquashFixupSequenceCount(currSquashMessage) + 1;
745
746 String content = composeSquashMessage(isSquash,
747 commitToPick, currSquashMessage, count);
748 rebaseState.createFile(MESSAGE_SQUASH, content);
749 if (messageFixup.exists())
750 rebaseState.createFile(MESSAGE_FIXUP, content);
751
752 return squashIntoPrevious(
753 !messageFixup.exists(),
754 nextStep);
755 }
756
757 private void resetSoftToParent() throws IOException,
758 GitAPIException, CheckoutConflictException {
759 Ref ref = repo.exactRef(Constants.ORIG_HEAD);
760 ObjectId orig_head = ref == null ? null : ref.getObjectId();
761 try (Git git = Git.wrap(repo)) {
762
763
764
765
766 git.reset().setMode(ResetType.SOFT)
767 .setRef("HEAD~1").call();
768 } finally {
769
770
771 repo.writeOrigHead(orig_head);
772 }
773 }
774
775 private RevCommit squashIntoPrevious(boolean sequenceContainsSquash,
776 RebaseTodoLine nextStep)
777 throws IOException, GitAPIException {
778 RevCommit retNewHead;
779 String commitMessage = rebaseState
780 .readFile(MESSAGE_SQUASH);
781
782 try (Git git = new Git(repo)) {
783 if (nextStep == null || ((nextStep.getAction() != Action.FIXUP)
784 && (nextStep.getAction() != Action.SQUASH))) {
785
786 if (sequenceContainsSquash) {
787 commitMessage = interactiveHandler
788 .modifyCommitMessage(commitMessage);
789 }
790 retNewHead = git.commit()
791 .setMessage(stripCommentLines(commitMessage))
792 .setAmend(true).setNoVerify(true).call();
793 rebaseState.getFile(MESSAGE_SQUASH).delete();
794 rebaseState.getFile(MESSAGE_FIXUP).delete();
795
796 } else {
797
798 retNewHead = git.commit().setMessage(commitMessage)
799 .setAmend(true).setNoVerify(true).call();
800 }
801 }
802 return retNewHead;
803 }
804
805 private static String stripCommentLines(String commitMessage) {
806 StringBuilder result = new StringBuilder();
807 for (String line : commitMessage.split("\n")) {
808 if (!line.trim().startsWith("#"))
809 result.append(line).append("\n");
810 }
811 if (!commitMessage.endsWith("\n")) {
812 int bufferSize = result.length();
813 if (bufferSize > 0 && result.charAt(bufferSize - 1) == '\n') {
814 result.deleteCharAt(bufferSize - 1);
815 }
816 }
817 return result.toString();
818 }
819
820 @SuppressWarnings("nls")
821 private static String composeSquashMessage(boolean isSquash,
822 RevCommit commitToPick, String currSquashMessage, int count) {
823 StringBuilder sb = new StringBuilder();
824 String ordinal = getOrdinal(count);
825 sb.setLength(0);
826 sb.append("# This is a combination of ").append(count)
827 .append(" commits.\n");
828
829 sb.append(currSquashMessage.substring(currSquashMessage.indexOf("\n") + 1));
830 sb.append("\n");
831 if (isSquash) {
832 sb.append("# This is the ").append(count).append(ordinal)
833 .append(" commit message:\n");
834 sb.append(commitToPick.getFullMessage());
835 } else {
836 sb.append("# The ").append(count).append(ordinal)
837 .append(" commit message will be skipped:\n# ");
838 sb.append(commitToPick.getFullMessage().replaceAll("([\n\r])",
839 "$1# "));
840 }
841 return sb.toString();
842 }
843
844 private static String getOrdinal(int count) {
845 switch (count % 10) {
846 case 1:
847 return "st";
848 case 2:
849 return "nd";
850 case 3:
851 return "rd";
852 default:
853 return "th";
854 }
855 }
856
857
858
859
860
861
862
863
864 static int parseSquashFixupSequenceCount(String currSquashMessage) {
865 String regex = "This is a combination of (.*) commits";
866 String firstLine = currSquashMessage.substring(0,
867 currSquashMessage.indexOf("\n"));
868 Pattern pattern = Pattern.compile(regex);
869 Matcher matcher = pattern.matcher(firstLine);
870 if (!matcher.find())
871 throw new IllegalArgumentException();
872 return Integer.parseInt(matcher.group(1));
873 }
874
875 private void initializeSquashFixupFile(String messageFile,
876 String fullMessage) throws IOException {
877 rebaseState
878 .createFile(
879 messageFile,
880 "# This is a combination of 1 commits.\n# The first commit's message is:\n" + fullMessage);
881 }
882
883 private String getOurCommitName() {
884
885
886 String ourCommitName = "Upstream, based on "
887 + Repository.shortenRefName(upstreamCommitName);
888 return ourCommitName;
889 }
890
891 private void updateHead(String headName, RevCommit aNewHead, RevCommit onto)
892 throws IOException {
893
894
895 if (headName.startsWith(Constants.R_REFS)) {
896 RefUpdate rup = repo.updateRef(headName);
897 rup.setNewObjectId(aNewHead);
898 rup.setRefLogMessage("rebase finished: " + headName + " onto "
899 + onto.getName(), false);
900 Result res = rup.forceUpdate();
901 switch (res) {
902 case FAST_FORWARD:
903 case FORCED:
904 case NO_CHANGE:
905 break;
906 default:
907 throw new JGitInternalException(
908 JGitText.get().updatingHeadFailed);
909 }
910 rup = repo.updateRef(Constants.HEAD);
911 rup.setRefLogMessage("rebase finished: returning to " + headName,
912 false);
913 res = rup.link(headName);
914 switch (res) {
915 case FAST_FORWARD:
916 case FORCED:
917 case NO_CHANGE:
918 break;
919 default:
920 throw new JGitInternalException(
921 JGitText.get().updatingHeadFailed);
922 }
923 }
924 }
925
926 private RevCommit checkoutCurrentHead() throws IOException, NoHeadException {
927 ObjectId headTree = repo.resolve(Constants.HEAD + "^{tree}");
928 if (headTree == null)
929 throw new NoHeadException(
930 JGitText.get().cannotRebaseWithoutCurrentHead);
931 DirCache dc = repo.lockDirCache();
932 try {
933 DirCacheCheckout dco = new DirCacheCheckout(repo, dc, headTree);
934 dco.setFailOnConflict(false);
935 dco.setProgressMonitor(monitor);
936 boolean needsDeleteFiles = dco.checkout();
937 if (needsDeleteFiles) {
938 List<String> fileList = dco.getToBeDeleted();
939 for (String filePath : fileList) {
940 File fileToDelete = new File(repo.getWorkTree(), filePath);
941 if (repo.getFS().exists(fileToDelete))
942 FileUtils.delete(fileToDelete, FileUtils.RECURSIVE
943 | FileUtils.RETRY);
944 }
945 }
946 } finally {
947 dc.unlock();
948 }
949 try (RevWalk rw = new RevWalk(repo)) {
950 RevCommit commit = rw.parseCommit(repo.resolve(Constants.HEAD));
951 return commit;
952 }
953 }
954
955
956
957
958
959
960 private RevCommit continueRebase() throws GitAPIException, IOException {
961
962 DirCache dc = repo.readDirCache();
963 boolean hasUnmergedPaths = dc.hasUnmergedPaths();
964 if (hasUnmergedPaths)
965 throw new UnmergedPathsException();
966
967
968 boolean needsCommit;
969 try (TreeWalk treeWalk = new TreeWalk(repo)) {
970 treeWalk.reset();
971 treeWalk.setRecursive(true);
972 treeWalk.addTree(new DirCacheIterator(dc));
973 ObjectId id = repo.resolve(Constants.HEAD + "^{tree}");
974 if (id == null)
975 throw new NoHeadException(
976 JGitText.get().cannotRebaseWithoutCurrentHead);
977
978 treeWalk.addTree(id);
979
980 treeWalk.setFilter(TreeFilter.ANY_DIFF);
981
982 needsCommit = treeWalk.next();
983 }
984 if (needsCommit) {
985 try (Git git = new Git(repo)) {
986 CommitCommand commit = git.commit();
987 commit.setMessage(rebaseState.readFile(MESSAGE));
988 commit.setAuthor(parseAuthor());
989 return commit.call();
990 }
991 }
992 return null;
993 }
994
995 private PersonIdent parseAuthor() throws IOException {
996 File authorScriptFile = rebaseState.getFile(AUTHOR_SCRIPT);
997 byte[] raw;
998 try {
999 raw = IO.readFully(authorScriptFile);
1000 } catch (FileNotFoundException notFound) {
1001 if (authorScriptFile.exists()) {
1002 throw notFound;
1003 }
1004 return null;
1005 }
1006 return parseAuthor(raw);
1007 }
1008
1009 private RebaseResult stop(RevCommit commitToPick, RebaseResult.Status status)
1010 throws IOException {
1011 PersonIdent author = commitToPick.getAuthorIdent();
1012 String authorScript = toAuthorScript(author);
1013 rebaseState.createFile(AUTHOR_SCRIPT, authorScript);
1014 rebaseState.createFile(MESSAGE, commitToPick.getFullMessage());
1015 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1016 try (DiffFormatter df = new DiffFormatter(bos)) {
1017 df.setRepository(repo);
1018 df.format(commitToPick.getParent(0), commitToPick);
1019 }
1020 rebaseState.createFile(PATCH, new String(bos.toByteArray(),
1021 Constants.CHARACTER_ENCODING));
1022 rebaseState.createFile(STOPPED_SHA,
1023 repo.newObjectReader()
1024 .abbreviate(
1025 commitToPick).name());
1026
1027
1028 repo.writeCherryPickHead(null);
1029 return RebaseResult.result(status, commitToPick);
1030 }
1031
1032 String toAuthorScript(PersonIdent author) {
1033 StringBuilder sb = new StringBuilder(100);
1034 sb.append(GIT_AUTHOR_NAME);
1035 sb.append("='");
1036 sb.append(author.getName());
1037 sb.append("'\n");
1038 sb.append(GIT_AUTHOR_EMAIL);
1039 sb.append("='");
1040 sb.append(author.getEmailAddress());
1041 sb.append("'\n");
1042
1043
1044 sb.append(GIT_AUTHOR_DATE);
1045 sb.append("='");
1046 sb.append("@");
1047 String externalString = author.toExternalString();
1048 sb
1049 .append(externalString.substring(externalString
1050 .lastIndexOf('>') + 2));
1051 sb.append("'\n");
1052 return sb.toString();
1053 }
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063 private void popSteps(int numSteps) throws IOException {
1064 if (numSteps == 0)
1065 return;
1066 List<RebaseTodoLine> todoLines = new LinkedList<>();
1067 List<RebaseTodoLine> poppedLines = new LinkedList<>();
1068
1069 for (RebaseTodoLine line : repo.readRebaseTodo(
1070 rebaseState.getPath(GIT_REBASE_TODO), true)) {
1071 if (poppedLines.size() >= numSteps
1072 || RebaseTodoLine.Action.COMMENT.equals(line.getAction()))
1073 todoLines.add(line);
1074 else
1075 poppedLines.add(line);
1076 }
1077
1078 repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
1079 todoLines, false);
1080 if (poppedLines.size() > 0) {
1081 repo.writeRebaseTodoFile(rebaseState.getPath(DONE), poppedLines,
1082 true);
1083 }
1084 }
1085
1086 private RebaseResult initFilesAndRewind() throws IOException,
1087 GitAPIException {
1088
1089
1090
1091 Ref head = getHead();
1092
1093 ObjectId headId = head.getObjectId();
1094 if (headId == null) {
1095 throw new RefNotFoundException(MessageFormat.format(
1096 JGitText.get().refNotResolved, Constants.HEAD));
1097 }
1098 String headName = getHeadName(head);
1099 RevCommit headCommit = walk.lookupCommit(headId);
1100 RevCommit upstream = walk.lookupCommit(upstreamCommit.getId());
1101
1102 if (!isInteractive() && walk.isMergedInto(upstream, headCommit))
1103 return RebaseResult.UP_TO_DATE_RESULT;
1104 else if (!isInteractive() && walk.isMergedInto(headCommit, upstream)) {
1105
1106 monitor.beginTask(MessageFormat.format(
1107 JGitText.get().resettingHead,
1108 upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
1109 checkoutCommit(headName, upstreamCommit);
1110 monitor.endTask();
1111
1112 updateHead(headName, upstreamCommit, upstream);
1113 return RebaseResult.FAST_FORWARD_RESULT;
1114 }
1115
1116 monitor.beginTask(JGitText.get().obtainingCommitsForCherryPick,
1117 ProgressMonitor.UNKNOWN);
1118
1119
1120 FileUtils.mkdir(rebaseState.getDir(), true);
1121
1122 repo.writeOrigHead(headId);
1123 rebaseState.createFile(REBASE_HEAD, headId.name());
1124 rebaseState.createFile(HEAD_NAME, headName);
1125 rebaseState.createFile(ONTO, upstreamCommit.name());
1126 rebaseState.createFile(ONTO_NAME, upstreamCommitName);
1127 if (isInteractive()) {
1128 rebaseState.createFile(INTERACTIVE, "");
1129 }
1130 rebaseState.createFile(QUIET, "");
1131
1132 ArrayList<RebaseTodoLine> toDoSteps = new ArrayList<>();
1133 toDoSteps.add(new RebaseTodoLine("# Created by EGit: rebasing " + headId.name()
1134 + " onto " + upstreamCommit.name()));
1135
1136 List<RevCommit> cherryPickList = calculatePickList(headCommit);
1137 ObjectReader reader = walk.getObjectReader();
1138 for (RevCommit commit : cherryPickList)
1139 toDoSteps.add(new RebaseTodoLine(Action.PICK, reader
1140 .abbreviate(commit), commit.getShortMessage()));
1141 repo.writeRebaseTodoFile(rebaseState.getPath(GIT_REBASE_TODO),
1142 toDoSteps, false);
1143
1144 monitor.endTask();
1145
1146
1147 monitor.beginTask(MessageFormat.format(JGitText.get().rewinding,
1148 upstreamCommit.getShortMessage()), ProgressMonitor.UNKNOWN);
1149 boolean checkoutOk = false;
1150 try {
1151 checkoutOk = checkoutCommit(headName, upstreamCommit);
1152 } finally {
1153 if (!checkoutOk)
1154 FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
1155 }
1156 monitor.endTask();
1157
1158 return null;
1159 }
1160
1161 private List<RevCommit> calculatePickList(RevCommit headCommit)
1162 throws GitAPIException, NoHeadException, IOException {
1163 Iterable<RevCommit> commitsToUse;
1164 try (Git git = new Git(repo)) {
1165 LogCommand cmd = git.log().addRange(upstreamCommit, headCommit);
1166 commitsToUse = cmd.call();
1167 }
1168 List<RevCommit> cherryPickList = new ArrayList<>();
1169 for (RevCommit commit : commitsToUse) {
1170 if (preserveMerges || commit.getParentCount() == 1)
1171 cherryPickList.add(commit);
1172 }
1173 Collections.reverse(cherryPickList);
1174
1175 if (preserveMerges) {
1176
1177
1178 File rewrittenDir = rebaseState.getRewrittenDir();
1179 FileUtils.mkdir(rewrittenDir, false);
1180 walk.reset();
1181 walk.setRevFilter(RevFilter.MERGE_BASE);
1182 walk.markStart(upstreamCommit);
1183 walk.markStart(headCommit);
1184 RevCommit base;
1185 while ((base = walk.next()) != null)
1186 RebaseState.createFile(rewrittenDir, base.getName(),
1187 upstreamCommit.getName());
1188
1189 Iterator<RevCommit> iterator = cherryPickList.iterator();
1190 pickLoop: while(iterator.hasNext()){
1191 RevCommit commit = iterator.next();
1192 for (int i = 0; i < commit.getParentCount(); i++) {
1193 boolean parentRewritten = new File(rewrittenDir, commit
1194 .getParent(i).getName()).exists();
1195 if (parentRewritten) {
1196 new File(rewrittenDir, commit.getName()).createNewFile();
1197 continue pickLoop;
1198 }
1199 }
1200
1201 iterator.remove();
1202 }
1203 }
1204 return cherryPickList;
1205 }
1206
1207 private static String getHeadName(Ref head) {
1208 String headName;
1209 if (head.isSymbolic()) {
1210 headName = head.getTarget().getName();
1211 } else {
1212 ObjectId headId = head.getObjectId();
1213
1214 assert headId != null;
1215 headName = headId.getName();
1216 }
1217 return headName;
1218 }
1219
1220 private Ref getHead() throws IOException, RefNotFoundException {
1221 Ref head = repo.exactRef(Constants.HEAD);
1222 if (head == null || head.getObjectId() == null)
1223 throw new RefNotFoundException(MessageFormat.format(
1224 JGitText.get().refNotResolved, Constants.HEAD));
1225 return head;
1226 }
1227
1228 private boolean isInteractive() {
1229 return interactiveHandler != null;
1230 }
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242 public RevCommit tryFastForward(RevCommit newCommit) throws IOException,
1243 GitAPIException {
1244 Ref head = getHead();
1245
1246 ObjectId headId = head.getObjectId();
1247 if (headId == null)
1248 throw new RefNotFoundException(MessageFormat.format(
1249 JGitText.get().refNotResolved, Constants.HEAD));
1250 RevCommit headCommit = walk.lookupCommit(headId);
1251 if (walk.isMergedInto(newCommit, headCommit))
1252 return newCommit;
1253
1254 String headName = getHeadName(head);
1255 return tryFastForward(headName, headCommit, newCommit);
1256 }
1257
1258 private RevCommit tryFastForward(String headName, RevCommit oldCommit,
1259 RevCommit newCommit) throws IOException, GitAPIException {
1260 boolean tryRebase = false;
1261 for (RevCommit parentCommit : newCommit.getParents())
1262 if (parentCommit.equals(oldCommit))
1263 tryRebase = true;
1264 if (!tryRebase)
1265 return null;
1266
1267 CheckoutCommand co = new CheckoutCommand(repo);
1268 try {
1269 co.setProgressMonitor(monitor);
1270 co.setName(newCommit.name()).call();
1271 if (headName.startsWith(Constants.R_HEADS)) {
1272 RefUpdate rup = repo.updateRef(headName);
1273 rup.setExpectedOldObjectId(oldCommit);
1274 rup.setNewObjectId(newCommit);
1275 rup.setRefLogMessage("Fast-forward from " + oldCommit.name()
1276 + " to " + newCommit.name(), false);
1277 Result res = rup.update(walk);
1278 switch (res) {
1279 case FAST_FORWARD:
1280 case NO_CHANGE:
1281 case FORCED:
1282 break;
1283 default:
1284 throw new IOException("Could not fast-forward");
1285 }
1286 }
1287 return newCommit;
1288 } catch (RefAlreadyExistsException e) {
1289 throw new JGitInternalException(e.getMessage(), e);
1290 } catch (RefNotFoundException e) {
1291 throw new JGitInternalException(e.getMessage(), e);
1292 } catch (InvalidRefNameException e) {
1293 throw new JGitInternalException(e.getMessage(), e);
1294 } catch (CheckoutConflictException e) {
1295 throw new JGitInternalException(e.getMessage(), e);
1296 }
1297 }
1298
1299 private void checkParameters() throws WrongRepositoryStateException {
1300 if (this.operation == Operation.PROCESS_STEPS) {
1301 if (rebaseState.getFile(DONE).exists())
1302 throw new WrongRepositoryStateException(MessageFormat.format(
1303 JGitText.get().wrongRepositoryState, repo
1304 .getRepositoryState().name()));
1305 }
1306 if (this.operation != Operation.BEGIN) {
1307
1308 switch (repo.getRepositoryState()) {
1309 case REBASING_INTERACTIVE:
1310 case REBASING:
1311 case REBASING_REBASING:
1312 case REBASING_MERGE:
1313 break;
1314 default:
1315 throw new WrongRepositoryStateException(MessageFormat.format(
1316 JGitText.get().wrongRepositoryState, repo
1317 .getRepositoryState().name()));
1318 }
1319 } else
1320 switch (repo.getRepositoryState()) {
1321 case SAFE:
1322 if (this.upstreamCommit == null)
1323 throw new JGitInternalException(MessageFormat
1324 .format(JGitText.get().missingRequiredParameter,
1325 "upstream"));
1326 return;
1327 default:
1328 throw new WrongRepositoryStateException(MessageFormat.format(
1329 JGitText.get().wrongRepositoryState, repo
1330 .getRepositoryState().name()));
1331
1332 }
1333 }
1334
1335 private RebaseResult abort(RebaseResult result) throws IOException,
1336 GitAPIException {
1337 try {
1338 ObjectId origHead = repo.readOrigHead();
1339 String commitId = origHead != null ? origHead.name() : null;
1340 monitor.beginTask(MessageFormat.format(
1341 JGitText.get().abortingRebase, commitId),
1342 ProgressMonitor.UNKNOWN);
1343
1344 DirCacheCheckout dco;
1345 if (commitId == null)
1346 throw new JGitInternalException(
1347 JGitText.get().abortingRebaseFailedNoOrigHead);
1348 ObjectId id = repo.resolve(commitId);
1349 RevCommit commit = walk.parseCommit(id);
1350 if (result.getStatus().equals(Status.FAILED)) {
1351 RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
1352 dco = new DirCacheCheckout(repo, head.getTree(),
1353 repo.lockDirCache(), commit.getTree());
1354 } else {
1355 dco = new DirCacheCheckout(repo, repo.lockDirCache(),
1356 commit.getTree());
1357 }
1358 dco.setFailOnConflict(false);
1359 dco.checkout();
1360 walk.close();
1361 } finally {
1362 monitor.endTask();
1363 }
1364 try {
1365 String headName = rebaseState.readFile(HEAD_NAME);
1366 monitor.beginTask(MessageFormat.format(
1367 JGitText.get().resettingHead, headName),
1368 ProgressMonitor.UNKNOWN);
1369
1370 Result res = null;
1371 RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false);
1372 refUpdate.setRefLogMessage("rebase: aborting", false);
1373 if (headName.startsWith(Constants.R_REFS)) {
1374
1375 res = refUpdate.link(headName);
1376 } else {
1377 refUpdate.setNewObjectId(repo.readOrigHead());
1378 res = refUpdate.forceUpdate();
1379
1380 }
1381 switch (res) {
1382 case FAST_FORWARD:
1383 case FORCED:
1384 case NO_CHANGE:
1385 break;
1386 default:
1387 throw new JGitInternalException(
1388 JGitText.get().abortingRebaseFailed);
1389 }
1390 boolean stashConflicts = autoStashApply();
1391
1392 FileUtils.delete(rebaseState.getDir(), FileUtils.RECURSIVE);
1393 repo.writeCherryPickHead(null);
1394 repo.writeMergeHeads(null);
1395 if (stashConflicts)
1396 return RebaseResult.STASH_APPLY_CONFLICTS_RESULT;
1397 return result;
1398
1399 } finally {
1400 monitor.endTask();
1401 }
1402 }
1403
1404 private boolean checkoutCommit(String headName, RevCommit commit)
1405 throws IOException,
1406 CheckoutConflictException {
1407 try {
1408 RevCommit head = walk.parseCommit(repo.resolve(Constants.HEAD));
1409 DirCacheCheckout dco = new DirCacheCheckout(repo, head.getTree(),
1410 repo.lockDirCache(), commit.getTree());
1411 dco.setFailOnConflict(true);
1412 dco.setProgressMonitor(monitor);
1413 try {
1414 dco.checkout();
1415 } catch (org.eclipse.jgit.errors.CheckoutConflictException cce) {
1416 throw new CheckoutConflictException(dco.getConflicts(), cce);
1417 }
1418
1419 RefUpdate refUpdate = repo.updateRef(Constants.HEAD, true);
1420 refUpdate.setExpectedOldObjectId(head);
1421 refUpdate.setNewObjectId(commit);
1422 refUpdate.setRefLogMessage(
1423 "checkout: moving from "
1424 + Repository.shortenRefName(headName)
1425 + " to " + commit.getName(), false);
1426 Result res = refUpdate.forceUpdate();
1427 switch (res) {
1428 case FAST_FORWARD:
1429 case NO_CHANGE:
1430 case FORCED:
1431 break;
1432 default:
1433 throw new IOException(
1434 JGitText.get().couldNotRewindToUpstreamCommit);
1435 }
1436 } finally {
1437 walk.close();
1438 monitor.endTask();
1439 }
1440 return true;
1441 }
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451 public RebaseCommand setUpstream(RevCommit upstream) {
1452 this.upstreamCommit = upstream;
1453 this.upstreamCommitName = upstream.name();
1454 return this;
1455 }
1456
1457
1458
1459
1460
1461
1462
1463
1464 public RebaseCommand setUpstream(AnyObjectId upstream) {
1465 try {
1466 this.upstreamCommit = walk.parseCommit(upstream);
1467 this.upstreamCommitName = upstream.name();
1468 } catch (IOException e) {
1469 throw new JGitInternalException(MessageFormat.format(
1470 JGitText.get().couldNotReadObjectWhileParsingCommit,
1471 upstream.name()), e);
1472 }
1473 return this;
1474 }
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484 public RebaseCommand setUpstream(String upstream)
1485 throws RefNotFoundException {
1486 try {
1487 ObjectId upstreamId = repo.resolve(upstream);
1488 if (upstreamId == null)
1489 throw new RefNotFoundException(MessageFormat.format(JGitText
1490 .get().refNotResolved, upstream));
1491 upstreamCommit = walk.parseCommit(repo.resolve(upstream));
1492 upstreamCommitName = upstream;
1493 return this;
1494 } catch (IOException ioe) {
1495 throw new JGitInternalException(ioe.getMessage(), ioe);
1496 }
1497 }
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507 public RebaseCommand setUpstreamName(String upstreamName) {
1508 if (upstreamCommit == null) {
1509 throw new IllegalStateException(
1510 "setUpstreamName must be called after setUpstream.");
1511 }
1512 this.upstreamCommitName = upstreamName;
1513 return this;
1514 }
1515
1516
1517
1518
1519
1520
1521
1522
1523 public RebaseCommand setOperation(Operation operation) {
1524 this.operation = operation;
1525 return this;
1526 }
1527
1528
1529
1530
1531
1532
1533
1534
1535 public RebaseCommand setProgressMonitor(ProgressMonitor monitor) {
1536 if (monitor == null) {
1537 monitor = NullProgressMonitor.INSTANCE;
1538 }
1539 this.monitor = monitor;
1540 return this;
1541 }
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558 public RebaseCommand runInteractively(InteractiveHandler handler) {
1559 return runInteractively(handler, false);
1560 }
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579 public RebaseCommand runInteractively(InteractiveHandler handler,
1580 final boolean stopAfterRebaseInteractiveInitialization) {
1581 this.stopAfterInitialization = stopAfterRebaseInteractiveInitialization;
1582 this.interactiveHandler = handler;
1583 return this;
1584 }
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594 public RebaseCommand setStrategy(MergeStrategy strategy) {
1595 this.strategy = strategy;
1596 return this;
1597 }
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608 public RebaseCommand setPreserveMerges(boolean preserve) {
1609 this.preserveMerges = preserve;
1610 return this;
1611 }
1612
1613
1614
1615
1616 public interface InteractiveHandler {
1617
1618
1619
1620
1621
1622
1623 void prepareSteps(List<RebaseTodoLine> steps);
1624
1625
1626
1627
1628
1629
1630
1631 String modifyCommitMessage(String commit);
1632 }
1633
1634
1635 PersonIdent parseAuthor(byte[] raw) {
1636 if (raw.length == 0)
1637 return null;
1638
1639 Map<String, String> keyValueMap = new HashMap<>();
1640 for (int p = 0; p < raw.length;) {
1641 int end = RawParseUtils.nextLF(raw, p);
1642 if (end == p)
1643 break;
1644 int equalsIndex = RawParseUtils.next(raw, p, '=');
1645 if (equalsIndex == end)
1646 break;
1647 String key = RawParseUtils.decode(raw, p, equalsIndex - 1);
1648 String value = RawParseUtils.decode(raw, equalsIndex + 1, end - 2);
1649 p = end;
1650 keyValueMap.put(key, value);
1651 }
1652
1653 String name = keyValueMap.get(GIT_AUTHOR_NAME);
1654 String email = keyValueMap.get(GIT_AUTHOR_EMAIL);
1655 String time = keyValueMap.get(GIT_AUTHOR_DATE);
1656
1657
1658 int timeStart = 0;
1659 if (time.startsWith("@"))
1660 timeStart = 1;
1661 else
1662 timeStart = 0;
1663 long when = Long
1664 .parseLong(time.substring(timeStart, time.indexOf(' '))) * 1000;
1665 String tzOffsetString = time.substring(time.indexOf(' ') + 1);
1666 int multiplier = -1;
1667 if (tzOffsetString.charAt(0) == '+')
1668 multiplier = 1;
1669 int hours = Integer.parseInt(tzOffsetString.substring(1, 3));
1670 int minutes = Integer.parseInt(tzOffsetString.substring(3, 5));
1671
1672
1673 int tz = (hours * 60 + minutes) * multiplier;
1674 if (name != null && email != null)
1675 return new PersonIdent(name, email, when, tz);
1676 return null;
1677 }
1678
1679 private static class RebaseState {
1680
1681 private final File repoDirectory;
1682 private File dir;
1683
1684 public RebaseState(File repoDirectory) {
1685 this.repoDirectory = repoDirectory;
1686 }
1687
1688 public File getDir() {
1689 if (dir == null) {
1690 File rebaseApply = new File(repoDirectory, REBASE_APPLY);
1691 if (rebaseApply.exists()) {
1692 dir = rebaseApply;
1693 } else {
1694 File rebaseMerge = new File(repoDirectory, REBASE_MERGE);
1695 dir = rebaseMerge;
1696 }
1697 }
1698 return dir;
1699 }
1700
1701
1702
1703
1704
1705 public File getRewrittenDir() {
1706 return new File(getDir(), REWRITTEN);
1707 }
1708
1709 public String readFile(String name) throws IOException {
1710 return readFile(getDir(), name);
1711 }
1712
1713 public void createFile(String name, String content) throws IOException {
1714 createFile(getDir(), name, content);
1715 }
1716
1717 public File getFile(String name) {
1718 return new File(getDir(), name);
1719 }
1720
1721 public String getPath(String name) {
1722 return (getDir().getName() + "/" + name);
1723 }
1724
1725 private static String readFile(File directory, String fileName)
1726 throws IOException {
1727 byte[] content = IO.readFully(new File(directory, fileName));
1728
1729 int end = RawParseUtils.prevLF(content, content.length);
1730 return RawParseUtils.decode(content, 0, end + 1);
1731 }
1732
1733 private static void createFile(File parentDir, String name,
1734 String content)
1735 throws IOException {
1736 File file = new File(parentDir, name);
1737 try (FileOutputStream fos = new FileOutputStream(file)) {
1738 fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
1739 fos.write('\n');
1740 }
1741 }
1742
1743 private static void appendToFile(File file, String content)
1744 throws IOException {
1745 try (FileOutputStream fos = new FileOutputStream(file, true)) {
1746 fos.write(content.getBytes(Constants.CHARACTER_ENCODING));
1747 fos.write('\n');
1748 }
1749 }
1750 }
1751 }