Lucas Lucas - 1 month ago 19
Git Question

JGit: How to squash commits

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.

Answer

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();