Undoing Things in Git, Guide
One of the ways you can "undo" things in Git, is by using the --amend flag when you commit. You can use it to add files to the previous commit or just edit the message of a commit.
Visualising git commit --amend
Adding "forgotten" files to a commit
In short, when you commit a change, e.g., File.swift and you realize that you didn't commit another file that "belonged" to the scope of the previous commit, e.g., FileTest.swift, instead of committing again just FileTest.swift, you can stage FileTest.swift and commit using the --amend flag.
This flow will generate a new commit (it will have a new hash as it is a new commit) containing the initial changes plus the ones that you staged. In this example, you will end up with both File.swift and FileTest.swift in the same commit.
Please note when you execute git commit --amend Git will prompt you to enter a commit message for your changes. In case you don't want to change the commit message you can simply provide the --no-edit flag as well and Git will not show you the vim editor. Otherwise, if you want to change the message, you can enter vim's Insert mode by typing i, type any changes and save and exit hitting ESC then : then wq and finally the ENTER key.
Here is an example using the commands mentioned above:
With editing the message
$ git add File.swift (stage File.swift) $ git commit -m 'Add File.swift' (commit staged changes with message) $ git add FileTest.swift (stage FileTest.swift) $ git commit --amend (amend staged changes to PREVIOUS commit with new commit message prompt)
Without editing the message
$ git add File.swift (stage File.swift) $ git commit -m 'Add File.swift' (commit staged changes with message) $ git add FileTest.swift (stage FileTest.swift) $ git commit --amend --no-edit (amend staged changes to PREVIOUS commit without changing the commit message)
Editing a Commit Message
In case there is nothing to commit or there are unstaged files, you can use git commit --amend to edit the message of the last commit. Again, Git will prompt you to make any changes, using the vim editor. This flow can be particularly useful when you commit and immediately spot a typo in the commit message.
Here is a workflow of this use case:
$ git add File.swift (stage File.swift) $ git commit -m 'Add Filr.swift' (commit staged changes with a message containing a typo) $ git commit --amend (fix the typo by editing the message of the PREVIOUS commit with new commit message prompt)