【问题标题】:Git: Apply Diff of New FileGit:应用新文件的差异
【发布时间】:2018-10-19 00:00:37
【问题描述】:

我有一个脚本,对于

中的每个 changed_file
"git diff --name-only master..origin/master"

该文件的差异应用如下:

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

对于任何新创建的文件(原始 master 中的文件但最初不在 master 中的文件),我收到以下错误:

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

error: unrecognized input

在SO上搜索,发现git add的intent-to-add标志如下:What does git add --intent-to-add or -N do and when should it be used?

所以我尝试了以下方法:对于每个文件,我将获得 origin/master 和 master 之间的差异,如果该文件当前在 master(本地)中不存在,那么我调用 git add 并使用 --在使用该文件名调用 git 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

有了这个,我在尝试执行 git apply(最后一行)时收到以下错误,说文件已经存在于工作目录中:

error: tests/new_file: already exists in working directory

当我尝试删除虚拟文件创建部分时,如下所示,它也不起作用。

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

错误信息与之前相同:

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

error: unrecognized input

有谁知道发生了什么,我该如何解决这个问题? (获取并应用新远程文件的差异)

【问题讨论】:

    标签: bash git shell github diff


    【解决方案1】:

    问题在于,一般来说,Git 不知道 file_namefile 名称,还是 branch 名称,还是什么。解决方案是告诉它:在双破折号-- 之后,nothing 可以是选项或分支名称:

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

    同样的规则适用于像git checkout 这样的命令。如果您有一个名为master 的文件并且想要查看它怎么办?命令:

    git checkout master
    

    行不通,但是命令:

    git checkout -- master
    

    ,因为两个破折号告诉git checkout,这是选项和分支名称的结尾等等:其他所有内容必须是文件名。

    【讨论】:

      【解决方案2】:
      git reset --hard origin/master      # reset index, worktree and ref
      git reset --soft @{1}               # put the ref back
      

      就是你所需要的。

      【讨论】:

      • 好东西。有时修复错误的最佳方法不是编写代码,嗯?
      猜你喜欢
      • 2013-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 1970-01-01
      • 2011-04-11
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多