要執(zhí)行這個(gè)操作需要掌握兩個(gè)知識(shí)點(diǎn)
- php語法檢查工具php-cs-fixer(使用方法自行百度)。
- git鉤子的使用方法(如果不懂就繼續(xù)百度吧)。
具體操作方式:
- 在一個(gè)git項(xiàng)目的根目錄下進(jìn)入鉤子目錄編輯提交之前的鉤子文件
cd .git/hooks
大約能看到以下幾個(gè)鉤子文件,是git提供的一些例子。去掉.sample后綴名之后都可以運(yùn)行。
├── applypatch-msg.sample
├── commit-msg.sample
├── post-update.sample
├── pre-applypatch.sample
├── pre-commit.sample
├── pre-push.sample
├── pre-rebase.sample
├── pre-receive.sample
├── prepare-commit-msg.sample
└── update.sample
在文件列表中,pre-commit.sample 文件就是執(zhí)行 git commit命令之前的鉤子文件。系統(tǒng)會(huì)先調(diào)用此文件,我們就在這個(gè)文件里面處理那些已經(jīng)被add到暫存區(qū)的php文件。
1. 在當(dāng)前目錄創(chuàng)建一個(gè)pre-commit文件,并將以下代碼復(fù)制進(jìn)去,并保存。
#!/usr/bin/env bash
while read -r file;
do
file=${file:1}
#只處理后綴名為.php的文件
if [[ $file = *.php ]];
then
#執(zhí)行語法檢查并將不符合php代碼規(guī)范的文件執(zhí)行強(qiáng)轉(zhuǎn)
php-cs-fixer fix $file;
#重新執(zhí)行g(shù)it命令,將強(qiáng)轉(zhuǎn)之后的文件重新加入到緩存區(qū)
git add $file;
fi
done < <(git diff --cached --name-status --diff-filter=ACM)
#執(zhí)行完成,退出此腳本
exit 0
注意:php-cs-fixer命令需要配置好全局變量,否則的話,請寫全路徑,避免找不到php-cs-fixer命令而報(bào)錯(cuò)
然后,我們再執(zhí)行g(shù)it提交命令的時(shí)候,就會(huì)把php文件全部執(zhí)行一遍格式轉(zhuǎn)化然后再提交啦。
git commit -m 'xxxxxxxxxxx'