Amending Commits

Goals

  • Learn how to amend an existing commit

Change the program then commit

Add an author comment to the program.

hello.rb

  1. # Default is World
  2. # Author: Jim Weirich
  3. name = ARGV.first || "World"
  4. puts "Hello, #{name}!"

Execute:

  1. git add hello.rb
  2. git commit -m "Add an author comment"

Oops, Should have an Email

After you make the commit, you realize that any good author comment should have an email included. Update the hello program to include an email.

hello.rb

  1. # Default is World
  2. # Author: Jim Weirich (jim@somewhere.com)
  3. name = ARGV.first || "World"
  4. puts "Hello, #{name}!"

Amend the Previous Commit

We really don’t want a separate commit for just the email. Let’s amend the previous commit to include the email change.

Execute:

  1. git add hello.rb
  2. git commit --amend -m "Add an author/email comment"

Output:

  1. $ git add hello.rb
  2. $ git commit --amend -m "Add an author/email comment"
  3. [master 907a445] Add an author/email comment
  4. Date: Sat Jun 20 20:37:07 2020 +0100
  5. 1 file changed, 2 insertions(+), 1 deletion(-)

Review the History

Execute:

  1. git hist

Output:

  1. $ git hist
  2. * 907a445 2020-06-20 | Add an author/email comment (HEAD -> master) [Jim Weirich]
  3. * 4254c94 2020-06-20 | Added a comment (tag: v1) [Jim Weirich]
  4. * c8b3af1 2020-06-20 | Added a default value (tag: v1-beta) [Jim Weirich]
  5. * 30c2cd4 2020-06-20 | Using ARGV [Jim Weirich]
  6. * 4445720 2020-06-20 | First Commit [Jim Weirich]

We can see the original “author” commit is now gone, and it is replaced by the “author/email” commit. You can achieve the same effect by resetting the branch back one commit and then recommitting the new changes.