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


当前回答

您可以! 查看 Git FAQ。

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

其他回答

我也面临着空的目录的问题. 使用存储文件的问题是,你需要创建它们,并删除它们,如果它们不再需要(因为后来添加了子目录或文件。

这就是为什么我决定写一个开源工具,可以自动管理创建/删除此类存储文件。 它是为.NET 平台写的,并在 Mono (.NET for Linux) 和 Windows 中运行。

只需看看: http://code.google.com/p/markemptydirs

PowerShell 版本:

在目录中找到所有空的文件夹 添加一个空的.gitkeep 文件在那里

Get-ChildItem 'Path to your Folder' -Recurse -Directory | Where-Object {[System.IO.Directory]::GetFileSystemEntries($_.FullName).Count -eq 0} | ForEach-Object { New-Item ($_.FullName + "\.gitkeep") -ItemType file}

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

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

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