forked from TRI-ML/dgp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpre-commit
executable file
·63 lines (54 loc) · 2.12 KB
/
pre-commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#!/bin/bash
# Copyright 2019 Toyota Research Institute. All rights reserved.
# Git pre-commit hook to check staged Python files for formatting issues with
# yapf.
#
# When running, this first checks for unstaged changes to staged files, and if
# there are any, it will exit with an error. Files with unstaged changes will be
# printed.
#
# If all staged files have no unstaged changes, it will run yapf against them,
# leaving the formatting changes unstaged. Changed files will be printed.
#
# BUGS: This does not leave staged changes alone when used with the -a flag to
# git commit, due to the fact that git stages ALL unstaged files when that flag
# is used.
# Find all staged Python files, and exit early if there aren't any.
PYTHON_FILES=$(git diff --name-only --cached --diff-filter=AM | \
grep --color=never '.py$' | grep -Fv '_pb2')
PYTHON_FILES="${PYTHON_FILES//$'\n'/ }" # Replace all newline with a space.
if [ ! "${PYTHON_FILES[@]}" ]; then
exit 0
fi
# Check for unstaged changes to files in the index.
CHANGED_FILES=$(git diff --name-only "${PYTHON_FILES}")
CHANGED_FILES="${CHANGED_FILES//$'\n'/ }" # Replace all newline with a space.
if [ "${CHANGED_FILES[@]}" ]; then
echo 'You have unstaged changes to some files in your commit; skipping '
echo 'autoformat. Please stage, stash, or revert these changes. You may '
echo "find 'git stash -k' helpful here."
echo
echo 'Files with unstaged changes:'
for file in ${CHANGED_FILES}; do
echo " $file"
done
exit 1
fi
echo 'Fixing import order in Python files . . .'
isort "${PYTHON_FILES}"
# Format all staged files, then exit with an error code if any have uncommitted
# changes.
echo 'Formatting staged Python files with YAPF . . .'
yapf --style .style.yapf -i -r --exclude '*pb2.py' --exclude '*pb2_grpc.py' --exclude '*eggs*.py' --exclude '*env*' --exclude 'build/*' "${PYTHON_FILES}"
CHANGED_FILES=$(git diff --name-only "${PYTHON_FILES[@]}")
if [ "${CHANGED_FILES[@]}" ]; then
echo 'Reformatted staged files. Please review and stage the changes.'
echo
echo 'Files updated:'
for file in "${CHANGED_FILES[@]}"; do
echo " $file"
done
exit 1
else
exit 0
fi