Guide to Amending Git Commits

Aug 22, 2024

Amending Git Commits

Introduction

  • Presented by Nick Dunatakis
  • Focus on changing git commits:
    • Modifying commit messages
    • Interactive rebase to alter past commits
  • Importance of rewriting history before pushing code to remote repositories.

Basic Use Cases

Modifying the Last Commit Message

  • Use git commit --amend to change the last commit message.
  • Example:
    • Original message: "update docs to fix formatting"
    • New message: "update documentation to fix formatting"
  • Check changes with git log to verify the new message.

Amending Changes in the Last Commit

  • Scenario: Want to include additional changes in the last commit.
    • Make changes to a file.
    • Stage changes: git add [file] or git add -p for partial staging.
  • Use git commit --amend --no-edit to add staged changes without changing the commit message.

Interactive Rebase

  • Purpose: Modify commits further back in history (not just the last commit).
  • Steps:
    1. Identify the commit to edit using git log or reference it via HEAD~n.
    2. Run git rebase -i [sha or HEAD~n].
    3. Change pick to edit for the commit you want to modify.
    4. Save and close the file to begin the rebase.
  • Important to remember to use ^ (caret) when referencing commits by SHA to indicate the parent commit.

Making Changes After Starting a Rebase

  • After editing, make the necessary changes to files.
  • Stage changes and run git commit --amend.
  • Complete the rebase with git rebase --continue.

Aborting a Rebase

  • If you want to cancel a rebase in progress, use git rebase --abort to revert to the original state.

Handling Uncommitted Changes

  • Scenario: Having uncommitted changes that you want to keep separate from the rebase.
  • Use git stash to save uncommitted changes, then proceed with the rebase.
  • After completing the rebase, use git stash pop to restore the stashed changes.

Conclusion

  • Amending commits is a valuable tool in version control.
  • Encouragement to practice these commands for better workflow management.
  • Call to action: Like the video, leave comments for feedback or questions.