2

I usually work on the branch "dev". I have created another branch "temp". But now I would like my last commit on temp (which is clean) to totally replace my last commit on "dev" (which is really messed up). So I can continue working on "dev" with with a clean commit.

Can you help me do this ?

Thanks

Louis
  • 2,548
  • 10
  • 63
  • 120

2 Answers2

4
$ git checkout dev
$ git reset --hard HEAD^
$ git cherry-pick temp

This will reset your dev branch to the previous commit (HEAD^ is one before the current) (reset --hard throws away all current changes, and the changes in that commit) and then apply the most recent commit of branch temp onto branch dev, preserving the state of branch temp.

git reset --hard can cause problems if used wrongly, be aware of what it does before you actually use it.

Community
  • 1
  • 1
Tim
  • 41,901
  • 18
  • 127
  • 145
  • 2
    If you are unsecure about reset you can always create a branch `save` before resetting. If everything worked well just delete `save` – JDurstberger Oct 27 '15 at 15:04
  • @Altoyr that is a decent safety-net that doesn't involve fiddling with the reflog. Good tip – Tim Oct 27 '15 at 15:08
  • @TimCastelijns thanks, but why should i go back to `HEAD^`, can't I just remove your line #2 ? – Louis Oct 27 '15 at 16:41
  • @Louis that reset will remove the messy commit. The ^ is needed to jump back to before that commit was made – Tim Oct 27 '15 at 16:45
  • cherry pick only 'adds' the change, but I would like to totally replace the last dev commit by the last temp commit....see ? – Louis Oct 27 '15 at 16:46
  • ok what I did is : git checkout dev; git reset --hard 7d062cd (which is the last clean commit on branch dev); git cherry-pick temp – Louis Oct 27 '15 at 16:48
  • @Louis yes. It is a two step operation. First you remove the last commit on dev and then you add the other with cherry pick, the result will be that is has been replaced – Tim Oct 27 '15 at 16:48
  • @TimCastelijns ok I see. I did what I just wrote in the comment above, now I have 'unresolved conflict' – Louis Oct 27 '15 at 16:53
  • ok instead of `git cherry-pick temp` I did `git cherry-pick --strategy=recursive -X theirs temp` – Louis Oct 27 '15 at 16:55
  • @Louis yes cherry picking can result in conflicts, but I suppose it's solved now – Tim Oct 27 '15 at 17:02
2

The other answer is good, but I think it can be made a little simpler still:

$ git checkout dev
$ git reset --hard temp

In the first command, you're switching to your dev branch.

In the second command, you tell git to point your dev branch to the same commit pointed to by your temp branch, and overwrite the index and working directory to match.

tway
  • 369
  • 1
  • 10