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


当前回答

将.gitkeep 文件添加到空的目录中,并承诺。

touch .gitkeep

这是Git跟随的标准。

其他回答

我正在寻找这个问题,因为:我创建一个新的目录,它包含许多文件。在这些文件中,一些我想添加到Git存储库,有些不。

Untracked files:
  (use "git add <file>..." to include in what will be committed)
    ../trine/device_android/

它不在这个新目录中列出单独的文件,然后我认为也许我只能添加这个目录,然后处理单独的文件,所以我谷歌“只添加目录”。

在我的情况下,我发现我只能在新目录中添加一个文件,我确信我想将其添加到Git。

git add new_folder/some_file

此后,“Git状态”将显示单独文件的状态。

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

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

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

您可以! 查看 Git FAQ。

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

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

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

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

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

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

*
!.gitignore

输入: 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承诺是令人惊讶的困难。