如何将空目录添加到Git存储库?

时间:2020-03-06 14:33:00  来源:igfitidea点击:

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

解决方案

你不能请参阅Git常见问题解答。

Currently the design of the git index
  (staging area) only permits files to
  be listed, and nobody competent enough
  to make the change to allow empty
  directories has cared enough about
  this situation to remedy it.
  
  Directories are added automatically
  when adding files inside them. That
  is, directories never have to be added
  to the repository, and are not tracked
  on their own.
  
  You can say "git add <dir>" and it
  will add files in there.
  
  If you really need a directory to
  exist in checkouts you should create a
  file in it. .gitignore works well for
  this purpose; you can leave it empty,
  or fill in the names of files you
  expect to show up in the directory.

安迪·莱斯特(Andy Lester)是正确的,但是如果目录只需要为空,而不是空目录,则可以在其中放置一个空的.gitignore文件作为解决方法。

顺便说一句,这是一个实现问题,而不是基本的Git存储设计问题。正如在Git邮件列表中多次提到的那样,未实施此操作的原因是,没有人愿意为此提交补丁,而不是无法或者不应该这样做。

你不能这是Git维护者的有意设计决定。基本上,像Git这样的源代码管理系统的目的是管理源代码,而空目录不是源代码。 Git通常也被描述为内容跟踪器,同样,空目录也不是内容(实际上恰恰相反),因此不会被跟踪。

当添加.gitignore文件时,如果要在其中添加任意数量的内容(希望让Git忽略),则可能需要添加仅带有星号*的一行,以确保我们没有不会意外添加被忽略的内容。

假设我们需要一个名为tmp的空目录:

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

换句话说,我们需要将.gitignore文件添加到索引中,然后才能告诉Git忽略它(以及空目录中的所有其他内容)。

使目录保持为空(在存储库中)的另一种方法是在该目录内创建一个包含以下四行的.gitignore文件:

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

这样,我们就不必像m104解决方案中那样正确地获得订单。

这也带来了好处,当我们执行git status时,该目录中的文件不会显示为" untracked"。

使@GreenAsJade的评论持续存在:

I think it's worth noting that this solution does precisely what the question asked for, but is not perhaps what many people looking at this question will have been looking for. This solution guarantees that the directory remains empty. It says "I truly never want files checked in here". As opposed to "I don't have any files to check in here, yet, but I need the directory here, files may be coming later".

我也一直面临着空目录的问题。使用占位符文件的问题是,如果不再需要它们,则需要创建它们并删除它们(因为稍后添加了子目录或者文件。使用大型源代码树来管理这些占位符文件可能很麻烦且会出错。易于。

这就是为什么我决定编写一个开源工具,该工具可以自动管理此类占位符文件的创建/删除。它是为.NET平台编写的,可在Mono(Linux的.NET)和Windows下运行。

看看:http://code.google.com/p/markemptydirs