From 8d9d5372e7687733c6dd5b3c95f10754ee011bb0 Mon Sep 17 00:00:00 2001 From: Niklas Higi Date: Wed, 28 Apr 2021 10:29:19 +0200 Subject: [PATCH] Fix Java version check failing when it can only find a major version Fixes #52 --- src/utils/get-java-version.ts | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/utils/get-java-version.ts b/src/utils/get-java-version.ts index 9dd4a10..7d3f23e 100644 --- a/src/utils/get-java-version.ts +++ b/src/utils/get-java-version.ts @@ -1,13 +1,16 @@ import execa = require('execa') -/** Extracts the Java major version from the output of `java -version`. */ +/** Returns the major version of the system's default Java installation. */ export default async function getJavaVersion() { try { const { stderr } = await execa('java', ['-version']) - const version = stderr.match(/"(\d+\.\d+\.\d+)/)![1] + const majorVersionString = stderr.match(JAVA_VERSION_PATTERN)?.groups?.major + if (!majorVersionString) { + const message = `Could not extract Java major version from "java -version" output!\n${stderr}` + throw new Error(message) + } - // `.replace` needed to remove `1.` prefix from versions older than Java 9 - return parseInt(version.replace(/^1\./, '').match(/^\d+/)![0]) + return parseInt(majorVersionString) } catch (error) { if (error.code === 'ENOENT') throw new Error( @@ -18,3 +21,14 @@ export default async function getJavaVersion() { throw error } } + +/** + * Pattern for extracting the Java major version from the output of + * `java -version` (stripping the `1.` prefix from versions prior to Java 9). + * + * Some example outputs with their respective versions: + * - `openjdk version "1.8.0_292"` → `8` + * - `openjdk version "11.0.11" 2021-04-20` → `11` + * - `java version "15" 2020-09-15` → `15` + */ +const JAVA_VERSION_PATTERN = /"(?:1\.)?(?\d+).*?"/