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

How to Revert Pushed and Public Commit Records in Git?

2024年7月4日 09:38

When handling already pushed and public commits, several methods exist for reverting them, but the safest and most common approach is to use the git revert command. This command preserves the integrity of the project history by adding a new commit that effectively reverses the changes of the previous commit.

Steps

  1. Identify the commit hash to revert First, identify the hash of the commit to revert by examining the commit history with git log.

    bash
    git log
  2. Use git revert After identifying the commit hash to revert, use the following command:

    bash
    git revert <commit-hash>

    Here, <commit-hash> is the hash of the commit you want to revert.

  3. Resolve potential conflicts If conflicts arise during the revert process, Git will prompt you to resolve them. Manually edit the files to resolve these conflicts and use the git add command to mark the resolved files.

  4. Complete the revert operation After resolving conflicts, complete the revert operation. Typically, Git automatically opens a new commit message editor for this revert. Save and close the editor to finalize the revert commit.

  5. Push changes to the remote repository Push the changes to the remote repository using:

    bash
    git push

Practical Example

Suppose we mistakenly committed a feature to the project and later discovered it introduced serious issues, requiring a quick revert. The commit hash is abc1234.

Steps:

bash
git revert abc1234 # Resolve any potential conflicts git push

This way, the original erroneous commit remains in the history, but we effectively undo its impact by adding a new "revert" commit.

Important Notes

  • Use git revert instead of git reset, as reset alters the public history and may confuse other collaborators.
  • Ensure all changes are tested locally before pushing to avoid introducing new issues.

The advantage of this method is that it preserves the integrity of the project history, enabling the team to more easily track what occurred, why the revert was needed, and how the revert operation was executed.

标签:Git