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

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

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

30条回答
  •  滥情空心
    2020-11-21 05:06

    Git does not track empty directories. See the Git FAQ for more explanation. The suggested workaround is to put a .gitignore file in the empty directory. I do not like that solution, because the .gitignore is "hidden" by Unix convention. Also there is no explanation why the directories are empty.

    I suggest to put a README file in the empty directory explaining why the directory is empty and why it needs to be tracked in Git. With the README file in place, as far as Git is concerned, the directory is no longer empty.

    The real question is why do you need the empty directory in git? Usually you have some sort of build script that can create the empty directory before compiling/running. If not then make one. That is a far better solution than putting empty directories in git.

    So you have some reason why you need an empty directory in git. Put that reason in the README file. That way other developers (and future you) know why the empty directory needs to be there. You will also know that you can remove the empty directory when the problem requiring the empty directory has been solved.


    To list every empty directory use the following command:

    find -name .git -prune -o -type d -empty -print
    

    To create placeholder READMEs in every empty directory:

    find -name .git -prune -o -type d -empty -exec sh -c \
      "echo this directory needs to be empty because reasons > {}/README.emptydir" \;
    

    To ignore everything in the directory except the README file put the following lines in your .gitignore:

    path/to/emptydir/*
    !path/to/emptydir/README.emptydir
    path/to/otheremptydir/*
    !path/to/otheremptydir/README.emptydir
    

    Alternatively, you could just exclude every README file from being ignored:

    path/to/emptydir/*
    path/to/otheremptydir/*
    !README.emptydir
    

    To list every README after they are already created:

    find -name README.emptydir
    

提交回复
热议问题