Git Pull is Not Possible, Unmerged Files

后端 未结 8 2051
小蘑菇
小蘑菇 2020-12-07 07:47

I\'ve read all of the similar questions on this; it seems that none of the following have worked:

Delete offending files
git reset --hard HEAD
git stash
git          


        
8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 08:17

    Say the remote is origin and the branch is master, and say you already have master checked out, might try the following:

    git fetch origin
    git reset --hard origin/master
    

    This basically just takes the current branch and points it to the HEAD of the remote branch.

    WARNING: As stated in the comments, this will throw away your local changes and overwrite with whatever is on the origin.

    Or you can use the plumbing commands to do essentially the same:

    git fetch 
    git update-ref refs/heads/ $(git rev-parse /)
    git reset --hard
    

    EDIT: I'd like to briefly explain why this works.

    The .git folder can hold the commits for any number of repositories. Since the commit hash is actually a verification method for the contents of the commit, and not just a randomly generated value, it is used to match commit sets between repositories.

    A branch is just a named pointer to a given hash. Here's an example set:

    $ find .git/refs -type f
    .git/refs/tags/v3.8
    .git/refs/heads/master
    .git/refs/remotes/origin/HEAD
    .git/refs/remotes/origin/master
    

    Each of these files contains a hash pointing to a commit:

    $ cat .git/refs/remotes/origin/master
    d895cb1af15c04c522a25c79cc429076987c089b
    

    These are all for the internal git storage mechanism, and work independently of the working directory. By doing the following:

    git reset --hard origin/master
    

    git will point the current branch at the same hash value that origin/master points to. Then it forcefully changes the working directory to match the file structure/contents at that hash.

    To see this at work go ahead and try out the following:

    git checkout -b test-branch
    # see current commit and diff by the following
    git show HEAD
    # now point to another location
    git reset --hard /
    # see the changes again
    git show HEAD
    

提交回复
热议问题