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


当前回答

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

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

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

其他回答

有时你需要处理错误的书面图书馆或软件,需要一个“真实”空白和现有目录。 设置一个简单的.gitignore 或.keep 可能会破坏它们,并导致一个错误。

首先,创建所需的目录:

mkdir empty

然后你将一个破碎的象征性链接添加到这个目录(但在任何其他情况下,除了上面描述的使用情况,请使用一个 README 与解释):

ln -s .this.directory empty/.keep

要忽略此目录中的文件,您可以将其添加到根.gitignore:

echo "/empty" >> .gitignore

要添加被忽略的文件,使用一个参数强制它:

git add -f empty/.keep

在承诺之后,你在你的指数中有一个破碎的象征性链接, git 创建了目录. 破碎的链接有某些好处,因为它不是正常的文件和没有正常的文件的点。

find empty -type f

$ php -r "var_export(glob('empty/.*'));"
array (
  0 => 'empty/.',
  1 => 'empty/..',
)

没有办法 Git 跟踪目录,所以唯一的解决方案是在您想要 Git 跟踪的目录中添加一个位置持有者文件。

文件可以被命名并包含你想要的任何东西,但大多数人使用一个空白的文件称为.gitkeep (尽管有些人更喜欢VCS诊断的.keep)。

预定. 标记它作为一个隐藏的文件。

另一个想法是添加一个 README 文件,解释该目录将用于什么。

如上所述,无法添加空的目录,但这里是一个单一的列,将空的.gitignore 文件添加到所有目录中。

ruby -e'require "fileutils" ; Dir.glob(["target_directory","target_directory/**"]).each {♰f♰ FileUtils.touch(File.join(f, ".gitignore")) 如果 File.directory?(f) }'

我把它放在一个Rakefile中,以便轻松地访问。

输入: https://gitlab.com/empty-repo/empty.git

一个 Git 存储库与正确的一个承诺:

commit e84d7b81f0033399e325b8037ed2b801a5c994e0
Author: Nobody <none>
Date: Thu Jan 1 00:00:00 1970 +0000

使用

要添加一个空的目录给你 GIT repo:

git submodule add https://gitlab.com/empty-repo/empty.git path/to/dir

将所有现有空白目录转换为子模块:

find . -type d -empty -delete -exec git submodule add -f https://gitlab.com/empty-repo/empty.git \{\} \;

Git 在创建子模块参考时将存储最新的 commit hash,所以你不必担心我(或GitLab)使用此注射恶意文件。 不幸的是,我没有找到任何方法来强制该 commit ID 在查询期间使用,所以你将不得不手动检查该参考 commit ID 是e84d7b81f0033399e325b8037ed2b801a5c994e0 使用 git 子模块状态添加后

附件:重新创建此承诺

您应该能够重新创建这个准确的承诺使用(在一个空的目录):

# Initialize new GIT repository
git init

# Set author data (don't set it as part of the `git commit` command or your default data will be stored as “commit author”)
git config --local user.name "Nobody"
git config --local user.email "none"

# Set both the commit and the author date to the start of the Unix epoch (this cannot be done using `git commit` directly)
export GIT_AUTHOR_DATE="Thu Jan 1 00:00:00 1970 +0000"
export GIT_COMMITTER_DATE="Thu Jan 1 00:00:00 1970 +0000"

# Add root commit
git commit --allow-empty --allow-empty-message --no-edit

创建可重复的Git承诺是令人惊讶的困难。

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