4

Any suggestions on how to use RebaseCommand, MergeCommand or any other command in JGit to squash commits? I cannot find many examples and the documentation is not very helpful.

A simple example

I want to squash the following tree:

A-----B------C------D------E------F------G------H

Into this one:

A----Z-----H

Where Z is the squashed commit of B, C, D, E, F, and G.

Any suggestions and useful resources are appreciated.

centic
  • 15,565
  • 9
  • 68
  • 125
modulitos
  • 14,737
  • 16
  • 67
  • 110

1 Answers1

7

In command-line Git, this would be done using git rebase -i ... and then selecting "fixup" for commits C, D, E, F and G. With fixup, Z would have the same commit message as B.

In JGit, this can be done using RebaseCommand:

InteractiveHandler handler = new InteractiveHandler() {
    public void prepareSteps(List<RebaseTodoLine> steps) {
        // loop through steps and use setAction to change action
    }

    public String modifyCommitMessage(String oldMessage) {
        return oldMessage;
    }
};

Repository repo = FileRepositoryBuilder.create(gitDir);
Git git = Git.wrap(repo);
git.rebase().setUpstream(commitA).runInteractively(handler).call();
robinst
  • 30,027
  • 10
  • 102
  • 108
  • Thanks. Although I cannot find many examples using JGit via Google or SO, but I'm finding that Eclipse bug/patch reports are another good source of information: https://git.eclipse.org/r/#/c/7779/6/org.eclipse.jgit.test/tst/org/eclipse/jgit/api/RebaseCommandTest.java – modulitos Apr 09 '14 at 06:53
  • Here is another post about how to squash commits that do not include the head commit: http://stackoverflow.com/questions/26029698/git-squashing-consecutive-commits-that-are-not-the-most-recent-commits-and-do – modulitos Oct 23 '14 at 04:44
  • Regarding missing samples: I try to collect some useful snippets in my jgit-cookbook at https://github.com/centic9/jgit-cookbook/ – centic Oct 20 '16 at 04:37