Junior
How to undo the last commit in a version control system?
sobes.tech AI
Answer from AI
There are several ways to use Git:
1. Undo the last commit while keeping changes:
git reset --soft HEAD~1
# Undoes the last commit, staged changes remain
# Working directory is unchanged
2. Undo the last commit, unstage changes but keep working directory changes:
git reset --mixed HEAD~1
# Undoes the last commit and unstages changes
# Working directory is unchanged
3. Completely undo the last commit, including changes:
git reset --hard HEAD~1
# Completely undoes the last commit
# Staged changes and working directory are reset to the state before the last commit
# All unsaved changes in the working directory will be lost
4. Create a new commit that reverts the last commit:
git revert HEAD
# Creates a new commit that reverts the last commit
# The history is preserved, this is a safe method when working with public branches
The choice depends on the desired outcome and whether the branch has been published. --hard should be used with caution as it can lead to data loss. git revert is preferred when working with branches used by other developers.