May 6, 2013

偵測目錄變動並自動執行指令

最近比較少用 IDE 後,coding 少了些自動化的回饋機制總覺得缺了點什麼,手動執行不知不覺也浪費了許多時間

想了想, 有些重複流程是可以用程式自動化的, 只要有程式來偵測目錄變動並自動執行程式就夠了,在 linux 裡確沒找到相關的工具(inotify-tools), 於是用 Go 做了一個命令列工具 watchf ,能彈性組合命令, 也可以在多個作業系統上使用

Usage

Usage:
  watchf [options]
Options:
  -V=false: Show debugging messages
  -c=[]: Add arbitrary command (repeatable)
  -e=[all]: Listen for specific event(s) (comma separated list)
  -f=".watchf.conf": Specifies a configuration file
  -i=0: The interval limit the frequency of the command executions, if equal to 0, there is no limit (time unit: ns/us/ms/s/m/h)
  -p=".*": File name matches regular expression pattern (perl-style)
  -r=false: Watch directories recursively
  -s=false: Stop the watchf Daemon (windows is not support)
  -v=false: Show version and exit
  -w=false: Write command-line arguments to configuration file (write and exit)
Events:
     all  Create/Delete/Modify/Rename
  create  File/directory created in watched directory
  delete  File/directory deleted from watched directory
  modify  File was modified or Metadata changed
  rename  File moved out of watched directory
Variables:
  %f: The filename of changed file
  %t: The event type of file changes

Example 1

程式碼存檔時從另一個 terminal 看到程式碼錯誤分析、compiler 編譯訊息跟測試結果

以Go為例:

watchf -e "modify,delete" -c "go vet" -c "go test" -c "go install" -p "\.go$"

以Java為例:

watchf -r -i 5s -e "modify,delete" -c "mvn test" -p "\.java$"

Example 2

放置一個背景程式&偵測當前目錄與子目錄的檔案變動, 接著自動同步檔案到另一個目錄(或著遠端目錄)

watchf -r -c "rsync -aq $SRC $DST" &

停掉背景程式, 只要在同個執行目錄裡下watchf -s命令

Example 3

將常用參數寫入設定檔,之後只要在同個執行目錄裡下watchf命令不用給定參數

watchf -e "modify,delete" -c "go vet" -c "go test" -c "go install" -p "\.go$" -w