In this lesson, you watched a forgotten file go into the last commit in the practice folder, and you saw Git replace that commit with a new one. Both files are in The Final Code below, so you can try it in your own practice folder.
Key Points
- A commit can come out incomplete. Your commit took the new import in
prices.js, butgit statusstill listed the helper fileformat.jsunder “Untracked files”. This happens to everyone, most often with a new file, becausegit addstages only the files you name. - That commit’s snapshot has a
prices.jsthat imports aformat.jsthe snapshot doesn’t have, so anyone who gets these files back from it gets an error. You could commit the forgotten file on its own, but your history would then hold a commit that can’t run without the next one. The file belongs in the commit you made last. - To put it there, stage the file as usual. Check with
git statusthat it’s the only staged file, because amend takes in everything that’s staged. Then rungit commit --amend. The--amendoption tells Git to replace your last commit rather than add another one after it, and--no-editkeeps the message you already wrote. TheDate:line Git prints is the author date, when you first made the commit. Git also records when you amended, as the committer date, but doesn’t print it here. - The amended commit gets a new hash. Git calculates a hash from what’s in the commit, such as its snapshot, its label and its parent, and the snapshot now has one more file. Git doesn’t edit your commit. It makes a new one with the same parent and the same message, and marks it as the commit you’re on. The old commit leaves the list that
git logshows. - Check the result with
git show --stat, which lists every file the last commit changed. - Amend can fix the message too. Leave out
--no-edit, and Git opens your editor with your last message. Change it, save, and close the tab, as when you wrote a commit body. Because amend takes in anything staged, rungit statusfirst and check that nothing is staged:
$ git status
On branch main
nothing to commit, working tree clean
--amendonly ever replaces your latest commit. If you spot a typo three commits back and amend, the fix lands in your latest commit, and the older one stays as it was. For an older commit, fix the file and make a new commit of its own.- Because amend swaps in a new commit, use it only on commits nobody else has a copy of. Everything you’ve committed so far lives only on your computer, so you’re free to amend.