Reputation: 130
I decided to integrate a library into my code. I add the library, and change a couple lines of code to start implementing it. It compiles, so I commit and push to the repo.
I only realise later that I've missed a line that is still on old code.
I give it a google search and find out about git commit --amend
, and lucky for me, there are no other commits.
I thought all I had to do was fix the line of code, git add
the file, git commit --amend
, and finally git push
that to the repo, but git tells me
! [rejected] master -> master (non-fast-forward) hint: Updates were rejected because the tip of your current branch is behind
I find that strange since I'm on the latest commit and if I git reset -soft HEAD~1
I am back to being aligned with the repo, besides the single line of code I've changed.
Am I doing it wrong? I really don't want to make an entirely new commit just for this single line of code that should've been part of the last commit.
Upvotes: 1
Views: 224
Reputation: 521194
If you really want to amend the commit, then you will need to force the branch to the remote:
git push origin master --force
Keep in mind that this will overwrite the remote branch, which might potentially cause havoc for anyone else sharing the branch.
Also, you need to ascertain that no new commits were added to the remote branch since the commit which you are trying to amend. Forcing your branch out will clobber any new work from someone other than you which was made after the commit in question.
As you can tell, there are many things that could go wrong here. So a much safer strategy, and what I recommend for you, is to simply fix the missing line of code in a new commit and then push your changes out to the remote.
Update:
The reason you were getting the Updates were rejected because the tip of your current branch is behind
error is because amending the commit on the HEAD of your local branch actually caused your local branch to diverge from the remote. Here is a diagram showing what your local and remote master
branches looked like before the amend:
remote: A -- B -- C
local: A -- B -- C
In other words, you were up to date. However, when you amended commit C
locally, you actually replaced it with a completely new commit (with a new SHA-1 hash). Here is what the diagram looked like after the amend:
remote: A -- B -- C
local: A -- B -- C'
When you tried pushing, Git thought that commit B
was the common ancestor, and that you were actually behind the remote master
. Another way of drawing this is:
remote: A -- B -- C
local: \_ C'
Git doesn't realize that you intend for your amended commit to replace C
on the remote, so you have to do a force push to achieve this.
Upvotes: 4