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


当前回答

这样做的一个简单的方式是通过添加一个.gitkeep 文件到您希望(目前)保持空白的目录。

查看此 SOF 答案以获取更多信息 - 这也解释了为什么一些人发现添加.gitignore 文件的竞争协议(如在许多答案中所述)令人困惑。

其他回答

添加另一个选项给女士。

假设你想添加一个目录到 git,这对于所有与 git 相关的目的,应该保持空白,从来没有跟踪其内容,一个.gitignore 如这里多次提议,会做这个技巧。

形式,如上所述,是:

*
!.gitignore

$ echo "*" > .gitignore && echo '!.gitignore' >> .gitignore && git add .gitignore

#!/bin/bash

dir=''

if [ "$1" != "" ]; then
    dir="$1/"
fi

echo "*" > $dir.gitignore && \
echo '!.gitignore' >> $dir.gitignore && \
git add $dir.gitignore

使用此,您可以从您想要添加的目录中运行它,或者将目录引用为第一个和唯一的参数:

$ ignore_dir ./some/directory

另一个选项(回复 @GreenAsJade的评论),如果你想跟踪一个空的文件夹,可能在未来包含跟踪的文件,但将是空的现在,你可以从.gitignore 文件中删除 *,并检查它。

!.gitignore

我建议在文件中保持一个行是,它给了.gitignore 目的。 否则,某些下行可能会认为要删除它. 如果你在线上放一个评论,这可能有帮助。

要将 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 文件在该目录内,其中包含以下四行:

# Ignore everything in this directory
*
# Except this file
!.gitignore

然后你不需要得到订单正确的方式,你必须在m104的解决方案。

此外,这还提供了该目录中的文件不会在您进行 git 状态时显示为“不受吸引”的好处。

让 @GreenAsJade的评论持久:

我认为值得注意的是,这个解决方案正是问题所提出的,但并不确定许多人正在寻找什么。这个解决方案保证目录仍然是空的. 它说“我真的从来不想要文件在这里检查”。 相反,“我没有任何文件在这里检查,但是,我需要目录在这里,文件可能会出现。

您可以! 查看 Git FAQ。

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

您可以通过 create_readme.php 保存此代码并从您的 Git 项目的根目录运行 PHP 代码。

php create_readme.php

它将添加 README 文件到所有是空的目录,因此这些目录将被添加到指数。

<?php
    $path = realpath('.');
    $objects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path),       RecursiveIteratorIterator::SELF_FIRST);
    foreach($objects as $name => $object){
        if ( is_dir($name) && ! is_empty_folder($name) ){
            echo "$name\n" ;
            exec("touch ".$name."/"."README");
        }
    }

    function is_empty_folder($folder) {
        $files = opendir($folder);
        while ($file = readdir($files)) {
            if ($file != '.' && $file != '..')
                return true; // Not empty
            }
        }
?>

然后做

git commit -m "message"
git push