Skip to content

Commit dc81e35

Browse files
committed
feat: detect wrong java version in application runtime and give better user feedback
1 parent a00ebf6 commit dc81e35

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

app/build.gradle

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,44 @@ dependencies {
1919
implementation project(':provisioner')
2020
}
2121

22+
import org.gradle.api.GradleException
23+
24+
def javaExtension = extensions.getByType(JavaPluginExtension)
25+
def requiredMajor = javaExtension.toolchain.languageVersion.map { it.asInt() }.get()
26+
27+
tasks.named('startScripts', CreateStartScripts).configure {
28+
doLast {
29+
def unixMarker = 'exec "$JAVACMD" "$@"'
30+
def windowsMarker = '"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %SPOTLESS_OPTS% -classpath "%CLASSPATH%" com.diffplug.spotless.cli.SpotlessCLI %*'
31+
32+
if (!unixScript.text.contains(unixMarker)) {
33+
throw new GradleException("Unable to patch Unix launcher: '${unixMarker}' not found.")
34+
}
35+
if (!windowsScript.text.contains(windowsMarker)) {
36+
throw new GradleException("Unable to patch Windows launcher: '${windowsMarker}' not found.")
37+
}
38+
39+
unixScript.text = unixScript.text.replace(unixMarker, """
40+
spotlessCheckJavaVersion() {
41+
local current=\$("\$JAVACMD" -version 2>&1 | awk -F[\\".] 'NR==1 {print \$2}')
42+
if [ "\$current" -lt $requiredMajor ]; then
43+
echo "Spotless CLI requires Java $requiredMajor or newer but found \$current. Make sure to install Java >= $requiredMajor and add it to the path or set JAVA_HOME env variable." >&2
44+
exit 1
45+
fi
46+
}
47+
spotlessCheckJavaVersion
48+
$unixMarker""")
49+
50+
windowsScript.text = windowsScript.text.replace(windowsMarker, """
51+
for /f "tokens=3 delims=." %%i in ('"%JAVA_EXE%" -version 2^>^&1 ^| findstr /r "[0-9][0-9]*\\.[0-9][0-9]*.*"') do set CURRENT_JAVA_MAJOR=%%i
52+
if %CURRENT_JAVA_MAJOR% LSS $requiredMajor (
53+
echo Spotless CLI requires Java $requiredMajor or newer but found %CURRENT_JAVA_MAJOR%. Make sure to install Java >= $requiredMajor and add it to the path or set JAVA_HOME env variable. >&2
54+
exit /b 1
55+
)
56+
$windowsMarker""")
57+
}
58+
}
59+
2260
application {
2361
mainClass = 'com.diffplug.spotless.cli.SpotlessCLI'
2462
applicationName = 'spotless'

0 commit comments

Comments
 (0)