51

Basically, I have an open pull request that I want to fix and at the same time I want to make 1 commit that contains 2 features into 2 seperate commits.

Github repository now looks like this where fix is a new branch:

master c-c-c
            \
     fix c-c-c-c

I created a pull request from fix.

I wanted to change the last commit in fix into 2 commits in my local repository as follows:

master c-c-c
            \
     fix c-c-c-n-n

where n-n are my 2 new commits.

To get to this point locally, I did this:

1. git rebase -i HEAD~2
2. Changed my last commit line to "edit", saved and closed the file
3. git reset HEAD^
4. git stash save
5. Removed the changes I don't want in the first commit
6. git commit -m "commit a" -a
7. git stash apply
8. git commit -m "commit b"

So now I have 2 commits the way I want. The problem is I found a bug that ended up in the pull request. Since I have already pushed to the remote repository, it won't accept my new commits (as the original one is now missing).

I run:

git push origin fix --dry-run

and I get the message:

To git@github.com:<UserName>/<Repository>.git
! [rejected]        fix -> fix (non-fast-forward)
error: failed to push some refs to 'git@github.com:<UserName>/<Repository>.git'

I have seen other posts suggest to pull my changes from origin before pushing back again, but won't that basically reset my 2 commits back into the one?

Ideally, what I would like to do is assign the same commit ID to the last commit so it can replace the current one as is. Is there a way to do that? (Note that I didn't run git reset with --hard)

NightOwl888
  • 55,572
  • 24
  • 139
  • 212

1 Answers1

89

When faced with that problem, a force push has worked for me:

git push --force origin fix
Nate
  • 12,499
  • 5
  • 45
  • 60
  • 1
    That worked like a charm. In case anyone reads this and wonders what happened to my pull request, it simply replaced the 1 commit with 2. I added a comment at Github to the project owner to let him know to fetch in case he has done so already. – NightOwl888 Apr 07 '12 at 14:06
  • So to clarify: is it correct that if the project owner has already merged in the pull request, after which I do a `git push --force origin fix`, then a `git fetch` from the project owner's end would pull in the fix? – PonyEars Sep 25 '13 at 22:09
  • 4
    The project owner will need to do a reset if the changes have already been pulled, because the commit will still exist in his branch. `git fetch origin` then `git reset --hard origin/master`. See: http://stackoverflow.com/questions/1628088/how-to-reset-my-local-repository-to-be-just-like-the-remote-repository-head – NightOwl888 Sep 26 '13 at 05:34
  • 8
    Use --force-with-lease instead of --force : it will force only if there is no intermediate commit. See : https://developer.atlassian.com/blog/2015/04/force-with-lease/ – Benj Jul 07 '16 at 15:11