⚡
追加の依存パッケージなしで PHP プロジェクトごとの Git コミットフックを設定する
はじめに
元ネタは以下。
追加の依存パッケージなしでプロジェクトごとのGitコミットフックを設定する方法 | Web Scratch
元ネタはNode.js の例だったので、PHP のプロジェクトで PHP-CS-Fixer を実行する場合を考えてみる。
手順
-
.githooksディレクトリ(名前は何でも可)を作成する。 - 上記で作成したディレクトリ内に Git フック で実行されるファイルを作成する。
-
core.hooksPathオプションを設定できるようにする。
1. .githooksディレクトリを作成する。
% mkdir .githooks
2. .githooks/pre-commitを作成して、コミットフックの処理を書く。
.githooks/pre-commit
#!/bin/bash
ROOT_DIR=$(git rev-parse --show-toplevel)
PHP_CS_FIXER="${ROOT_DIR}/vendor/bin/php-cs-fixer fix --stop-on-violation --using-cache=no"
LIST=$(git diff-index --cached --name-status HEAD -- | grep -E '^[AUM].*\.php$' | cut -c3-)
HAS_ERROR=false
for file in $LIST; do
target="${ROOT_DIR}/${file}"
if php -l "${target}" >/dev/null; then
if ${PHP_CS_FIXER} "${target}" >/dev/null 2>&1; then
git add "${target}"
else
HAS_ERROR=true
fi
else
HAS_ERROR=true
fi
done
if "${HAS_ERROR}"; then
echo -e "\033[31mCommit failed\033[m"
exit 1
fi
3. composer.jsonのライフサイクルスクリプトでcore.hooksPathを設定する。
何かしらのcomposerのコマンド(composer installとか)を実行するとpre-command-runスクリプトが実行され、.githooksが Git フックディレクトリとして扱われるようになる。
"scripts": {
"pre-command-run": [
"git config --local core.hooksPath .githooks"
]
}
参考
- Git - githooks Documentation
- Scripts - Composer
- FriendsOfPHP/PHP-CS-Fixer: A tool to automatically fix PHP Coding Standards issues
- PHP-CS-FixerとGit フックで治安保持活動 - Qiita
環境
% git --version
git version 2.33.0
% composer -V
Composer version 2.0.11 2021-02-24 14:57:23
% sw_vers
ProductName: macOS
ProductVersion: 11.3.1
BuildVersion: 20E241
Discussion