Skip to content

Commit 7344c42

Browse files
authored
Fix problems with the format tasks (#1390)
* Fix problems with the format tasks The format check is using python2, and if "python" doesn't exist on the path (or isn't python 2, or there is any other error in the python code or in the shell script...) the format check just succeeds. This change: - Refactors out the gradle code that finds a python3 executable and use it to get the python executable to be used for the format check. - Upgrades google-java-format-diff.py to python3 and removes #! line. - Fixes shell script to ensure that failures are propagated. - Suppresses error output when checking for python commands. Tested: - verified that python errors cause the build to fail - verified that introducing a bad format diff causes check to fail - verified that javaIncrementalFormatDryRun shows the diffs that would be introduced. - verified that javaIncrementalFormatApply reformats a file. - verified that well formatted code passes the format check. - verified that an invalid or missing PYTHON env var causes google-java-format-git-diff.sh to fail with the appropriate error. * Fix presubmit issues Omit the format presubmit when not in a git repo and remove unused "string" import.
1 parent 969fa2b commit 7344c42

3 files changed

Lines changed: 59 additions & 31 deletions

File tree

build.gradle

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -200,33 +200,39 @@ rootProject.ext {
200200
pyver = { exe ->
201201
try {
202202
ext.execInBash(
203-
exe + " -c 'import sys; print(sys.hexversion)'", "/") as Integer
203+
exe + " -c 'import sys; print(sys.hexversion)' 2>/dev/null",
204+
"/") as Integer
204205
} catch (org.gradle.process.internal.ExecException e) {
205206
return -1;
206207
}
207208
}
208-
}
209-
210-
task runPresubmits(type: Exec) {
211-
212-
args('config/presubmits.py')
213209

214-
doFirst {
210+
// Return the path to a usable python3 executable.
211+
getPythonExecutable = {
215212
// Find a python version greater than 3.7.3 (this is somewhat arbitrary, we
216213
// know we'd like at least 3.6, but 3.7.3 is the latest that ships with
217214
// Debian so it seems like that should be available anywhere).
218215
def MIN_PY_VER = 0x3070300
219216
if (pyver('python') >= MIN_PY_VER) {
220-
executable 'python'
217+
return 'python'
221218
} else if (pyver('/usr/bin/python3') >= MIN_PY_VER) {
222-
executable '/usr/bin/python3'
219+
return '/usr/bin/python3'
223220
} else {
224221
throw new GradleException("No usable Python version found (build " +
225222
"requires at least python 3.7.3)");
226223
}
227224
}
228225
}
229226

227+
task runPresubmits(type: Exec) {
228+
229+
args('config/presubmits.py')
230+
231+
doFirst {
232+
executable getPythonExecutable()
233+
}
234+
}
235+
230236
def javadocSource = []
231237
def javadocClasspath = []
232238
def javadocDependentTasks = []
@@ -438,28 +444,34 @@ rootProject.ext {
438444
? "${rootDir}/.."
439445
: rootDir
440446
def formatDiffScript = "${scriptDir}/google-java-format-git-diff.sh"
447+
def pythonExe = getPythonExecutable()
441448

442449
return ext.execInBash(
443-
"${formatDiffScript} ${action}", "${workingDir}")
450+
"PYTHON=${pythonExe} ${formatDiffScript} ${action}", "${workingDir}")
444451
}
445452
}
446453

447454
// Checks if modified lines in Java source files need reformatting.
448455
// Note that this task checks modified Java files in the entire repository.
449456
task javaIncrementalFormatCheck {
450457
doLast {
451-
def checkResult = invokeJavaDiffFormatScript("check")
452-
if (checkResult == 'true') {
453-
throw new IllegalStateException(
454-
"Some Java files need to be reformatted. You may use the "
455-
+ "'javaIncrementalFormatDryRun' task to review\n "
456-
+ "the changes, or the 'javaIncrementalFormatApply' task "
457-
+ "to reformat.")
458-
} else if (checkResult != 'false') {
459-
throw new RuntimeException(
460-
"Failed to invoke format check script:\n" + checkResult)
458+
// We can only do this in a git tree.
459+
if (new File("${rootDir}/.git").exists()) {
460+
def checkResult = invokeJavaDiffFormatScript("check")
461+
if (checkResult == 'true') {
462+
throw new IllegalStateException(
463+
"Some Java files need to be reformatted. You may use the "
464+
+ "'javaIncrementalFormatDryRun' task to review\n "
465+
+ "the changes, or the 'javaIncrementalFormatApply' task "
466+
+ "to reformat.")
467+
} else if (checkResult != 'false') {
468+
throw new RuntimeException(
469+
"Failed to invoke format check script:\n" + checkResult)
470+
}
471+
println("Incremental Java format check ok.")
472+
} else {
473+
println("Omitting format check: not in a git directory.")
461474
}
462-
println("Incremental Java format check ok.")
463475
}
464476
}
465477

java-format/google-java-format-diff.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
#!/usr/bin/env python2.7
21
#
32
#===- google-java-format-diff.py - google-java-format Diff Reformatter -----===#
43
#
@@ -24,7 +23,6 @@
2423
import argparse
2524
import difflib
2625
import re
27-
import string
2826
import subprocess
2927
import io
3028
import sys
@@ -99,7 +97,7 @@ def main():
9997
base_command = [binary]
10098

10199
# Reformat files containing changes in place.
102-
for filename, lines in lines_by_file.iteritems():
100+
for filename, lines in lines_by_file.items():
103101
if args.i and args.verbose:
104102
print('Formatting ' + filename)
105103
command = base_command[:]
@@ -120,11 +118,11 @@ def main():
120118
if not args.i:
121119
with open(filename) as f:
122120
code = f.readlines()
123-
formatted_code = io.BytesIO(stdout).readlines()
121+
formatted_code = io.StringIO(stdout.decode()).readlines()
124122
diff = difflib.unified_diff(code, formatted_code,
125123
filename, filename,
126124
'(before formatting)', '(after formatting)')
127-
diff_string = string.join(diff, '')
125+
diff_string = ''.join(diff)
128126
if len(diff_string) > 0:
129127
sys.stdout.write(diff_string)
130128

java-format/google-java-format-git-diff.sh

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,16 @@ where:
4242
SCRIPT_DIR="$(realpath $(dirname $0))"
4343
JAR_NAME="google-java-format-1.8-all-deps.jar"
4444

45+
# Make sure we have a valid python interpreter.
46+
if [ -z "$PYTHON" ]; then
47+
echo "You must specify the name of a python3 interpreter in the PYTHON" \
48+
"environment variable."
49+
exit 1
50+
elif ! "$PYTHON" -c ''; then
51+
echo "Invalid python interpreter: $PYTHON"
52+
exit 1
53+
fi
54+
4555
# Locate the java binary.
4656
if [ -n "$JAVA_HOME" ]; then
4757
JAVA_BIN="$JAVA_HOME/bin/java"
@@ -69,10 +79,14 @@ function runGoogleJavaFormatAgainstDiffs() {
6979
shift
7080

7181
git diff -U0 "$forkPoint" | \
72-
${SCRIPT_DIR}/google-java-format-diff.py \
73-
--java-binary "$JAVA_BIN" \
74-
--google-java-format-jar "${SCRIPT_DIR}/${JAR_NAME}" \
75-
-p1 "$@" | tee gjf.out
82+
"${PYTHON}" "${SCRIPT_DIR}/google-java-format-diff.py" \
83+
--java-binary "$JAVA_BIN" \
84+
--google-java-format-jar "${SCRIPT_DIR}/${JAR_NAME}" \
85+
-p1 "$@" | \
86+
tee gjf.out
87+
88+
# If any of the commands in the last pipe failed, return false.
89+
[[ ! "${PIPESTATUS[@]}" =~ [^0\ ] ]]
7690
}
7791

7892
# Show the file names in a diff preceeded by a message.
@@ -96,7 +110,11 @@ function callGoogleJavaFormatDiff() {
96110
local callResult
97111
case "$1" in
98112
"check")
99-
local output=$(runGoogleJavaFormatAgainstDiffs "$forkPoint")
113+
# We need to do explicit checks for an error and "exit 1" if there was
114+
# one here (though not elsewhere), "set -e" doesn't catch this case,
115+
# it's not clear why.
116+
local output
117+
output=$(runGoogleJavaFormatAgainstDiffs "$forkPoint") || exit 1
100118
echo "$output" | showFileNames "\033[1mNeeds formatting: "
101119
callResult=$(echo -n "$output" | wc -l)
102120
;;

0 commit comments

Comments
 (0)