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


当前回答

要将 Jamie Flournoy 的解决方案扩展到一个目录树上,您可以将此.gitignore 文件放在顶级目录中,并在 Git 应该跟踪的每个子目录中点击.keepdir。

# Ignore files but not directories. * matches both files and directories
# but */ matches only directories. Both match at every directory level
# at or below this one.
*
!*/

# Git doesn't track empty directories, so track .keepdir files, which also
# tracks the containing directory.
!.keepdir

# Keep this file and the explanation of how this works
!.gitignore
!Readme.md

其他回答

在目录中创建一个名为.gitkeep 的空白文件,然后将其添加到 git。

这将是一个隐藏的文件在Unix类似系统的默认情况下,但它将迫使Git承认该目录的存在,因为它现在有内容。

此外,请注意,关于此文件的名称没有什么特别的。 你可能已经命名了它你想要的任何东西. 所有 Git 关心的是,文件夹里有什么东西。

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

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

您可以! 查看 Git FAQ。

目前,Git指数的设计仅允许文件列出,并且没有人有足够的能力进行更改,以便空的目录对这种情况有足够的关注,以便解决它。

将.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.