乐闻世界logo
搜索文章和话题

How do you squash multiple Git commits into one?

1个答案

1

When developing new features or fixing issues in Git, you may create multiple commits. However, before merging into the main branch, to maintain a clean project history, you may need to squash these commits into one. This process is commonly known as Squashing commits. A commonly used tool in Git is git rebase. I will explain this process with a specific example:

Suppose you are working on a new feature and have made three commits on a branch named feature-branch. The details of these three commits are as follows:

  1. Add the framework for the new feature
  2. Implement the core part of the new feature
  3. Fix some bugs in the implementation

To squash these three commits into one before code review or merging into the main branch, follow these steps:

  1. Switch to your feature branch
bash
git checkout feature-branch
  1. Use git rebase for interactive history rewriting
bash
git rebase -i HEAD~3

This command opens a text editor listing the last three commits.

  1. In the text editor, you will see something like the following:
shell
pick e3a1b35 Add the framework for the new feature squash 7ac9a67 Implement the core part of the new feature squash 4ed2a9d Fix some bugs in the implementation

To squash these commits into one, change all pick commands except the first to squash or s. This tells Git to merge these commits into the first one.

  1. Save and close the editor

Git will start squashing the commits and may open a new editor window for writing a new commit message. Here, you can write a concise message describing the entire feature.

  1. Complete the history rewriting

After this step, feature-branch will contain only one new commit with all changes from the previous three commits.

  1. Push the changes to the remote repository

If you have already pushed these commits to the remote repository, since the history has been rewritten, you need to force push:

bash
git push origin feature-branch --force

By doing this, you can effectively squash multiple commits into one, maintaining a clear and concise project history. This is very helpful for code reviews and long-term maintenance.

2024年8月15日 02:13 回复

你的答案