1

I had a script that, for each changed_file in

"git diff --name-only master..origin/master"

the diff for that file is applied like the following:

git diff master..origin/master file_name | git apply.

For any newly creately files (files in origin master but not originally in master), I got the following errors:

fatal: ambiguous argument 'my_file_name': unknown revision or path not in the working tree.

error: unrecognized input

Upon searching on SO, I found the following information on the intent-to-add flag of git add: What does git add --intent-to-add or -N do and when should it be used?

So I tried the following: for each file I'm about to get a diff of between origin/master and master, if that file doesn't currently exist in master (local), then I call git add with --intent-to-add flag prior to calling git diff with that filename and applying the diff.

if ! ls "$changed_file" 1> /dev/null 2>&1; then
        echo adding new file "$changed_file"
        echo foo > "$changed_file"
        git add --intent-to-add "$changed_file"
fi
git diff master..origin/master "$changed_file" | git apply

With this, I'm getting the following error when trying to do the git apply (last line), saying the file already exists in working directory:

error: tests/new_file: already exists in working directory

When I tried removing the dummy file creation part, like the following, it also didn't work.

if ! ls "$changed_file" 1> /dev/null 2>&1; then
        echo adding new file "$changed_file"
        git add --intent-to-add "$changed_file"
fi

with the error message being the same as before:

fatal: ambiguous argument 'my_file_name': unknown revision or path not in the working tree.

error: unrecognized input

Does anyone know what's going on, and how I can fix this? (get and apply diff of NEW remote file)

ajfbiw.s
  • 401
  • 1
  • 8
  • 22

2 Answers2

1

The problem is that in general, Git doesn't know if file_name is a file name, or a branch name, or what. The solution is to tell it: after a double dash --, nothing can be an option or branch name:

git diff --name-only master origin/master -- file_name

The same rule applies to commands like git checkout. What if you have a file named master and you want to check it out? The command:

git checkout master

won't work, but the command:

git checkout -- master

will, because the two dashes tell git checkout that this is the end of options and branch names and such: everything else must be a file name.

torek
  • 448,244
  • 59
  • 642
  • 775
1
git reset --hard origin/master      # reset index, worktree and ref
git reset --soft @{1}               # put the ref back

is all you need.

jthill
  • 55,082
  • 5
  • 77
  • 137