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


当前回答

Jamie Flournoy的解决方案工作得很好. 这里有一个稍微改进的版本,以保持.htaccess :

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

使用此解决方案,您可以插入一个空的文件夹,例如 /log、 /tmp 或 /cache 并且文件夹将保持空白。

其他回答

您可以通过 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

也许添加一个空的目录似乎会是最少的抵抗的道路,因为你有脚本,希望该目录存在(也许是因为它是生成的二进制的目标)。

mkdir --parents .generated/bin ## create a folder for storing generated binaries
mv myprogram1 myprogram2 .generated/bin ## populate the directory as needed

在此例子中,您可以查看(破)标志性链接到目录,以便您可以访问它,而无需“创建”预定义(但这是可选的)。

ln -sf .generated/bin bin
git add bin

如果你想清理你的源树,你可以:

rm -rf .generated ## this should be in a "clean" script or in a makefile

如果您采取常见的检查方法,在一个几乎空的文件夹中,您有更少的复杂性,删除内容,而不删除“Gitignore”文件。

您可以忽略所有创建的文件,并将以下内容添加到您的 root.gitignore:

.generated

安迪·莱斯特是对的,但如果你的目录只需要是空的,而不是空的,你可以把一个空的.gitignore 文件在那里作为一个工作室。

另一方面,这是一个实施问题,而不是一个基本的Git存储设计问题,正如在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

Jamie Flournoy的解决方案工作得很好. 这里有一个稍微改进的版本,以保持.htaccess :

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

使用此解决方案,您可以插入一个空的文件夹,例如 /log、 /tmp 或 /cache 并且文件夹将保持空白。