How do I force “git pull” to overwrite local files?

前端 未结 30 3445
失恋的感觉
失恋的感觉 2020-11-21 11:35

How do I force an overwrite of local files on a git pull?

The scenario is the following:

  • A team member is modifying the t
30条回答
  •  终归单人心
    2020-11-21 12:12

    The problem with all these solutions is that they are all either too complex, or, an even bigger problem, is that they remove all untracked files from the web server, which we don't want since there are always needed configuration files which are on the server and not in the Git repository.

    Here is the cleanest solution which we are using:

    # Fetch the newest code
    git fetch
    
    # Delete all files which are being added, so there
    # are no conflicts with untracked files
    for file in `git diff HEAD..origin/master --name-status | awk '/^A/ {print $2}'`
    do
        rm -f -- "$file"
    done
    
    # Checkout all files which were locally modified
    for file in `git diff --name-status | awk '/^[CDMRTUX]/ {print $2}'`
    do
        git checkout -- "$file"
    done
    
    # Finally pull all the changes
    # (you could merge as well e.g. 'merge origin/master')
    git pull
    
    • The first command fetches newest data.

    • The second command checks if there are any files which are being added to the repository and deletes those untracked files from the local repository which would cause conflicts.

    • The third command checks-out all the files which were locally modified.

    • Finally we do a pull to update to the newest version, but this time without any conflicts, since untracked files which are in the repo don't exist anymore and all the locally modified files are already the same as in the repository.

提交回复
热议问题