What does git add --intent-to-add or -N do and when should it be used?

后端 未结 4 1107
再見小時候
再見小時候 2021-01-01 10:58

On git add -h I can see the following option:

-N, --intent-to-add   record only the fact that the path will be added later

But

4条回答
  •  迷失自我
    2021-01-01 11:21

    Enable diffing of untracked files

    Blue112's answer is partially correct. git add --intent-to-add does indeed add an empty file to the staging area/index for each specified untracked file in your working copy, but one of the main purposes of this is to enable you to use git diff with files that haven't been added to the Git repository yet by diffing your untracked file against its empty version in the staging area:

    $ echo foo > foo.txt
    $ git diff foo.txt
    
    $ git add --intent-to-add foo.txt
    $ git status
    On branch master
    Your branch is up-to-date with 'origin/master'.
    
    Changes to be committed:
      (use "git reset HEAD ..." to unstage)
    
            new file:   foo.txt
    
    Changes not staged for commit:
      (use "git add ..." to update what will be committed)
      (use "git checkout -- ..." to discard changes in working directory)
    
            modified:   foo.txt
    
    $ git diff --staged foo.txt
    diff --git a/foo.txt b/foo.txt
    new file mode 100644
    index 0000000..e69de29
    
    $ git diff foo.txt
    diff --git a/foo.txt b/foo.txt
    index e69de29..257cc56 100644
    --- a/foo.txt
    +++ b/foo.txt
    @@ -0,0 +1 @@
    +foo
    

    Once you've diffed the file, you can add the non-empty version to the staging area/index by simply doing a normal git add:

    $ git add foo.txt
    

    Enable git commit -a of untracked files

    Likewise, since --intent-to-add makes untracked files "known" to Git by adding empty versions of those files to the staging area/index, it also allows you to use git commit --all or git commit -a to commit those files along with your known modified files, which is something that you wouldn't be able to do otherwise.

    As explained in the official Linux Kernel documentation for git commit:

    using the -a [or --all] switch with the commit command [will] automatically "add" changes from all known files (i.e. all files that are already listed in the index)...and then perform the actual commit

    Documentation

    From the official Linux Kernel git add documentation:

    -N
    --intent-to-add
    

    Record only the fact that the path will be added later. An entry for the path is placed in the index with no content. This is useful for, among other things, showing the unstaged content of such files with git diff and committing them with git commit -a.

提交回复
热议问题