This article is part of our ongoing "Advanced Git" series. Stay tuned for future installments by following Tower on Twitter or subscribing to their newsletter.
Interactive Rebase: Your Git History's Best Friend
Interactive rebase is a powerful Git tool, offering a wide range of options for refining your local commit history before sharing changes with your team. Think of it as the Swiss Army knife of Git commands. Let's explore its capabilities and practical applications.
Interactive rebase empowers you to modify your commit history for improved organization and clarity. Key actions include:
Important Note: Interactive rebase rewrites your commit history, assigning new hash IDs to affected commits. Since commit IDs are crucial identifiers (SHA-1 checksums), this creates entirely new commits. Therefore, never use interactive rebase on commits already pushed to a shared remote repository. Doing so could disrupt your colleagues' work. Use it to clean up your local history before merging and pushing to a shared branch.
Regardless of the specific operation (deleting, messaging, combining, etc.), the workflow remains consistent:
git log
to examine your project's history before starting.Let's illustrate with examples:
For the most recent commit, git commit --amend
offers a simpler solution. This opens your default editor to modify the message and content. However, avoid amending pushed commits.
For older commits, use interactive rebase:
git rebase -i HEAD~3
This opens an editor showing the three commits. Change pick
to reword
to modify the message. Save, close, and edit the message again before saving and exiting.
To combine commits (e.g., "7b2317cf Change the page structure" and "6bcf266 Optimize markup"), determine the base commit and use:
git rebase -i HEAD~3
Change pick
to squash
on the second commit (combining it with the one above it). Save and close. A new editor window appears to create a combined commit message.
Tower Tip: In Tower, drag and drop commits to squash, or right-click to edit commit messages.
Use the drop
keyword to remove a commit:
drop 0023cdd Add simple robots.txt pick 2b504be Change headlines for about and imprint pick 6bcf266 Optimizes markup structure in index page
If you need to undo an interactive rebase, use:
git rebase --abort
This covers just a fraction of interactive rebase's capabilities. Explore its full potential and other advanced Git techniques with our free "Advanced Git Kit" (a collection of short videos).
Happy rebasing! Join us next time for more "Advanced Git" insights!
The above is the detailed content of Interactive Rebase: Clean up your Commit History. For more information, please follow other related articles on the PHP Chinese website!