git command for making one branch like another

2018-12-31 15:21发布

I'm trying to take a branch with changes and bring it back to be identical to the upstream it diverged from. The changes are both local and have been pushed to github, so neither git reset or git rebase are really viable, since they change history, which is a bad thing with a branch that's already been pushed.

I've also tried git merge with various strategies but none of them undo the local changes, i.e. if I'd added a file, a merge might bring other files back in line, but I'll still have that file that the upstream doesn't have.

I could just create a new branch off the upstream, but i'd really like a merge that in terms of revision history applies all the changes to take my branch and make it identical to the upstream again, so that I can safely push that change without clobbering history. Is there such a command or series of commands?

8条回答
心情的温度
2楼-- · 2018-12-31 16:16

It sounds to me like you just need to do:

$ git reset --hard origin/master

If there is no change to push upstream, and you simply want the upstream branch to be your current branch, this will do that. It is not harmful to do this locally but you will lose any local changes** that haven't been pushed to master.

** Actually the changes are still around if you have committed them locally, as the commits will still be in your git reflog, usually for at least 30 days.

查看更多
只靠听说
3楼-- · 2018-12-31 16:18

Use git reset BACKWARDS!

You can make a branch look like any other commit with git reset, but you have to do it in a round-about way.

To make a branch on commit <old> look like a commit <new>, you can do

git reset --hard <new>

in order to make <new> the contents of the working tree.

Then do

git reset --mixed <old> 

to change the branch back to the original commit but leaving working tree in the <new> state.

Then you can add and commit the changes, in order to make your branch exactly match the contents of the <new> commit.

It's counter-intuitive that to move from the <old> state to the <new> you need to do a git reset from <new> to <old>. However with the option --mixed the working tree is left at <new> and the branch pointer set to <old>, so that when the changes are committed the branch looks how we want.

Warning

Don't lose track of your commits, e.g. forget what <old> is when doing git reset --hard <new>.

查看更多
登录 后发表回答