Eslam HelmyEslam Helmy
3 min readEslam

Mastering Git: Undoing and Reapplying Commits


Mastering Git: Undoing and Reapplying Commits

We’ve all encountered a situation where a commit goes wrong on a shared repository. In those moments, you need to undo the commit quickly to address the issue. Once undone, you need to focus on applying the necessary fixes and recommitting the changes again. This guide will walk you through:

  • Undoing a commit immediately 🔙
  • Reapplying fixes and recommitting 🔄

Let’s dive into the first part:

Undoing a Commit Immediately 🔙

For shared branches, git revert is the preferred method because it:

  • Preserves your commit history 📜
  • Creates a new commit that undoes the changes ➕
  • Maintains clarity in the commit log 🔍

How to Use **git revert**:

  1. Update Your Branch: Make sure your branch is up-to-date with the latest changes from the remote repository
  2. Identify the Commit to Revert: Use git log to view the commit history and find the hash of the commit you want to undo
  3. Revert the Commit: Run the following command to revert the changes made by the specified commit:
git revert <commit-hash>

Git will create a new commit that reverses the changes made by the specified commit. Afterward, push the changes and create a new PR against the target branch.

Important: Only use git revert for shared branches. For local branches where your commit history isn’t yet public, consider using git reset to rewrite history directly.


Reapplying Fixes and Recommitting 🔄

You might think you can simply return to your original branch, apply fixes, and create a new pull request (PR). However, Git won’t merge the original changes again because it considers them already applied — only the new fixes will be included.

This happens because Git tracks changes by commit history:

👻 If the commit with your original changes already exists in both branches, Git recognizes those changes as already applied and won’t merge them again, even in a new PR.

How to Apply Your Fixes 🛠️

The solution is to revert the revert. Here’s how:

  1. Get the latest version of your target branch that included the reverted commit(s).
  2. Create a new feature branch.
  3. Revert the revert commit(s) to bring back the original changes.
  4. Add your fixes.
  5. Create a new PR for your target branch.

By following these steps, you’ll have your original changes reintroduced, along with any new fixes, ready for review and merging.


Conclusion

Mastering these Git techniques requires practice, but they are essential for safely managing code, especially when working on shared branches or with large teams. Whether you’re undoing commits or reapplying changes, these tools empower you to manage your Git history cleanly and efficiently. By using git revert to undo changes and the strategy of reverting the revert to reapply fixes, you can maintain a clear, consistent commit history and avoid unnecessary complications in your workflow.

Share this post