2014-02-27 61 views
3

假設我有一個目錄結構如下所示:我該如何在目錄結構中使用gitignore文件,但維護目錄結構?

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 

這不但是工作。沒有任何子目錄被添加。

回答

1

感謝@RyPeck的建議,我開始了bash腳本的路徑。最終,它最終被用作一個簡單的git鉤子。

運行git commit,在提交消息出現之前將執行以下腳本。這使我能夠(A)確保這些上傳目錄中的文件從git緩存中刪除(「un-add」)和(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 
3

不排除.gitkeep,只需將其添加到要保留的目錄中的存儲庫即可。

您必須將.gitkeep文件添加到存儲庫,並使用-f標誌強制它覆蓋該文件的.gitignore

git add -f uploads/.gitkeep 
+0

在我正在掙扎的實際使用情況, 'uploads'中有很多子目錄可以通過CMS進行管理。所以,如果我理解,你說我每次創建一個新的子目錄時都需要'git keep'。這裏沒有「通配符」解決方案嗎? – Jbird

+1

是的,您需要爲每個想要保留的子目錄添加一個'.gitkeep'文件。你可以做的唯一通配符是默認情況下忽略所有這些子目錄,除了你專門用'git add -f'添加的文件。你可以編寫一個bash腳本來爲你運行git add命令。 – RyPeck

+0

以及在每個文件上運行'touch'命令。這超出了你原來的問題範圍。 – RyPeck

-1

或者,在你的uploads目錄.gitignore與內容

*  # ignore everything here below 
!*/  # except don't ignore directories 
!.git* # and don't ignore files beginning .git 

,然後做如常。

+0

感謝您的建議@jthill。我有點厭倦散佈在子目錄中的.gitignore文件。我知道其他人對這種方法很滿意,但我寧願保持一個.gitignore。另外,我最終使用的鉤子還會在提交期間輸出有用的行「在$ keep'中刪除本地生成的文件」,這對提示這些目錄級項目需求很有幫助。 – Jbird

9

我正在使用的結構是這樣的:我的應用程序/ .gitignore文件以的

app/ 
    .gitignore 
    uploads/ 
    images/ 
     .gitkeep 
    videos/ 
     .gitkeep 
    docs/ 
     .gitkeep 

內容:

uploads/** # Ignore everything in 'uploads' folder 
!uploads/**/ # exclude subdirectories 
!.gitkeep  # and .gitkeep files. 
+0

那些來自.gitignore的最後3行很棘手。謝謝! – the0ther