LoginSignup
12
14

More than 5 years have passed since last update.

Gitのコミット前にESLintする

Last updated at Posted at 2016-11-25

2019-03-04 追記

この記事は古いため、非推奨です。現代ではhuskyやlint-stagedを使うことをおすすめします。

はじめに

remoteにpush後、CIから通知が来てLintに引っかかっていることに気づくことってありますよね?:scream:
一応push前には実行するように気をつけてはいますが、忘れちゃうことも多々・・・:innocent:
CIで通知くるから問題なしって思うかもですが、「あいつ、またこんなコード書いてるぜw(プークスクス)」みたいになりたくないので
git hooksを利用して、git commit時にESLintが動くように設定しようと思います:smile:

Git Hooksとは

Git フック

Gitの操作時にスクリプトが動かせるやつです。
git init後、.git/hooksの下を確認すると、サンプルのスクリプトがあることが確認できます。

$ tree ./.git/hooks/
./.git/hooks/
|-- applypatch-msg.sample
|-- commit-msg.sample
|-- post-update.sample
|-- pre-applypatch.sample
|-- pre-commit.sample
|-- pre-push.sample
|-- pre-rebase.sample
|-- prepare-commit-msg.sample
`-- update.sample

今回はcommit時に動かしたいので、pre-commitを作成します。

vi .git/hooks/pre-commit
pre-commit
#!/bin/sh

cd $GIT_DIR/../ && gulp lint # プロジェクトルートに移動してlint実行

スクリプトに実行権限をつけます。

$ chmod a+x ./.git/hooks/pre-commit

動かす

実際に動作させてみます。
例えば、下記のようなプログラムを作成します。

app.js
console.log('Hello')

で、commitしてみると・・・

$ git commit -m 'check'
[16:51:25] Using gulpfile ~/tmp/eslint/gulpfile.js
[16:51:25] Starting 'lint'...
[16:51:26] 
/Users/kohatan/tmp/eslint/app.js
  1:13  error  Strings must use doublequote  quotes
  1:21  error  Missing semicolon             semi

✖ 2 problems (2 errors, 0 warnings)

[16:51:26] 'lint' errored after 599 ms
[16:51:26] ESLintError in plugin 'gulp-eslint'
Message:
    Failed with 2 errors

怒られました:imp:
該当部分を修正した後、再度commitしてみます。

$ git commit -m 'check'
[16:55:09] Using gulpfile ~/tmp/eslint/gulpfile.js
[16:55:09] Starting 'lint'...
[16:55:10] Finished 'lint' after 720 ms
[master 6992a22] check
 1 file changed, 1 insertion(+), 1 deletion(-)

無事、commitできました:rocket:

さいごに

とりあえず後でrebaseするからcommitだけさせてよーってときは、git commit --no-verifyのオプションで回避できます:sushi:

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14