假设我有一个像这样的目录结构:
app/
uploads/
.gitkeep
images/
.gitkeep
videos/
.gitkeep
docs/
.gitkeep
我想保留目录结构,但不包含其中的文件(显然除了
.gitkeep
)。文档说:
斜杠后跟两个连续的星号,然后斜杠匹配零个或多个目录。例如,“a/**/b”匹配“a/b”、“a/x/b”、“a/x/y/b”等。
所以,我希望这能解决问题:
/app/uploads/**
!/app/uploads/**/.gitkeep
但这不起作用。没有添加任何子目录。
我使用的结构如下:
app/
.gitignore
uploads/
images/
.gitkeep
videos/
.gitkeep
docs/
.gitkeep
我的 app/.gitignore 文件的内容:
uploads/** # Ignore everything in 'uploads' folder
!uploads/**/ # exclude subdirectories
!.gitkeep # and .gitkeep files.
不要排除
.gitkeep
,只需将其添加到存储库中您想要保留的目录中即可。
您必须使用
.gitkeep
标志将 -f
文件添加到存储库,以强制它覆盖该文件的 .gitignore
。
git add -f uploads/.gitkeep
感谢 @RyPeck 的建议,我开始走 bash 脚本的道路。最终,它最终被最好地用作一个简单的 git hook。
运行
git commit
,以下脚本将在提交消息出现之前执行。这使我能够 (A) 确保这些上传目录中的文件从 git 缓存中删除(“取消添加”),以及 (B) 在每个目录中添加/触摸 .gitkeep 文件以维护目录结构。
.git/hooks/pre-commit
#!/bin/sh
# pre-commit
################################################################################
# This is a site-specific hook to deal with locally-generated files that don't
# belong in the repo while maintaining the directory structure. The dir
# './images' is primarily managed via the CMS. This little ditty will
# remove cached files within the './images' directories (recursively)
# and adds a '.gitkeep' file to each folder (to maintain dir structure in repo).
################################################################################
keep=images
cd `pwd`
for cached in `find $keep -type d`
do
if [ -d $cached ]
then
touch $cached/.gitkeep
git rm -r --cached --quiet --ignore-unmatch $cached
git add -f $cached/.gitkeep # Force add with -f to deal with .gitignore conflicts
chmod 600 $cached/.gitkeep
fi
done
echo "Removed locally-generated files in '$keep'"
exit 0
或者,在您的
.gitignore
目录中有一个 uploads
,其中包含内容
* # ignore everything here below
!*/ # except don't ignore directories
!.git* # and don't ignore files beginning .git
然后照常做。