Challenge 002 - Undo a commit while keeping the changes
Scenario
You just made a local commit (one you have not pushed to any remote), but you realize you did it too soon: you wanted to keep editing. Your goal is to undo that last commit but keep all the changes so you can keep working and commit again later.
Because the commit is local and unpublished, it is safe to rewrite history.
How to solve it
# 1. View the history to confirm which is the last commit
git log --oneline
# 9c8b7a6 Commit prematuro que quiero deshacer <- HEAD
# 1a2b3c4 Commit anterior (este se queda)
# 2. Undo the last commit keeping the changes STAGED
git reset --soft HEAD~1
# HEAD~1 means "one commit before the current one"
# --soft: undoes the commit but leaves the changes staged
# 3. Verify: the commit is gone, but the changes are still ready
git status
# Changes to be committed: (your files are still staged)
git log --oneline
# 1a2b3c4 Commit anterior (este se queda)
Why it works
git reset --soft HEAD~1 moves the branch pointer back one commit (HEAD~1), "removing" the last commit from the history. The --soft mode is the key: it keeps the changes in the staging area, ready to commit again. With --mixed (the default) they would be unstaged; with --hard they would be deleted (that would lose your work).
Full solution
View commented solution
# Option A: keep the changes STAGED (ready to re-commit)
git reset --soft HEAD~1
# Option B: keep the changes UNSTAGED (in the working directory)
git reset --mixed HEAD~1
# or simply: git reset HEAD~1 (mixed is the default mode)
# Now you can keep editing and commit again when you are ready
echo "mas contenido" >> archivo.txt
git add .
git commit -m "Version final con los cambios completos"
Key point: use --soft or --mixed to keep your work; never use --hard here because it would delete the changes. And this is safe only because the commit was local: if you had already published it, you would use git revert instead.