开发者

Can git commit "empty versions" of new, non-empty files?

Can git commit empty versions of some files? The case in point is that I need new (untracked), non-empty files to first be added and committed as empty files, so as to mark their contents as being new and to be reviewed (the full, untracked file should not be added to the index; git diff should show the newly added contents by comparing the file to its committed empty version).

There is git add -N file…, which puts file with an empty content in the index, but this only says that file will be added, and git commit complains that the file has not been added. The thing is that the current, non-empty version is not what has to be added, but only an empt开发者_开发知识库y version of the new file.

Is there a way to do this?

PS: This question is asked in the context of a program that automatically adds files to a git repository (my program follows what code students write). Uncommitted code is code that I have yet to approve. Thus, the state in which a program created by a student starts should be the empty state, even though my program just found a new, non-empty program in their home directory; this is handled by automatically committing a new, empty version of any new student program file in a git repository. Thus, new code lines that they write appear as being newly added contents, compared to the last committed git revision.


To be honest, I do not really understand what this is useful for. I would try to fix the review process instead of messing up the history. But if you really want to do this, here are several ways how:

  1. The pragmatic approach:

    mv file out-of-way
    touch file
    git add file
    mv out-of-way file
    
  2. The porcelain approach:

    git add -N file
    git add -p file
    

    ... and just answer "no" when asked whether the single hunk should be added. (Apparently this does not work anymore in 2019.)

  3. The plumbing approach:

    First, make sure an empty object exists in the object database:

    git hash-object -w --stdin < /dev/null
    

    This will return the SHA1 of an empty blob (which is e69de29bb2d1d6434b8b29ae775ad8c2e48c5391). You have to create this object only once. Now you can create empty files in the index by

    git update-index --add --cacheinfo 0644 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 file
    


Automatically add all empty files and folders


Force add all files

$ git add -Af

You can automatically add a .gitignore file in every empty folder.

$ find $PATH_TO_REPOSITORY -type d ! -path "*.git*" -empty -exec cp .gitignore '{}'/ \;

You can automatically add a .gitkeep file in every empty folder.

$ find $PATH_TO_REPOSITORY -type d ! -path "*.git*" -empty -exec touch '{}'/.gitkeep \;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜