![](/img/trans.png)
[英]How can I add and track files in git without tracking the directories they are in?
[英]How to track directories but not their files with Git?
我最近开始使用 Git,但只有一件事遇到了麻烦。 如何在不跟踪目录内容的情况下跟踪目录?
例如,我正在处理的网站允许上传。 我想跟踪上传目录,以便在分支等时创建它,但显然不是其中的文件(开发分支中的测试文件或主文件中的真实文件)。
在 my.gitignore 我有以下内容:
uploads/*.*
也试过(忽略整个目录):
uploads/
该目录还可能包含子目录(uploads/thumbs/uploads/videos/)我希望能够跟踪这些但不是他们的文件。
Git 可以吗? 我到处搜索都没有找到答案。
Git不跟踪目录,它跟踪文件,因此要实现这一点,您需要跟踪至少一个文件。 所以假设您的.gitignore
文件看起来像这样:
upload/*
你可以这样做:
$ touch upload/.placeholder
$ git add -f upload/.placeholder
如果你忘了-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
我在这里写到了这个。
在目录中添加.gitignore。
我发现最好的答案是在您的上传文件夹中包含一个带有此内容的.gitignore文件
# Ignore everything in this directory
*
# Except this file
!.gitignore
您在这里如何将空目录添加到Git存储库?
迄今为止最好的解决方案:
1)创建.gitignore文件
2)写在里面:
*
*/
!.gitignore
3)将.gitignore文件添加到所需的文件夹中。
为了仅跟踪目录而不跟踪文件,我做了以下操作。 感谢@ PeterFarmer对git仅跟踪文件的评论,我已经能够保留所有目录,不包括文件,如下所述。
# exclude everything in every folder
/data/**/*.*
# include only .gitkeep files
!/data/**/*.gitkeep
将其添加到.gitignore文件将完成工作。 以下是我的文件夹结构。
data/
├── processed
│ ├── dataset1.csv
│ └── dataset2.csv
├── raw
│ ├── raw_dataset1.json
└── test
├── subfolder
│ └── dataset2.csv
└── reviews.csv
当我做git add . && git status
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
请记住.gitignore文件的以下内容:
前缀斜杠仅查找根目录。
/ DIR
双星号查找零个或多个目录。
/ ** /
(在您的示例中, directory
是uploads
。)
在根目录的.gitignore
文件中,放入:
directory/*
!*.gitkeep
然后在directory
中保存一个空的.gitkeep
文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.