pull specific commit/file from git

前端 未结 2 868
夕颜
夕颜 2021-02-08 10:09

I have made two commits in my git repository and push them to my git server

the two commits are

  • In first commit file A is committed
2条回答
  •  鱼传尺愫
    2021-02-08 11:02

    First, on your development server, you'll need to fetch the list of commits from the git server like this:

    git fetch origin master (or whatever branch you need)
    

    Then there are a few options to achieve what you want:

    Cherry pick the first commit - this simply 'plucks' the chosen commit from another branch/repo and applies it to your current local branch. It can be very useful, but should be used with caution (see below).

    git cherry-pick  
    

    In this particular case, you could do

    git cherry-pick FETCH_HEAD^ (gets commit before the HEAD of what's been fetched)
    

    Or, pull everything and then do a hard reset to the commit you want (in this case the one just before HEAD). A hard reset effectively rewinds your local branch back in time to the chosen commit, changing the state of all files to how they were at that time (so in this case File B would either be deleted, or go back to how it was before either commit, depending on whether or not it previously existed).

    git pull
    git reset --hard HEAD^ (or git reset --hard )
    

    I would prefer the second option as cherry-picking can have some knock on effects if you're not careful with it. I believe it creates a new hash for the commit, so the cherry-picked commit and the original commit aren't identical. I'm afraid I don't have time right now to read up on this and confirm exactly what the pitfalls are, but I would strongly recommend that you investigate it for yourself if you decide to use it.

    EDIT - Another solution (given that this is a live server and that it's not acceptable for File B to appear on the server at any point) is to do the following:

    git fetch origin master
    git checkout FETCH_HEAD^
    

    This fetches all commits from the repo, and then checkes out your local repo to the commit before the HEAD of what was fetched. The only downside here is that you will then be in 'detached head' state and will have to create a new branch locally, but that's not a big problem.

提交回复
热议问题