如何使用Git跟踪目录而不是他们的文件?

Ben*_*Ben 68 git directory gitignore

我最近开始使用Git,但我遇到了一件事.如何跟踪目录而不跟踪其内容?

例如,我正在处理的网站允许上传.我想跟踪uploads目录,以便在分支等时创建它,但显然不是其中的文件(在开发分支中测试文件或在master中的真实文件).

在我的.gitignore中我有以下内容:

uploads/*.*

还试过(忽略整个目录):

uploads/

此目录还可能包含子目录(uploads/thumbs/uploads/videos /)我希望能够跟踪这些目录而不是他们的文件.

这可能与Git有关吗?我在没有找到答案的情况下到处搜索.

Pet*_*mer 97

Git不跟踪目录,它跟踪文件,因此要实现这一点,您需要跟踪至少一个文件.所以假设你的.gitignore文件看起来像这样:

upload/*
Run Code Online (Sandbox Code Playgroud)

你可以这样做:

$ touch upload/.placeholder
$ git add -f upload/.placeholder
Run Code Online (Sandbox Code Playgroud)

如果你忘记了,-f你会看到:

$ git add upload/.placeholder
The following paths are ignored by one of your .gitignore files:
upload
Use -f if you really want to add them.
fatal: no files added

然后,当你这样做时,git status你会看到:

# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached ..." to unstage)
#
#   new file:   upload/.placeholder
#

显然你可以这样做:

$ touch upload/images/.placeholder
$ git add -f upload/images/.placeholder
Run Code Online (Sandbox Code Playgroud)

  • 占位符的常见约定是gitignore文件. (10认同)
  • @Jefromi确实,正如我对Abizern的评论,从未考虑过使用`.gitignore`文件作为占位符. (2认同)
  • *Git不跟踪目录,它跟踪文件*听起来很有趣当他们教你一切都是UNIX中的文件,即使目录是文件 (2认同)

Abi*_*ern 37

在这里写到了这个.

在目录中添加.gitignore.


Gon*_*Cao 18

我发现最好的答案是在您的上传文件夹中包含一个带有此内容的.gitignore文件

# Ignore everything in this directory
*
# Except this file
!.gitignore
Run Code Online (Sandbox Code Playgroud)

您在这里如何将空目录添加到Git存储库?

  • 它不适用于嵌套文件夹结构. (3认同)

mej*_*l57 12

迄今为止最好的解决方案:

1)创建.gitignore文件

2)写在里面:

*
*/
!.gitignore
Run Code Online (Sandbox Code Playgroud)

3)将.gitignore文件添加到所需的文件夹中.

资料来源:https://stackoverflow.com/a/5581995/2958543


met*_*urk 6

为了仅跟踪目录而不跟踪文件,我执行了以下操作。感谢@PeterFarmer 对 git 仅跟踪文件的评论,我已经能够保留所有目录,不包括如下所述的文件。

# exclude everything in every folder
/data/**/*.*

# include only .gitkeep files
!/data/**/*.gitkeep
Run Code Online (Sandbox Code Playgroud)

将此添加到 .gitignore 文件将完成这项工作。以下是我的文件夹结构。

data/
??? processed
?   ??? dataset1.csv
?   ??? dataset2.csv
??? raw
?   ??? raw_dataset1.json
??? test
    ??? subfolder
    ?   ??? dataset2.csv
    ??? reviews.csv
Run Code Online (Sandbox Code Playgroud)

当我这样做时git add . && git status,git 只识别文件夹,而不识别文件。

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   .gitignore
        new file:   data/processed/.gitkeep
        new file:   data/raw/.gitkeep
        new file:   data/test/.gitkeep
        new file:   data/test/subfolder/.gitkeep
Run Code Online (Sandbox Code Playgroud)

请记住,.gitignore 文件的以下内容:

前置斜杠仅查找根目录。

/目录

双星号查找零个或多个目录。

/**/