Squash multiple commits into one new commit - RedHatInsights/red-hat-ansible-automation-platform-documentation GitHub Wiki
Use git rebase -i
to squash several commits into one new commit.
-
Navigate to the local branch that contains the commits you want to squash.
$ git checkout <local_branch>
-
Run
git log
to view the commit log. You can$ git log [--oneline] [-n <num_commits_to_view>] [<root_branch>..]
-
The
--oneline
option displays one commit per line. -
The
-n <num_commits_to_view>
option displays the 20 most recent commits. -
Use the
<root_branch>..
option to display only the commits you made since you created the branch:$ git log [--oneline] main..
-
-
Identify the commits you want to squash.
-
Use the
git rebase -i
command to squash the commits. Specify which commits to squash using one of the following options:-
To squash the <n> most recent commits:
$ git rebase -i HEAD~<n>
-
To preserve <commit_id> and squash all the commits newer than <commit_id>:
$ git rebase -i <commit_id>
-
The rebase process has three stages.
-
The
/red-hat-ansible-automation-platform-documentation/.git/rebase-merge/git-rebase-todo
file opens. It lists the commits that your rebase command specified, starting with the oldest commit and finishing with the newest.-
Make sure that you want to squash these commits. If you made a mistake in the rebase command, cancel the rebase by quitting the file without editing it.
-
Change
pick
toreword
in the first line (representing the oldest commit) -
Change the rest of the instances of
pick
tosquash
. -
Save and quit the file.
-
-
The
/red-hat-ansible-automation-platform-documentation/.git/COMMIT_EDITMSG
file opens. It contains the message for the commit that you labelled withreword
in the previous step.-
Change the commit message to the message you would like to appear in the final squashed commit.
-
Save and quit the file.
-
-
The
/red-hat-ansible-automation-platform-documentation/.git/COMMIT_EDITMSG
file opens. This file contains the reworded message for the oldest commit, and the unchanged messages for the newer commits in the previous step.-
The first message in the list is for the final squashed commit
-
Add a
#
character at the beginning of the lines containing the other messages. -
Save and quit the file.
-