The title summarizes it perfectly. I have a couple commits on the main GitHub branch that I would like to add a co-author too. I tried using git --amend
and adding the email and name to the commit in the proper syntax, but it didn't work and the text itself just showed up. I'm not sure if this is because I got the syntax wrong or if it simply doesn't work but I couldn't find any resources about this online. If have any information please let me know!
It is possible, but for shared branches it's not advisable.
Changing the Git history of shared branches is rarely a good idea and always best avoided. There may be some exceptions to this, such as removing accidentally pushed credentials.
As @torek alluded to, commits are immutable. So, what you'd be doing is changing the commit history, this has a cascading effect on all future commits so anyone who has your code checked out will need to reset to the remote after and, any pending PRs will become invalid.
In other words, if you have your main
or some other shared branch in mind, I suggest leaving it. However, if it's in a feature branch that hasn't been merged to a shared branch yet, then you can absolutely add the co-authors after the fact!
In your local repository, first make sure you've pulled any changes on the remote branch with git fetch
and git pull
respectively.
git fetch --all
git pull {remote} {branch}
Then you want to start an interactive rebase with git rebase -i
. This will rewind commits, and allow you to specify actions to do while replaying them, such as squashing, amending, or dropping entirely.
The 2nd parameter should be the commit reference for the earliest commit you want to modify, you can just do HEAD~N
to specify N commits back. For example, HEAD~5
if the last commit to modify is 5 commits back.
git rebase -i HEAD~5
This will provide you with instructions, for all commits you want to have a different commit message for, change the action on the left from pick
to edit
or e
and save/exit the editor.
This is when git will rewind and start replaying commits, but it'll halt on any commit you set to edit
so you can make amendments before it continues to replay.
Use git commit --amend -m
to change the message to what you want, which in your case should include:
…
Co-authored-by: Name <name@example.org>
Then do git rebase --continue
to proceed with editing the next commit you marked with edit
.
When you're finished, you should be able to review the history in git log
so check there to make sure you're happy with that.
Finally, because the history has changed, you'll need to do git push --force-with-lease
.
git push --force-with-lease {remote} {branch}
During the rebase you can always do git rebase --abort
to panic out of it.
If after the rebase you find that you accidentally messed something up, immediately stop what you're doing and look into git reflog
to try and recover the previous state of your local branch before you started rebasing!