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


当前回答

这里是一个黑客,但有趣的是它工作(Git 2.2.1) 类似于 @Teka 提出的,但更容易记住:

添加一个子模块到任何存储库(git 子模块添加 path_to_repo) 这将添加一个文件夹和一个文件.submodules. 执行一个更改. 删除.submodules 文件并执行更改。

现在,你有一个目录,当承诺被检查时创建。 有趣的是,如果你看看这个文件的木材对象的内容,你会得到:

致命: 没有有效的对象名称 b64338b90b4209263b50244d18278c0999867193

我不会鼓励使用它,因为它可能会停止在未来的版本的Git,这可能会让您的存储库腐败。

其他回答

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

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

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

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

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

此分類上一篇

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

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

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

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

只需添加一个 readme 或.gitignore 文件,然后从 GitHub 网站删除它,但不是终端。