From fd4c08bf706f9529f8b47989b41740444a59ffd0 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 27 Oct 2026 08:53:51 -0700 Subject: [PATCH 1/4] Fix Java version detection --- run-google-java-format.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/run-google-java-format.py b/run-google-java-format.py index 53133cd..c8f6999 100755 --- a/run-google-java-format.py +++ b/run-google-java-format.py @@ -30,16 +30,17 @@ fixup_py_name = "fixup-google-java-format.py" fixup_py_path = script_dir / fixup_py_name -# java_version_string is either 1.8 or nothing. -# For JDK 8, `java -version` has the form: openjdk version "1.8.0_292" -# For JDK 11, `java -version` has the form: openjdk 11.0.11 2021-04-20 -# For JDK 17, `java -version` has the form: java 17 2021-09-14 LTS +# java_version_string is the output of `java -version`. Its first line has a form such as: +# JDK 8: openjdk version "1.8.0_292" +# JDK 11: openjdk version "11.0.11" 2021-04-20 +# JDK 17: java version "17" 2021-09-14 LTS java_version_string = subprocess.check_output( ["java", "-version"], stderr=subprocess.STDOUT ).decode("utf-8") if debug: print("java_version_string =", java_version_string) -match = re.search(r'"(\d+(\.\d+)?).*"', java_version_string) +# java_version is the major version, such as "1.8", "11", or "17". +match = re.search(r'"(1\.\d+|\d+)[^"]*"', java_version_string) if not match: msg = f'no match for java version string "{java_version_string}"' raise Exception(msg) From 3b38cd46380b30714af9bfebf846e232ee79fe33 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 27 Oct 2026 14:01:20 -0700 Subject: [PATCH 2/4] Parse the Java version as an integer and choose by range Anchor the regex to the version line, so that preceding lines such as "Picked up JAVA_TOOL_OPTIONS: ..." do not confuse it. Add unit tests. Co-Authored-By: Claude Opus 5.5 --- .circleci/config.yml | 3 ++ Makefile | 3 ++ run-google-java-format.py | 48 +++++++++++++++++--------- tests/test_parse_java_version.py | 58 ++++++++++++++++++++++++++++++++ 4 files changed, 97 insertions(+), 15 deletions(-) create mode 100644 tests/test_parse_java_version.py diff --git a/.circleci/config.yml b/.circleci/config.yml index 232d815..6fc7ad6 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -11,6 +11,9 @@ jobs: - run: name: Run prek hooks command: prek run -q --all-files + - run: + name: Run tests + command: make test workflows: build: jobs: diff --git a/Makefile b/Makefile index 75eba78..047b38b 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,9 @@ # Nothing to do default: +test: + python3 -m unittest discover -s tests + type-qualifiers.txt: grep --recursive --files-with-matches -e '^@Target\b.*TYPE_USE' ${CHECKERFRAMEWORK}/checker/src/test ${CHECKERFRAMEWORK}/checker-qual/src/main/java ${CHECKERFRAMEWORK}/framework/src/main/java ${CHECKERFRAMEWORK}/docs/examples/units-extension ${CHECKERFRAMEWORK}/framework/src/test/java \ | grep -v '~' | sed 's:.*/::' \ diff --git a/run-google-java-format.py b/run-google-java-format.py index c8f6999..7544903 100755 --- a/run-google-java-format.py +++ b/run-google-java-format.py @@ -30,21 +30,39 @@ fixup_py_name = "fixup-google-java-format.py" fixup_py_path = script_dir / fixup_py_name -# java_version_string is the output of `java -version`. Its first line has a form such as: -# JDK 8: openjdk version "1.8.0_292" -# JDK 11: openjdk version "11.0.11" 2021-04-20 -# JDK 17: java version "17" 2021-09-14 LTS + +def parse_java_version(java_version_string: str) -> int: + """Return the major version of the JDK, given the output of `java -version`. + + The output of `java -version` contains a line with a form such as: + JDK 8: openjdk version "1.8.0_292" + JDK 11: openjdk version "11.0.11" 2021-04-20 + JDK 17: java version "17" 2021-09-14 LTS + Other lines may precede it, such as "Picked up JAVA_TOOL_OPTIONS: ...". + + Args: + java_version_string: the output of `java -version` + + Returns: + the major version of the JDK, such as 8, 11, or 17 + + Raises: + Exception: if `java_version_string` contains no version line. + """ + match = re.search(r'^\w+ version "(?:1\.(\d+)|(\d+))', java_version_string, re.MULTILINE) + if not match: + msg = f'no match for java version string "{java_version_string}"' + raise Exception(msg) + return int(match.group(1) or match.group(2)) + + java_version_string = subprocess.check_output( ["java", "-version"], stderr=subprocess.STDOUT ).decode("utf-8") if debug: print("java_version_string =", java_version_string) -# java_version is the major version, such as "1.8", "11", or "17". -match = re.search(r'"(1\.\d+|\d+)[^"]*"', java_version_string) -if not match: - msg = f'no match for java version string "{java_version_string}"' - raise Exception(msg) -java_version = match.groups()[0] +# java_version is the major version of the JDK, such as 8, 11, or 17. +java_version = parse_java_version(java_version_string) ## To use an officially released version. ## (Releases appear at https://github.com/google/google-java-format/releases/ , @@ -59,13 +77,13 @@ ## To set this variable: ## https://github.com/diffplug/spotless/blob/3924217d5f711a9fa41dcb71810f6e3649328135/lib/src/main/java/com/diffplug/spotless/java/GoogleJavaFormatStep.java#L122 ## or search for "Bump default google" in https://github.com/diffplug/spotless/blob/main/plugin-gradle/CHANGES.md -if java_version == "1.8": +if java_version < 11: gjf_version_default = "1.7" -elif java_version == "11": +elif java_version < 17: gjf_version_default = "1.24.0" -elif java_version == "17": +elif java_version < 21: gjf_version_default = "1.28.0" -elif java_version == "21": +elif java_version < 22: gjf_version_default = "1.29.0" else: gjf_version_default = "1.36.1" @@ -188,7 +206,7 @@ def urlretrieve(url: str, filename: Path) -> None: print("run-google-java-format.py expects 1 or more filenames as arguments") sys.exit(1) -if java_version == "1.8": +if java_version < 9: jdk_opens = [] else: # From https://github.com/google/google-java-format/releases/ diff --git a/tests/test_parse_java_version.py b/tests/test_parse_java_version.py new file mode 100644 index 0000000..9307d34 --- /dev/null +++ b/tests/test_parse_java_version.py @@ -0,0 +1,58 @@ +"""Tests for `parse_java_version` in run-google-java-format.py.""" + +import ast +import re +import unittest +from collections.abc import Callable +from typing import Any +from pathlib import Path + +# Importing run-google-java-format.py would run it, so extract just the function. +script_path = Path(__file__).resolve().parent.parent / "run-google-java-format.py" +script_tree = ast.parse(script_path.read_text()) +function_def = next( + node + for node in script_tree.body + if isinstance(node, ast.FunctionDef) and node.name == "parse_java_version" +) +namespace: dict[str, Any] = {"re": re} +exec(compile(ast.Module([function_def], []), str(script_path), "exec"), namespace) # noqa: S102 +parse_java_version: Callable[[str], int] = namespace["parse_java_version"] + + +class TestParseJavaVersion(unittest.TestCase): + """Tests for `parse_java_version`.""" + + def test_versions(self) -> None: + """Test the output of various JDKs.""" + cases = { + 'java version "1.7.0_80"\n': 7, + 'openjdk version "1.8.0_292"\n': 8, + 'openjdk version "10.0.2" 2018-07-17\n': 10, + 'openjdk version "11.0.11" 2021-04-20\n': 11, + 'openjdk version "16.0.2" 2021-07-20\n': 16, + 'java version "17" 2021-09-14 LTS\n': 17, + 'openjdk version "21.0.5" 2024-10-15 LTS\n': 21, + 'openjdk version "26-ea" 2026-03-17\n': 26, + } + for java_version_string, expected in cases.items(): + with self.subTest(java_version_string=java_version_string): + self.assertEqual(parse_java_version(java_version_string), expected) + + def test_preceding_line(self) -> None: + """Test output that has a line before the version line.""" + java_version_string = ( + 'Picked up JAVA_TOOL_OPTIONS: -Dhttp.proxyPort="8080"\n' + 'openjdk version "17.0.1" 2021-10-19\n' + "OpenJDK Runtime Environment (build 17.0.1+12-39)\n" + ) + self.assertEqual(parse_java_version(java_version_string), 17) + + def test_no_version(self) -> None: + """Test output that contains no version line.""" + with self.assertRaises(Exception): # noqa: B017, PT027 + parse_java_version("Error: could not find java.dll\n") + + +if __name__ == "__main__": + unittest.main() From 2b648eed3548552e4960c3627f8ce7be313bef40 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 27 Oct 2026 14:23:55 -0700 Subject: [PATCH 3/4] Satisfy ruff in the test file Co-Authored-By: Claude Opus 5.5 --- tests/test_parse_java_version.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test_parse_java_version.py b/tests/test_parse_java_version.py index 9307d34..cf88445 100644 --- a/tests/test_parse_java_version.py +++ b/tests/test_parse_java_version.py @@ -4,8 +4,8 @@ import re import unittest from collections.abc import Callable -from typing import Any from pathlib import Path +from typing import Any # Importing run-google-java-format.py would run it, so extract just the function. script_path = Path(__file__).resolve().parent.parent / "run-google-java-format.py" @@ -16,7 +16,7 @@ if isinstance(node, ast.FunctionDef) and node.name == "parse_java_version" ) namespace: dict[str, Any] = {"re": re} -exec(compile(ast.Module([function_def], []), str(script_path), "exec"), namespace) # noqa: S102 +exec(compile(ast.Module([function_def], []), str(script_path), "exec"), namespace) parse_java_version: Callable[[str], int] = namespace["parse_java_version"] @@ -50,7 +50,7 @@ def test_preceding_line(self) -> None: def test_no_version(self) -> None: """Test output that contains no version line.""" - with self.assertRaises(Exception): # noqa: B017, PT027 + with self.assertRaises(Exception): # ruff: ignore[assert-raises-exception] parse_java_version("Error: could not find java.dll\n") From b3479069157811176046c7d4f2b0ef8422433037 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 27 Oct 2026 14:42:24 -0700 Subject: [PATCH 4/4] Run tests in GitHub Actions; remove a redundant comment Co-Authored-By: Claude Opus 5.5 --- .github/workflows/prek.yaml | 1 + run-google-java-format.py | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/prek.yaml b/.github/workflows/prek.yaml index 707d9a1..39135a6 100644 --- a/.github/workflows/prek.yaml +++ b/.github/workflows/prek.yaml @@ -8,3 +8,4 @@ jobs: - uses: actions/checkout@v7 - run: curl -fLSs https://raw.githubusercontent.com/CircleCI-Public/circleci-cli/main/install.sh | sudo bash - uses: j178/prek-action@v3.1.0 + - run: make test diff --git a/run-google-java-format.py b/run-google-java-format.py index 7544903..a121442 100755 --- a/run-google-java-format.py +++ b/run-google-java-format.py @@ -61,7 +61,6 @@ def parse_java_version(java_version_string: str) -> int: ).decode("utf-8") if debug: print("java_version_string =", java_version_string) -# java_version is the major version of the JDK, such as 8, 11, or 17. java_version = parse_java_version(java_version_string) ## To use an officially released version.