How to stage only part of a new file with git?

前端 未结 5 1891
猫巷女王i
猫巷女王i 2020-12-02 03:33

I love git add --interactive. It is now part of my daily workflow.

The problem seems that it does not work with untracked files. What I wan

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 04:22

    git update-index --add --cacheinfo 100644 $(git hash-object -w /dev/null) newfile
    git add --interactive newfile
    

    Simple demo:

    mkdir /tmp/demo
    cd /tmp/demo
    git init .
    
    echo hello > newfile
    git update-index --add --cacheinfo 100644 $(git hash-object -w /dev/null) newfile
    
    • Hint If you're sure the 'empty' blob already exists in your git object database, you could hardcode the hash e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 instead. I don't recommend doing that_
    • Hint If you're on Windows, you probably can just use NUL: instead of /dev/null. Otherwise, use something like echo -n '' | git hash-object --stdin -w

    Now the index will contain newfile as the empty blob, and the empty blob has been entered into the object database if it didn't exist yet:

    $ find .git/objects/ -type f 
    .git/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391
    
    $ git status
    # On branch master
    #
    # Initial commit
    #
    # Changes to be committed:
    #   (use "git rm --cached ..." to unstage)
    #
    #   new file:   newfile
    #
    # Changed but not updated:
    #   (use "git add ..." to update what will be committed)
    #   (use "git checkout -- ..." to discard changes in working directory)
    #
    #   modified:   newfile
    #
    
    $ git diff
    diff --git a/newfile b/newfile
    index e69de29..ce01362 100644
    --- a/newfile
    +++ b/newfile
    @@ -0,0 +1 @@
    +hello
    

    This should be precisely what you want. May I also recommend the vim fugitive plugin for very intelligent index management (see Better git add -p?)

提交回复
热议问题