2
0

More than 3 years have passed since last update.

pre-commit時にphp-cs-fixierを走らせる

Last updated at Posted at 2019-11-26

作業者それぞれ書き方にブレがあるとウガーってなりますよね。
コミット時にphp-cs-fixierを走らせて強制的にfixするようにします。

pre-commitのファイルを作成します

リポジトリの.gitディレクトリの中にあるpre-commit.sampleファイルをリネームコピーします。

cp .git/hooks/pre-commit.sample .git/hooks/pre-commit

pre-commitファイル

pre-commitファイルに下記を記述します。

#!/bin/sh

# php-cs-fixerを適用してからコミットします

if git rev-parse --verify HEAD >/dev/null 2>&1
then
  against=HEAD
else
  # Initial commit: diff against an empty tree object
  against=$(git hash-object -t tree /dev/null)
fi

# If you want to allow non-ASCII filenames set this variable to true.
allownonascii=$(git config --bool hooks.allownonascii)

# Redirect output to stderr.
exec 1>&2

# 終了コード
IS_ERROR=0

# 区切り文字を改行のみにする
IFS=$'\n'

for FILE in `git diff --cached --name-only --diff-filter=d | grep .php`; do
  if php -l $FILE; then
    php-cs-fixer fix $FILE
    git add $FILE
  else
    IS_ERROR=1
  fi
done

if [ $IS_ERROR -eq 1 ] ; then
  echo syntax error was detected. please correct.
fi

exit $IS_ERROR

fixする対象は作業した(差分のある)ファイルです。
phpのsyntaxなどでエラーが出た場合は別途メッセージが表示されます。

2
0
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
2
0