How can I add an empty directory to a Git repository?

后端 未结 30 2673
离开以前
离开以前 2020-11-21 04:52

How can I add an empty directory (that contains no files) to a Git repository?

30条回答
  •  猫巷女王i
    2020-11-21 05:18

    WARNING: This tweak is not truly working as it turns out. Sorry for the inconvenience.

    Original post below:

    I found a solution while playing with Git internals!

    1. Suppose you are in your repository.
    2. Create your empty directory:

      $ mkdir path/to/empty-folder
      
    3. Add it to the index using a plumbing command and the empty tree SHA-1:

      $ git update-index --index-info
      040000 tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904    path/to/empty-folder
      

      Type the command and then enter the second line. Press Enter and then Ctrl + D to terminate your input. Note: the format is mode [SPACE] type [SPACE] SHA-1hash [TAB] path (the tab is important, the answer formatting does not preserve it).

    4. That's it! Your empty folder is in your index. All you have to do is commit.

    This solution is short and apparently works fine (see the EDIT!), but it is not that easy to remember...

    The empty tree SHA-1 can be found by creating a new empty Git repository, cd into it and issue git write-tree, which outputs the empty tree SHA-1.

    EDIT:

    I've been using this solution since I found it. It appears to work exactly the same way as creating a submodule, except that no module is defined anywhere. This leads to errors when issuing git submodule init|update. The problem is that git update-index rewrites the 040000 tree part into 160000 commit.

    Moreover, any file placed under that path won't ever be noticed by Git, as it thinks they belong to some other repository. This is nasty as it can easily be overlooked!

    However, if you don't already (and won't) use any Git submodules in your repository, and the "empty" folder will remain empty or if you want Git to know of its existence and ignore its content, you can go with this tweak. Going the usual way with submodules takes more steps that this tweak.

提交回复
热议问题