Can git merge/pull detect when "local changes" are the same as an incoming merge conflict?

StackOverflow https://stackoverflow.com/questions/19441027

  •  01-07-2022
  •  | 
  •  

Question

I run into this sometimes:

  1. On server, git clone myrepo
  2. Change foo.sh on machine 1 to solve some problem.
  3. It works, so replicate the change on my development machine.
  4. On dev machine, git add foo.sh, git commit, git push
  5. On server, git pull

    remote: Counting objects: 1, done.
    remote: Compressing objects: 100% (1/1), done.
    remote: Total 5 (delta 4), reused 5 (delta 4)
    Unpacking objects: 100% (5/5), done.
    From ...
       c78..e4d  master     -> origin/master
    Updating c78..e4d
    error: Your local changes to the following files would be overwritten by merge:
        foo.sh
    
    Please, commit your changes or stash them before you can merge.
    Aborting
    

Is there a way that Git could be a bit smarter, and notice that the "local changes" are identical to the merge changes? Obviously I could simply git reset --hard', but I'd like to double check that the changes I've made remotely really are the same.

Was it helpful?

Solution

You can diff directly against the new tree. git diff origin/master compares the working directory against the upstream changes (the tree you just tried to merge) and so should answer your question about whether the changes match and whether it's safe to throw away your local changes.

The git documentation warns against doing pulls and merges with uncommited changes; I don't think you'll be able to get the automatic behaviour you're asking for.

OTHER TIPS

I'd like to double check that the changes I've made remotely really are the same.

You can, but not automatically through git.
Although you can use a script similar to this one, except that instead of doing directly a 'rm', you could compare the file from origin/yourBranch with the file from your current working tree (and rm if identical).

# 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
    # diff between "$file" and $(git show origin/master:$file)
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top