Can I use git diff on untracked files?

前端 未结 10 1065
你的背包
你的背包 2020-11-27 09:58

Is it possible to ask git diff to include untracked files in its diff output, or is my best bet to use git add on the newly created files and the e

10条回答
  •  执笔经年
    2020-11-27 10:33

    With recent git versions you can git add -N the file (or --intent-to-add), which adds a zero-length blob to the index at that location. The upshot is that your "untracked" file now becomes a modification to add all the content to this zero-length file, and that shows up in the "git diff" output.

    git diff
    
    echo "this is a new file" > new.txt
    git diff
    
    git add -N new.txt
    git diff
    diff --git a/new.txt b/new.txt
    index e69de29..3b2aed8 100644
    --- a/new.txt
    +++ b/new.txt
    @@ -0,0 +1 @@
    +this is a new file
    

    Sadly, as pointed out, you can't git stash while you have an --intent-to-add file pending like this. Although if you need to stash, you just add the new files and then stash them. Or you can use the emulation workaround:

    git update-index --add --cacheinfo \
    100644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 new.txt
    

    (setting up an alias is your friend here).

提交回复
热议问题