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

How to squash commits in git after they have been pushed?

1个答案

1

In Git, compressing commit history is typically achieved using the rebase command, especially after commits have been pushed to the remote repository, where operations require extra caution to avoid disrupting other collaborators' work. Below, I will outline the steps to safely compress commits after pushing.

Step 1: Ensure Your Local Repository is Up-to-Date

Before compressing commits, ensure your local repository is synchronized with the remote repository. This can be done using git fetch and git pull.

bash
git fetch origin git pull origin main

Replace main with your target branch name.

Step 2: Use git rebase for Interactive Compression

Using the interactive mode of git rebase, you can choose which commits to compress. Here, we'll compress the last four commits as an example:

bash
git rebase -i HEAD~4

This will open an editor listing the last four commits, providing options such as pick, reword, edit, squash, and fixup. To compress commits, change pick to squash or fixup:

  • squash: Compress the commit and request a merged commit message.
  • fixup: Compress the commit and discard the commit's log message.

For example:

shell
pick e3a1b35 Initial commit pick 7ac9a67 Added new feature squash 1d2a3f4 Improved feature squash 76b9e7f Fixed bug in feature

After saving and closing the editor, Git will begin the compression process. If squash is used, it will prompt you to edit the new commit message.

Step 3: Force-Push Changes to the Remote Repository

After compressing commits, the local history no longer matches the remote repository's history. You need to use git push --force or git push --force-with-lease to update the remote repository. --force-with-lease is a safer option as it checks for new commits on the remote branch before pushing.

bash
git push --force-with-lease origin main

Important Considerations

  • Communication: Before compressing pushed commits and force-pushing to the remote repository, communicate with team members to inform them of your actions, as this may affect their work.
  • Backup: Before performing this operation, it's advisable to back up your branch in case of errors that require recovery.
  • Use Case: It's generally recommended to compress commits and force-push only in personal projects or when all collaborators are aware and agree to the history changes.

By following these steps, you can effectively compress Git commits and ensure the continuity and consistency of team work.

2024年6月29日 12:07 回复

你的答案