Home / Companies / Mergify / Blog / Post Details
Content Deep Dive

How to Git Delete Last Commit Safely

Blog post from Mergify

Post Details
Company
Date Published
Author
Huguette Miramar
Word Count
2,507
Language
English
Hacker News Points
-
Summary

The text provides an in-depth examination of how to handle Git commits, especially focusing on the scenarios where a developer might need to undo a commit. It emphasizes the use of `git reset` for local commits that haven't been pushed to a shared repository, detailing its three modes: `--soft`, which removes the last commit while keeping changes staged; `--mixed`, which unstages changes but keeps them in the working directory; and `--hard`, which permanently deletes all changes. For commits that have been pushed, the text advocates using `git revert`, which creates a new commit to reverse the changes, preserving the project's history and avoiding potential conflicts in a shared environment. The guide also cautions against rewriting shared history and describes the risks associated with using force push commands like `git push --force`, recommending `git push --force-with-lease` as a safer alternative to prevent overwriting others' work. Additionally, it covers scenarios like recovering from an accidental `--hard` reset using Git's reflog and amending the last commit message with `git commit --amend`. Throughout, the guide stresses the importance of careful command use to maintain a clean, collaborative project history.