forked from pytorch/PiPPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.sh
executable file
·157 lines (125 loc) · 2.52 KB
/
format.sh
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#!/bin/bash
# USAGE: ./format.sh [--show-targets] [--check] [TARGETS]
# When used with --show-targets, list all default targets and exits.
# When used with --check, reports errors but changes nothing.
DEFAULT_TARGETS=()
for f in $(git ls-files | grep '\.py$'); do
case "$f" in
'pippy/fx/'*)
# ignore
;;
'pippy/'*)
DEFAULT_TARGETS+=( "$f" )
;;
'examples/'*)
# ignore
;;
'docs/'*)
# ignore
;;
'test/'*fx*)
# ignore
;;
*)
# include
DEFAULT_TARGETS+=( "$f" )
;;
esac
done
function format() {
local TARGET="$1"
# TODO: enable autoflake and isort.
# these are not currently enabeled because the existing
# import structure has magic side-effects that need to
# be cleaned up so that isort and autoflake don't break them.
# | autoflake \
# --stdin-display-name "$TARGET" \
# --remove-all-unused-imports \
# - \
# | isort \
# --filename "$TARGET" \
# - \
cat "$TARGET" \
| black \
-q \
--stdin-filename "$TARGET" \
-
return ${PIPESTATUS[-1]}
}
function format_check() {
local TARGET="$1"
local TFILE=$(mktemp)
trap "rm $TFILE" EXIT
format "$TARGET" > "$TFILE"
diff -u "$TARGET" "$TFILE"
return $?
}
function reformat_inplace() {
local TARGET="$1"
local TFILE=$(mktemp)
trap "rm $TFILE" EXIT
format "$TARGET" > "$TFILE"
if (( $? )); then
return $?;
fi
diff -q "$TARGET" "$TFILE" > /dev/null
if (( $? )); then
cat "$TFILE" > "$TARGET";
fi
return 0
}
function main() {
local CHECK
local TARGETS
CHECK=0
TARGETS=()
for x in "$@"; do
case "$x" in
'--show-targets')
for f in "${DEFAULT_TARGETS[@]}"; do
echo $f;
done
exit 0;
;;
'--check')
CHECK=1;
;;
*)
TARGETS+=( "$x" )
;;
esac
done
if (( ${#TARGETS[@]} == 0 )); then
TARGETS=( ${DEFAULT_TARGETS[@]} )
fi
PY_TARGETS=()
for x in "${TARGETS[@]}"; do
if [[ -d "$x" ]]; then
PY_TARGETS+=( $(find "$x" -name '*.py' -or -name '*.pyi') )
elif [[ -f "$x" ]]; then
case "$x" in
*.py)
PY_TARGETS+=( "$x" );
;;
esac
fi
done
if (( $CHECK )); then
local result
result=0
for x in "${PY_TARGETS[@]}"; do
format_check "$x";
(( result|=$? ))
done
exit $result
else
local result
result=0
for x in "${PY_TARGETS[@]}"; do
reformat_inplace "$x";
(( result|=$? ))
done
exit $result
fi
}
main "$@"