Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

Need to reset git branch to origin version

I was accidentally working on a branch I shouldn't have been for a while, so I branched off of it giving it the appropriate name. Now I want to overwrite the branch I shouldn't have been on to the version from origin (github). Is there an easy way to do this? I tried deleting the branch and then resetting up the tracking branch, but it just gives me the version I was working on again.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you haven't pushed to origin yet, you can reset your branch to the upstream branch with:

git checkout mybranch
git reset --hard origin/mybranch

(Make sure that you reference your latest commit in a separate branch, like you mention in your question)

Note that just after the reset, mybranch@{1} refers to the old commit, before reset.

But if you had already pushed, see "Create git branch, and revert original to upstream state" for other options.


With Git 2.23 (August 2019), that would be one command: git switch.
Namely: git switch -C mybranch origin/mybranch

Example

C:Usersvoncgitgit>git switch -C master origin/master
Reset branch 'master'
Branch 'master' set up to track remote branch 'master' from 'origin'.
Your branch is up to date with 'origin/master'.

That restores the index and working tree, like a git reset --hard would.


As commented by Brad Herman, a reset --hard would remove any new file or reset modified file to HEAD.

Actually, to be sure you start from a "clean slate", a git clean -f -d after the reset would ensure a working tree exactly identical to the branch you just reset to.


This blog post suggests those aliases (for master branch only, but you can adapt/extend those):

[alias]
   resetorigin = !git fetch origin && git reset --hard origin/master && git clean -f -d
   resetupstream = !git fetch upstream && git reset --hard upstream/master && git clean -f -d

Then you can type:

git resetupstream

or

git resetorigin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...