Skip to content

Commit

Permalink
Fix Java version check failing when it can only find a major version
Browse files Browse the repository at this point in the history
Fixes #52
  • Loading branch information
niklashigi committed Apr 28, 2021
1 parent bf33e5e commit 8d9d537
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/utils/get-java-version.ts
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -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\.)?(?<major>\d+).*?"/

0 comments on commit 8d9d537

Please sign in to comment.