建立 git repository 時,要如何找出空目錄,以避免 build code 失敗?


在過去的經驗裡,使用 git 管理 project source code 最討厭遇到空目錄 (empty directory),偏偏我們在 build firmware image 時,常常會需要這樣的目錄,例如 root filesystem 的 /etc, /var, /dev 等等這些目錄。

假如 Makefile 沒有寫好的話,會假設這些目錄是存在的,但是因為 git 並不會儲存空的目錄,這會導致當我們將 project 從 git server clone 下來後,空目錄消失,然後 compile 就 fail 了。

多半這時候的解法就是透過 directory comparison 的工具,例如 Araxis Merge, Beyond Compare,或是 meld 等等,找出空目錄,touch 一個檔案,把檔案加入 git 管理,這樣就可以避免這樣的問題了。

過去我是這樣解決的:
在 project 目錄下,我會執行以下的指令:

find . -type d -empty -exec touch {}/.gitignore \;
view raw gistfile1.txt hosted with ❤ by GitHub


find 這個指令大家多少都用過,就不多做解釋
-type d 就是找出目錄,man page 說明如下:

-type True if the file is of the specified type. Possible file types are as follows:
b block special
c character special
d directory
f regular file
l symbolic link
p FIFO
s socket
view raw gistfile1.txt hosted with ❤ by GitHub


-empty 就是空檔案或是空目錄的,man page說明如下:

-empty True if the current file or directory is empty.
view raw gistfile1.txt hosted with ❤ by GitHub


-exec find 指令產生的 output,可以有幾種針對 output 做後續處理的方法,其中一種比較直覺的就是透過 exec,將 output 作為新指令的輸入,有點類似 pipeline ( | ) 的概念;exec 的參數必須以 " ; " 結尾,又因為在 shell 下,這個符號有其他用途,所以必須用反斜線標記 (\),然後 " { } " 是代表前面 find 指令的 output string。man page 說明如下:

-exec utility [argument ...] ;
True if the program named utility returns a zero value as its exit status. Optional arguments may be passed to the utility.
The expression must be terminated by a semicolon (``;''). If you invoke find from a shell you may need to quote the semicolon if
the shell would otherwise treat it as a control operator. If the string ``{}'' appears anywhere in the utility name or the arguments
it is replaced by the pathname of the current file. Utility will be executed from the directory from which find was executed. Utility
and arguments are not subject to the further expansion of shell patterns and constructs.
view raw gistfile1.txt hosted with ❤ by GitHub


最後, .gitignore 是 open source community 中,滿常被用來解決這問題的空檔案,而且同時又是 git 本身會 check 的特殊檔案,所以我都是拿這個檔案作為保留空目錄使用。

附註:在搜尋的過程中,也有人建議:如果在空目錄內新增一個 README 之類的檔案,藉以說明這個目錄是用來做什麼的,也是一個不錯的好選擇。





留言

這個網誌中的熱門文章

How to use ebtables: ebtable 的小筆記

如何在 Linux Kernel 下偵測網路的連線狀態?