Edit a Commit
Edit a commit (latest or old) to insert something extra and safely push
NOTE: As a thumb rule
it's recommended to edit commits on you own branch, if someone else is co-working on the same branch, then do these with caution.
Add a change to the last commit
- Make your code changes:
nano path/to/file
- Check what changed:
git status
git diff <file_path>
- Stage the changes:
git add path/to/file
- Replace/update the latest commit while keeping its message:
git commit --amend --no-edit
To edit the commit message, use:
git commit --amend -m "new commit message"
- Verify the amended commit:
git status
git log --oneline --decorate -5
-
Confirm exactly what differs from the remote
-
Safely overwrite the remote version of the amended commit:
git push --force-with-lease origin branch-name
Why --force-with-lease: If a coworker pushes new commits to the same remote branch while you are working, a standard --force push will blindly overwrite and permanently erase their changes.
- Check the remote to see new changes
Editing an Older (Deep) Commit
- Start an interactive rebase counting back the number of commits (eg: last 3 commits):
git rebase -i HEAD~3
This will open an editor like Nano
-
Change the word
picktoeditnext to the target commit. -
Save and exit the editor
-
Do your file changes, then run:
4.1. Stage the changes:
git add <file>
4.2. Incorporate the changes into the older commit:
git commit --amend
4.3. Complete the rebase process:
git rebase --continue
4.4. Push the changes to remote
git push --force-with-lease origin branch-name
Already edited, not commited, add to older commit
- Stash your current uncommitted changes:
git stash
-
Follow the step in
Editing an Older (Deep) Commitfrom 1 to 3 -
Pop your stashed changes back:
If the stashed item was the last in.
git stash pop
If there more stashes on top of stash you required, then use git stash list to get the number of stash, which look like stash@{2} then the command will be like git stash pop stash@{2}.
- Stage the changes:
git add <file>
- Incorporate the changes into the older commit:
git commit --amend --no-edit
- Complete the rebase process:
git rebase --continue
- Push the changes to remote (now the hash of commit in local and remote is changed)
git push --force-with-lease origin branch-name