Chef Cookbook のスタイルをチェックしてくれる Foodcritic を使ってみた

Foodcritic というのは「Chef の Cookbook のスタイルをチェックしてくれる Lint ツール」みたいなやつで、どんなものなのか気になったので少し触ってみた。

インストール

$ rvm use 1.9.3
$ gem install foodcritic
$ foodcritic # 正常にインストールされると foodcritic コマンドが使えるようになる

とりあえず使ってみる

「使ってみる」と言っても foodcritic [チェックしたい cookbook のパス] を実行するだけ。デフォルトではこのページに載っている 32 個のルールでチェックが行われる。試しに Opscode 公式の mysql cookbook をチェックしてみた。公式なのにけっこう指摘が出る…。

$ mkdir try-foodcritic
$ cd try-foodcritic
$ git clone git://github.com/opscode-cookbooks/mysql.git
$ ls
mysql
$ foodcritic mysql
FC002: Avoid string interpolation where not required: mysql/attributes/server.rb:70
FC007: Ensure recipe dependencies are reflected in cookbook metadata: mysql/recipes/client.rb:42
FC019: Access node attributes in a consistent manner: mysql/attributes/server.rb:105
FC023: Prefer conditional attributes: mysql/recipes/server.rb:142
FC024: Consider adding platform equivalents: mysql/recipes/server.rb:117
FC024: Consider adding platform equivalents: mysql/recipes/server.rb:119

他のルールを適用してみる

デフォルトのルールだけではなく自分でルールを作ったりもできるっぽい。ほんとは自分でルールを作ってみたかったんだけど、特にめぼしいものを思いつかなかったので、Etsy 社が公開しているルールを試してみた。"-I [ルールを記述した ruby ファイルへのパス]" を指定することができる。

$ git clone https://github.com/etsy/foodcritic-rules.git etsy-rules
$ ls
etsy-rules mysql
$ foodcritic -I etsy-rules/rules.rb mysql
ETSY005: Action :restart sent to a core service: mysql/recipes/server.rb:132
FC002: Avoid string interpolation where not required: mysql/attributes/server.rb:70
FC007: Ensure recipe dependencies are reflected in cookbook metadata: mysql/recipes/client.rb:42
FC019: Access node attributes in a consistent manner: mysql/attributes/server.rb:105
FC023: Prefer conditional attributes: mysql/recipes/server.rb:142
FC024: Consider adding platform equivalents: mysql/recipes/server.rb:117
FC024: Consider adding platform equivalents: mysql/recipes/server.rb:119

感想

Chef は自由すぎて、どう cookbook を書けばいいかよく分からなかったり、書く人によって結構スタイルがバラバラになってしまったりするので、こういう仕組みは有益だと思う。

あと、Travis CI や Jenkins 等の継続的インテグレーションツールに組み込んで使うのもおもしろそうに思った。なかなかオリジナルの cookbook とか公開できていないんだけど、公開するときには Travis + foodcritic とか試してみたい。