Skip to content

Instantly share code, notes, and snippets.

@alongosz
Last active November 22, 2017 16:23
Show Gist options
  • Save alongosz/b42be08c33dc28d89e0ab28ae2ed1c0c to your computer and use it in GitHub Desktop.
Save alongosz/b42be08c33dc28d89e0ab28ae2ed1c0c to your computer and use it in GitHub Desktop.
[Python][Git] php-cs-fixer Git pre-commit hook
#!/usr/bin/env python
#
# by @Nattfarinn, improved by @alongosz
# Requires php-cs-fixer executable
# Place it in your repository, in .git/hooks/pre-commit
import sys
import subprocess
process = subprocess.Popen(['git', 'diff', '--cached', '--name-only', '--diff-filter=ACMRT'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errors = process.communicate()
paths = output.decode("utf-8").rstrip("\n").split("\n")
need_fix = []
for path in paths:
if path.endswith(".php"):
process = subprocess.Popen(['php-cs-fixer', 'fix', '--diff', '--no-interaction', '--dry-run', path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, errors = process.communicate()
if process.returncode:
print(output.decode("utf-8"))
need_fix.append(path)
if len(need_fix):
print("These files do not follow the PHP Coding Standards:")
for path in need_fix:
print(" * ", path)
print()
print("Fix them before commiting.")
exit(1)
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment