Last active
October 13, 2015 10:18
-
-
Save ymt2/4181312 to your computer and use it in GitHub Desktop.
[githook][python]phpのシンタックスチェック
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
import sys | |
import os | |
import subprocess | |
def get_index_files(extensions=[]): | |
"""gitリポジトリ path の INDEX に追加されているファイル名一覧を返す | |
Keyword arguments: | |
extensions -- フィルタする拡張子 | |
""" | |
against = 'HEAD' | |
try: | |
subprocess.check_output(['git', 'rev-parse', '--verify', 'HEAD'], | |
stderr=subprocess.STDOUT) | |
except subprocess.CalledProcessError, e: | |
against = '4b825dc642cb6eb9a060e54bf8d69288fbee4904' | |
try: | |
output = subprocess.check_output( | |
['git', 'diff-index', '--cached', '--name-only', against]) | |
except subprocess.CalledProcessError, e: | |
print '# unexpected error occurred' | |
print e | |
return [] | |
file_paths = [] | |
for file_path in output.split('\n'): | |
if not file_path: | |
break | |
path, ext = os.path.splitext(file_path) | |
if ext in extensions and os.path.exists(file_path): | |
file_paths.append(file_path) | |
return file_paths | |
def is_valid_php(file_path): | |
"""php -l を実行して結果を返す | |
Keyword arguments: | |
file_paths -- チェック対象のファイル | |
""" | |
try: | |
subprocess.check_output(['php', '-l', file_path]) | |
return True | |
except subprocess.CalledProcessError, e: | |
return False | |
def main(): | |
return_code = 0 | |
file_paths = get_index_files(extensions=['.php']) | |
error_files = [] | |
for file_path in file_paths: | |
if not is_valid_php(file_path): | |
return_code = 1 | |
error_files.append(file_path) | |
for file_path in error_files: | |
print '# error occurred : %s' % file_path | |
sys.exit(return_code) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment