如何使用 Git 跟踪目录而不跟踪文件?

我最近开始使用 Git,只有一个问题。如何跟踪目录而不跟踪其内容?

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

在我的. gitignore 我有以下:

uploads/*.*

Have also tried (which ignores the whole directory):

uploads/

这个目录也可能包含子目录(上传/拇指/上传/视频/)我希望能够跟踪这些,但不是他们的文件。

Git 可以做到这一点吗? 我到处都找过了,但是没有找到答案。

42453 次浏览

Git doesn't track directories, it tracks files, so to acheive this you need to track at least one file. So assuming your .gitignore file looks something like this:

upload/*

You can do this:

$ touch upload/.placeholder
$ git add -f upload/.placeholder

If you forget the -f you'll see:

$ 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

Then when you do git status you'll see:

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

Obviously you can then do:

$ touch upload/images/.placeholder
$ git add -f upload/images/.placeholder

I wrote about this here.

Add a .gitignore within the directory.

Best answerd I've found is to include a .gitignore file in your upload folder with this content

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

Here you have How can I add an empty directory to a Git repository?

The best solution so far:

1) Create a .gitignore file

2) Write inside:

*
*/
!.gitignore

3) Add the .gitignore file to the folder that you want.

Source: https://stackoverflow.com/a/5581995/2958543

In order to track only directories but not the files, I did the following. Thanks to the @PeterFarmer's comment on git tracking only files, I've been able to keep all directories excluding the files as described in below.

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


# include only .gitkeep files
!/data/**/*.gitkeep

Adding this to the .gitignore file will do the work. The following is my folder structure.

data/
├── processed
│   ├── dataset1.csv
│   └── dataset2.csv
├── raw
│   ├── raw_dataset1.json
└── test
├── subfolder
│   └── dataset2.csv
└── reviews.csv

When I do git add . && git status, git only recognizes folders, but not files.

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

Keep in mind that the following for your .gitignore files:

Prepending slash looks only for the root directory.

/dir

Double asterisk looks for zero or more directories.

/**/

(In your example, directory is uploads.)

In the root directory, in a .gitignore file, put:

directory/*
!*.gitkeep

Then save an empty .gitkeep file in directory.