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


当前回答

假设你需要一个空的目录,称为tmp:

$ mkdir tmp
$ touch tmp/.gitignore
$ git add tmp
$ echo '*' > tmp/.gitignore
$ git commit -m 'Empty directory' tmp

换句话说,你需要将.gitignore 文件添加到指数之前,你可以告诉 Git 忽略它(以及所有其他在空的目录中)。

其他回答

Jamie Flournoy的解决方案工作得很好. 这里有一个稍微改进的版本,以保持.htaccess :

# Ignore everything in this directory
*
# Except this file
!.gitignore
!.htaccess

使用此解决方案,您可以插入一个空的文件夹,例如 /log、 /tmp 或 /cache 并且文件夹将保持空白。

我喜欢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.

也许添加一个空的目录似乎会是最少的抵抗的道路,因为你有脚本,希望该目录存在(也许是因为它是生成的二进制的目标)。

mkdir --parents .generated/bin ## create a folder for storing generated binaries
mv myprogram1 myprogram2 .generated/bin ## populate the directory as needed

在此例子中,您可以查看(破)标志性链接到目录,以便您可以访问它,而无需“创建”预定义(但这是可选的)。

ln -sf .generated/bin bin
git add bin

如果你想清理你的源树,你可以:

rm -rf .generated ## this should be in a "clean" script or in a makefile

如果您采取常见的检查方法,在一个几乎空的文件夹中,您有更少的复杂性,删除内容,而不删除“Gitignore”文件。

您可以忽略所有创建的文件,并将以下内容添加到您的 root.gitignore:

.generated

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

当您添加一个.gitignore 文件时,如果您将放置任何内容(您希望 Git 忽略),您可能希望添加一个单一行,只需一个星级 * 以确保您不会随机添加被忽略的内容。