1

Git rightly gives an error when you do a git pull when the commit(s) merged would create a file that you have locally but is not tracked.

error: The following untracked working tree files would be overwritten by merge

I would like to detect this situation in a script so that I can do something about it before doing the git pull for real.

How can I do this? I tried git pull --dry-run but annoyingly that does not notice that the pull would fail (git version 2.11.0)

Test

mkdir a b; cd a
git init .; echo hi >file1 ; git add .; git commit -m "initial commit"
cd ../
git clone a b
cd a; echo boo>file2; git add .; git commit -m "2nd commit"
cd ../b
echo xxx>file2
git fetch

if some_git_command_detects_pull_would_fail
then
  echo 'Uh oh!'
fi

Nb. I realise I can "clean" out untracked files; that untracked files are nasty; that I can stash changes etc. but this is not what I want.

artfulrobot
  • 20,637
  • 11
  • 55
  • 81
  • Never use `git pull` in scripts. (Well, hardly ever. Recursive fetch-and-merge, with submodules, is ugly. But pull is very porcelain, not at all plumbing-friendly.) – torek Feb 15 '19 at 09:37
  • Thanks for your comment. It's an interactive script that saves me typing; not an automated process. – artfulrobot Feb 15 '19 at 09:41
  • Even then, just break it into fetch + merge. You'll know if the merge would fail because the merge fails. You can back the merge out if it succeeds (or use `--no-commit` as in the answer I've upvoted), if that's part of the general plan. – torek Feb 15 '19 at 10:10

2 Answers2

1

git pull is a shortcut for : git fetch + git merge

One way to "detect" before applying pull is :

  • run git fetch
  • check if some files in the remote branch would clash with existing files on your disk :

    • run git merge --no-commit with the upstream branch

      # if current branch is "linked" to a remote branch,
      # @{u} is a shortcut to say "the linked remote branch"
      git merge --no-commit @{u}
      
      # or you can explicitly name the remote reference :
      git merge --no-commit origin/you/know/what/branch
      
    • see if this action triggers any errors or merge conflicts

    • revert to what it was previously :

      git merge --abort
      

Another way to check "would this merge create conflicts ?" is offered in this answer

LeGEC
  • 46,477
  • 5
  • 57
  • 104
1

Thanks to LeGEC's hint, I've found something that appears to work:

function merge_will_work {
  git diff master..origin/master | git apply --check &>/dev/null
  return $?
}
  • Creates the patch
  • Tests whether it would apply cleanly
  • (Importantly) does not change a single file either way. (avoids a merge/merge abort situation where files may be momentarily changed.)
artfulrobot
  • 20,637
  • 11
  • 55
  • 81