我如何将一个空的目录(不包含文件)添加到一个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

其他回答

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

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

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

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

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

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

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

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

*
!.gitignore

只需在您想要跟踪的空白目录中添加一个空白(没有内容).gitignore 文件。

例如,如果你想跟踪一个空的目录, /项目/内容/帖子,然后创建一个新的空的文件, /项目/内容/帖子/.gitignore

注意:.gitkeep 不是官方 Git 的部分:

此分類上一篇

基本上,一个源代码管理系统的目的是管理源代码,空的目录不是源代码,Git也经常被描述为内容跟踪器,再次,空的目录不是内容(相反的,实际上),所以它们不被跟踪。

您可以! 查看 Git FAQ。

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