Skip to content

Commit e8ae37c

Browse files
authored
Add php-cs-fixer hook (#5)
* Add php-cs-fixer hook * Update CHANGELOG
1 parent 64f6bd4 commit e8ae37c

File tree

2 files changed

+69
-4
lines changed

2 files changed

+69
-4
lines changed

CHANGELOG.md

+5-4
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,14 @@ Security - in case of vulnerabilities.
1616

1717
## [Unreleased]
1818
### Added
19-
- Added hooks `disallow-commits`
20-
- Added hooks `conventional-commit`
19+
- Added hook `disallow-commits`
20+
- Added hook `conventional-commit`
21+
- Added hook `php-cs-fixer`
2122

2223
## [1.1.0] 2019-03-01
2324
### Added
24-
- Added hooks `motivation`
25-
- Added hooks `files-watcher`
25+
- Added hook `motivation`
26+
- Added hook `files-watcher`
2627

2728
## [1.0.0] 2019-03-01
2829
Initial release.

php-cs-fixer/php-cs-fixer

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#!/bin/sh
2+
# Git `pre-commit` hook that runs `php-cs-fixer` against changed files.
3+
#
4+
# Note: you can use `commit --no-verify` to skip `pre-commit` hooks.
5+
#
6+
# Example of config:
7+
# ~~~
8+
# [php-cs-fixer]
9+
# command = php-cs-fixer
10+
# mode = check
11+
# config-file = .php_cs
12+
# files-pattern = .php$
13+
# ~~~
14+
15+
FCR='\033[1;31m' # Red
16+
FCG='\033[1;32m' # Green
17+
FCY='\033[0;33m' # Yellow
18+
FCS='\033[0;37m' # Light gray (silver)
19+
NC='\033[0m'
20+
21+
report_error() {
22+
echo "${FCR}$@${NC}"
23+
}
24+
25+
report_done() {
26+
[[ $# > 0 ]] && echo "${FCG}$@${NC}" || echo "${FCG}✓ Done${NC}"
27+
}
28+
29+
command=$(git config --default php-cs-fixer --get php-cs-fixer.command)
30+
mode=$(git config --default check --get php-cs-fixer.mode)
31+
prefix_pattern=$(git config --default .php_cs --get php-cs-fixer.config-file)
32+
files_pattern=$(git config --default \.php$ --get php-cs-fixer.files-pattern)
33+
34+
diff_files() {
35+
git diff --name-only --diff-filter=ACMRTUXB $1 | grep -i ${files_pattern}
36+
}
37+
38+
cs() {
39+
if [[ -n "$1" ]] ; then
40+
case ${mode} in
41+
"check" )
42+
command ${command} fix --dry-run --config=${prefix_pattern} -v --using-cache=no --diff --diff-format=udiff --ansi $1
43+
;;
44+
"fix" )
45+
command ${command} fix --config=${prefix_pattern} -v --using-cache=no --diff --diff-format=udiff --ansi $1
46+
;;
47+
* )
48+
report_error "Invalid mode option"
49+
esac
50+
else
51+
echo "Nothing to fix"
52+
fi
53+
}
54+
55+
cs "$(diff_files HEAD)"
56+
status=$?
57+
58+
if [[ ${status} -gt 0 ]] ; then
59+
report_error "Commit rejected due Coding Standards errors"
60+
else
61+
report_done
62+
fi
63+
64+
exit ${status}

0 commit comments

Comments
 (0)