2024年7月4日 00:16

Git: How to Modify Previous Commit Author Information?

When working with Git for version control, modifying the author information of previous commits can be achieved using the git rebase command with the --author option or the git filter-branch command. Below are the detailed steps and examples:

Modifying Author Information for Individual Commits Using git rebase

To modify the author information for specific commits, use the git rebase command. Follow these steps:

  1. Start Interactive Rebase: Run git rebase -i to select the commits you want to modify. For example, to change the last three commits, use git rebase -i HEAD~3.

  2. Mark Commits for Modification in the Editor: Change pick to edit for the commits you wish to modify, then save and exit the editor.

  3. Modify Author Information: For each commit marked as edit, execute the following command to update the author:

    bash
    git commit --amend --author="New Author Name <new email address>" --no-edit
  4. Continue the Rebase Process: Use git rebase --continue to complete the rebase until all changes are applied.

Modifying Author Information for Multiple Commits Using git filter-branch

For modifying author information across multiple commits in the project history, use git filter-branch. This command is powerful but complex and should be used cautiously. Here's how to proceed:

  1. Backup the Current Branch: Before performing large-scale operations, back up the current branch:

    bash
    git branch backup-branch-name
  2. Use filter-branch to Modify Author Information: The following command updates all commits to the specified new author:

    bash
    git filter-branch --env-filter ' OLD_EMAIL="old email address" CORRECT_NAME="new author name" CORRECT_EMAIL="new email address" if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ] then export GIT_COMMITTER_NAME="$CORRECT_NAME" export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL" fi if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ] then export GIT_AUTHOR_NAME="$CORRECT_NAME" export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL" fi ' --tag-name-filter cat -- --branches --tags
  3. Verify the Changes: After completion, check the history to confirm the updates:

    bash
    git log --pretty=full
  4. Push the Changes: If everything is correct, push the changes to the remote repository (note: this will overwrite the remote history):

    bash
    git push --force --all git push --force --tags

Important Considerations

  • Performing these operations will alter the Git history; in a team environment, this may impact other developers.
  • After using git filter-branch, all clones, branches, and checkouts should be recreated to match the modified history.
标签:Git