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


当前回答

这个解决方案为我工作了。

1. 将.gitignore 文件添加到您的空白目录中:

*
*/
!.gitignore

* 忽略文件夹中的所有文件 */ 忽略子指南!.gitignore 包含.gitignore 文件

然后删除您的缓存,步行您的文件,承诺并按下:

git rm -r --cached .
git add . // or git stage .
git commit -m ".gitignore fix"
git push

其他回答

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

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

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

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

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

*
!.gitignore

在目录中创建一个名为.gitkeep 的空白文件,然后将其添加到 git。

这将是一个隐藏的文件在Unix类似系统的默认情况下,但它将迫使Git承认该目录的存在,因为它现在有内容。

此外,请注意,关于此文件的名称没有什么特别的。 你可能已经命名了它你想要的任何东西. 所有 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

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

PowerShell 版本:

在目录中找到所有空的文件夹 添加一个空的.gitkeep 文件在那里

Get-ChildItem 'Path to your Folder' -Recurse -Directory | Where-Object {[System.IO.Directory]::GetFileSystemEntries($_.FullName).Count -eq 0} | ForEach-Object { New-Item ($_.FullName + "\.gitkeep") -ItemType file}