4

I have created a feature branch and made somes commits on it

Now I would merge my feature-branch to develop but I would not take the last commit.

How can I merge before penultimate commit ?

Romain Valeri
  • 19,645
  • 3
  • 36
  • 61
infodev
  • 4,673
  • 17
  • 65
  • 138
  • 1
    Possible duplicate of [How to revert a Git repository to a previous commit](https://stackoverflow.com/questions/4114095/how-to-revert-a-git-repository-to-a-previous-commit) – Code-Apprentice Apr 09 '19 at 21:16

1 Answers1

3

You can make a backup, undo the unwanted commit on your branch, then push.

git branch <backup_feature> <feature-branch>
git checkout <feature-branch>
git reset --hard HEAD^
git push origin HEAD

and you'll have a backup of the last (unwanted) commit on branch <backup_feature>.

If the last commit was really unwanted, just keep on working on your branch, it's gone.

If, in the other hand, you need it back on your branch after the push, just

git merge <backup_feature>

It'll be a transparent fast-forward (as long as you don't commit again on the branch before merging this commit back in. If you do merge it back later on, you might have to resolve conflicts)


Recap of what's in comments below : OP did already push the feature branch with the unwanted commit to remote. Suggestion has been to push with --force to update the remote ref and, subsequently, the associated pull request.

Romain Valeri
  • 19,645
  • 3
  • 36
  • 61
  • Ok I understand, then `git branch -d `, I thought it's possible to select directly the commit to merge – infodev Mar 14 '19 at 09:35
  • 2
    @infodev Yes, eventually, but no rush, branches are so lightweight, and you never know... – Romain Valeri Mar 14 '19 at 09:36
  • the last unwanted commit will be on ( not backup_feature) I think because you checkout then you reset last commit on it, no ? Edit: mea culpa I have understand now – infodev Mar 14 '19 at 09:41
  • 1
    No. We checkout the branch, then we set its pointer back one commit (`HEAD^` means the last commit's parent). The pointer of our backup hasn't been moved and still has last commit. Do a `git log --oneline -10` between each step to see what happens with your refs. And your "culpa" is "minima" ;-) We've all been there, no worries. – Romain Valeri Mar 14 '19 at 09:43
  • I get an error when push origin HEAD: `Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes` should I force the push ? – infodev Mar 14 '19 at 09:51
  • 2
    Hmm... so you already pushed that unwanted commit, that's something you didn't mention. And if so, yes, you'll have to push with `--force` on remote. Can I safely assume it is a feature branch no one works on but you? In this case you'll be all set to create (or update) your pull request from your branch to `develop`. – Romain Valeri Mar 14 '19 at 10:15