35 Fixing Commits

One of the advantages of Git is the ability to “fix” commits. Fixing changes can be as simple as fixing typos that got committed, fixing a bug you didn’t catch because you hadn’t run your unit tests yet, or doing something as complex as rearranging an entire series of commits so they are ordered more logically.

git commit --amend is the way to fix the most recent commit. It comes in handy for those simple fixes that you catch right away. It is a convenience wrapper around using git reset --soft HEAD^ (see Task 37, Resetting Staged Changes and Commits) and git commit -c ORIG_HEAD. You can use the -C parameter with --amend when you want to reuse the original commit message.

You can use git rebase -i to replay the history of your repository and stop at certain points. Run the command, provide it with the parent of the commit you want to edit, and then mark that commit as “edit.” Git stops at that point and then lets you work on your repository as if it were the previous commit (see Task 28, Controlling How You Replay Commits).

You can fix typos, remove some buggy code, or do anything else you would normally do with the previous commit. Then, call git rebase --continue so Git can finish rebasing the rest of the history.

It’s worth noting again: be careful when rewriting history. Feel free to rewrite to your heart’s content until you share your work. After that, only rewrite when you have no other option available.

What To Do...
  • Amend the previous commit.

    Make the changes you want and stage those changes, and then use this:

     
    prompt>​ git commit --amend
     
    ...​ launch editor ...
  • Amend the previous commit, and keep the same log message.
     
    prompt>​ git commit --amend -C HEAD
     
    [master 38ec64e] update the README
     
    1 files changed, 5 insertions(+), 0 deletions(-)
  • Fix the previous commit by removing it entirely.
     
    prompt>​ git reset --hard HEAD^
     
    HEAD is now at 68f3164 use json if available
  • Use interactive rebase to edit a commit other than the last one.

    This command allows you to rewrite history by changing commits. In this example, say you want to edit the third commit before HEAD:

     
    prompt>​ git rebase -i HEAD~3
     
    ...​ launches editor, mark the first commit (the one you want
     
    ...​ to change) as "edit" instead of "pick", then save
     
    ...​ and exit your editor
     
    ...​
     
    ...​ make the change you want to your commit, then:
     
    prompt>​ git commit --amend
     
    prompt>​ git rebase --continue

Related Tasks

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.134.130