.editorconfigが便利すぎて失禁した
こんにちは。@mon_satです。
開発していてたまに困るのは、プロジェクトによってコーディングルールがばらばらで「インデントがタブ文字か半角空白か」などいろいろ統一されていないことです。
最近はIntelliJ IDEAで作業することが増えてきました。 エディタ側で自動的に設定しているコードスタイルにしてくれるのは大変ありがたいのですが、少し設定が面倒ともいえます。
また、プロジェクトメンバー間で別々のエディタを使っていても同じコーディング規約を適用したいものです。
CakePHP3.0のリポジトリを見ていて気づいたのが .editorconfig というファイルの存在で、検索して見つけたのは下記のWebサイト。
サイトのTOPページに載っているサンプルの .editorconfig の中身は以下のとおり。
これを見ているだけでもワクワクしてきませんか!?
# EditorConfig is awesome: http://EditorConfig.org # top-most EditorConfig file root = true # Unix-style newlines with a newline ending every file [*] end_of_line = lf insert_final_newline = true # 4 space indentation [*.py] indent_style = space indent_size = 4 # Tab indentation (no size specified) [*.js] indent_style = tab # Indentation override for all JS under lib directory [lib/**.js] indent_style = space indent_size = 2 # Matches the exact files package.json and .travis.yml [{package.json,.travis.yml}] indent_style = space indent_size = 2
IntelliJ IDEA での使用方法
上述のサイトに対応しているエディタが一覧されています。
VimやEmacsやSublimeTextをはじめ、JetBrains系のエディタでももちろん使用可能です。
Pluginをダウンロード
まずEditorConfig Pluginをダウンロードしインストールします。
.editorconfig ファイルを記述
プロジェクトのrootフォルダ等に .editorconfig を作成し、そこにコーディングスタイルを記述しましょう。
おもなものは以下のとおりです。
root
これは、プロジェクトのルートディレクトリの .editorconfig を示す記述方法です。
root = true
EditorConfig Pluginは、なんらかのファイルをひらいたとき、同じフォルダおよび上位階層にある .editorconfig を探します。
その際 .editorconfig 内に以下の記述があると、それ以上上位のフォルダを検索しません。
indent_style, indent_size, tab_width
インデントの方式を指定します。
以下は半角空白2つの例です。
indent_style = space indent_size = 2
indent_style は、 "tab" or "space" が指定可能です。
tabの場合は以下のように指定します。 tab_widthの初期値はindent_sizeの値とのことで省略可能のようです。
indent_style = tab tab_width = 4
end_of_line, charset, insert_final_newline, trim_trailing_whitespace
改行コード("lf" or "cr" or "crlf")、文字コード、ファイル末尾の空行の有無、行末の空白の削除
[*] end_of_line = lf charset = utf-8 insert_final_newline = true trim_trailing_whitespace = true
その他
ファイルの種類により別にする場合は下記のようになります。
[*] indent_style = space indent_size = 4 [*.html] indent_style = tab
というわけでリポジトリには .editorconfig を含めよう!
たとえばCakePHPのプロジェクトのリポジトリのルートは、以下のような感じが良さそうですね
files | 内容 |
---|---|
.git | .gitフォルダ |
.gitignore | バージョン管理対象外のファイルの設定 |
.editorconfig | エディタの設定 |
app | アプリケーションのディレクトリ |
lib | CakePHPのコアファイル等 |
Plugin | CakePHPのプラグイン |
vendor | サードパーティ製のライブラリ等 |
vagrant | vagrantで使用するファイル郡 |
composer.json | composerの設定 |
README.md | アプリケーションの説明等 |
お詫び
いきおいでタイトルに「便利すぎて失禁した」とつけてしまいましたが、正確には失禁までにはいたりませんでした。
心よりお詫び申し上げます。