我如何将一个空的目录(不包含文件)添加到一个Git存储库中?


当前回答

有时我有文件夹的存储库,这些文件只会永远包含被认为是“内容”的文件 - 也就是说,它们不是我关心被版本的文件,因此不应该被承诺。 使用 Git 的.gitignore 文件,你可以忽略整个目录。

我过去所做的是把一个.gitignore 文件放在我的 repo 的根上,然后排除文件夹,如下:

/app/some-folder-to-exclude
/another-folder-to-exclude/*

但是,这些文件夹然后不会成为 repo的一部分. 你可以添加一些东西,如一个 README 文件在那里. 但然后你必须告诉你的应用程序不要担心处理任何 README 文件。

如果您的应用程序依赖于文件夹存在(尤其是空白),您可以简单地将.gitignore 文件添加到该文件夹中,并使用它来实现两个目标:

*
!.gitignore

其他回答

The Ruby on Rails 登录文件夹创建方式:

mkdir log && touch log/.gitkeep && git add log/.gitkeep

现在日志目录将被列入树上,在部署时非常有用,所以你不需要写一个日常来创建日志目录。

登记文件可以通过发行,

echo log/dev.log >> .gitignore

但你可能知道这一点。

我总是建立一个功能来检查我想要的文件夹结构,并在项目中为我构建它。

function check_page_custom_folder_structure () {
    if (!is_dir(TEMPLATEPATH."/page-customs"))
        mkdir(TEMPLATEPATH."/page-customs");    
    if (!is_dir(TEMPLATEPATH."/page-customs/css"))
        mkdir(TEMPLATEPATH."/page-customs/css");
    if (!is_dir(TEMPLATEPATH."/page-customs/js"))
        mkdir(TEMPLATEPATH."/page-customs/js");
}

这是在PHP,但我确信大多数语言支持相同的功能,因为文件夹的创建是由应用程序照顾的,文件夹将永远在那里。

将.gitkeep 文件添加到空的目录中,并承诺。

touch .gitkeep

这是Git跟随的标准。

我喜欢Artur79和mjs的答案,所以我已经使用了两者的组合,并为我们的项目创造了标准。

find . -type d -empty -exec touch {}/.gitkeep \;

但是,只有少数我们的开发人员在Mac或Linux上工作,很多工作在Windows上,我找不到一个相当的简单的单线来完成相同的。

因此,由于我们大多数开发人员已经安装了Ant,我想到的第一件事是将一个Ant构建文件组合起来,以便独立于平台完成这一点。

pip3 install gitkeep2

它将允许你创建和删除.gitkeep 文件重复,它也将允许你添加消息给他们,让你的同事了解为什么这些目录是重要的。

$ gitkeep --help
Usage: gitkeep [OPTIONS] PATH

  Add a .gitkeep file to a directory in order to push them into a Git repo
  even if they're empty.

  Read more about why this is necessary at: https://git.wiki.kernel.org/inde
  x.php/Git_FAQ#Can_I_add_empty_directories.3F

Options:
  -r, --recursive     Add or remove the .gitkeep files recursively for all
                      sub-directories in the specified path.
  -l, --let-go        Remove the .gitkeep files from the specified path.
  -e, --empty         Create empty .gitkeep files. This will ignore any
                      message provided
  -m, --message TEXT  A message to be included in the .gitkeep file, ideally
                      used to explain why it's important to push the specified
                      directory to source control even if it's empty.
  -v, --verbose       Print out everything.
  --help              Show this message and exit.

您可以随时将 README 文件放入目录中,并解释为什么您想要此,否则空白,目录在存储库中。