Skip to content

Commit

Permalink
Fix version returning null when running on Java 9
Browse files Browse the repository at this point in the history
A bug in JDK-9 [JDK-8190987](https://bugs.openjdk.java.net/browse/JDK-8190987) caused `Package.getImplementationVersion()` to return null. This commits adds code to read the Manifest file from the JAR to get the Implementation Version when it's not possible to retreive the version through the normal way.
  • Loading branch information
ifrins committed Feb 15, 2018
1 parent dfe66b5 commit 3158eaa
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion ktlint/src/main/kotlin/com/github/shyiko/ktlint/Main.kt
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import java.io.FileNotFoundException
import java.io.PrintStream
import java.io.PrintWriter
import java.math.BigInteger
import java.net.URL
import java.net.URLDecoder
import java.nio.file.Path
import java.nio.file.Paths
Expand All @@ -52,6 +53,7 @@ import java.util.concurrent.Future
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import java.util.jar.Manifest
import kotlin.system.exitProcess

object Main {
Expand Down Expand Up @@ -220,7 +222,7 @@ ${ByteArrayOutputStream().let { this.printUsage(it); it }.toString().trimEnd().s
fun main(args: Array<String>) {
parseCmdLine(args)
if (version) {
println(javaClass.`package`.implementationVersion)
println(version())
exitProcess(0)
}
if (installGitPreCommitHook) {
Expand Down Expand Up @@ -430,6 +432,21 @@ ${ByteArrayOutputStream().let { this.printUsage(it); it }.toString().trimEnd().s
}
}

private fun version() = javaClass.`package`.implementationVersion ?: guessVersion()

private fun guessVersion(): String? {
//HACK: Workaround for https://bugs.openjdk.java.net/browse/JDK-8190987
val classFile = javaClass.simpleName + ".class"
val classPath = javaClass.getResource(classFile).toString()
if (!classPath.startsWith("jar")) return null

val manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"
val manifest = Manifest(URL(manifestPath).openStream())
val attributes = manifest.mainAttributes

return attributes.getValue("Implementation-Version")
}

private fun fileSequence() =
when {
patterns.isEmpty() ->
Expand Down

0 comments on commit 3158eaa

Please sign in to comment.