简体   繁体   中英

Pushing git branch after hard reset

I am a total beginner with git, so plz pardon my silly words if any.

Okay, so I have a local branch where I've done hard reset to a certain commit. And now when I do git status it shows that -

On branch product
Your branch is behind 'origin/product' by 3 commits, and can be fast-forwarded.
  (use "git pull" to update your local branch)

nothing to commit, working tree clean

Which is why I can't push my branch, as I first have to pull the changes.

Now, I do understand why this is happening, (because hard reset removes all the git history after that certain commit, and the remote branch does have those commits, therefore its telling me that origin/product branch is ahead by 3 commits) (plz correct me if I'm wrong)

So how can I push the changes made by hard reset?

Git tries to preserve the history wherever applicable, so with default settings it will not "revert" branches on push.

To force overwrite a remote branch with the tip (head) of your local branch, the traditional way was to use a "force push":

git push -f
git push --force  # Equivalent

However, note that the above command pushes all your branches in "force mode". If you want to do it safer by pushing only one branch, use this syntax:

git push origin +master

The plus sign means "overwrite", and as you've specified the branch name, only master will be force-pushed.

Both methods cover two cases of both "reverting" and "overwriting with diverged histories".


By the way, this understanding is (partially) wrong:

hard reset removes all the git history after that certain commit

Hard resets does not remove any commit from Git's local storage (that .git directory), but only points your current branch (head) at the target commit, and checks out any files changed.

Your commits stays in Git storage until GC'd. The easiest way to verify that they still exists (and intact!) is to examine the output of git reflog . You can also check them back using commands similar to git checkout/reset 'HEAD@{1}' should you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM