Skip to content

Instantly share code, notes, and snippets.

@raymyers
Last active December 21, 2015 11:19
Show Gist options
  • Save raymyers/6298009 to your computer and use it in GitHub Desktop.
Save raymyers/6298009 to your computer and use it in GitHub Desktop.
Gradle task that will fail if there are compile dependencies that require Java > 5.
task checkCompileDependenciesJava5Compatibility << {
configurations.compile.each { dep ->
def failureReason
zipTree(dep).matching { include("**/*.class") }.visit { fileDetails ->
if (!fileDetails.isDirectory()) {
def stream = fileDetails.file.newDataInputStream()
def magic1 = stream.readUnsignedShort()
def magic2 = stream.readUnsignedShort()
stream.skipBytes(2); // minor version
def majorVersion = stream.readUnsignedShort()
def javaVersion = majorVersion - 44
if (Long.toHexString(magic1) + Long.toHexString(magic2) != "cafebabe") {
println "Warning: bad magic number for ${fileDetails.name} in ${dep.name}"
}
if (javaVersion > 5) {
// Throwing exception directly from here will show a 'cannot open ZIP' message.
failureReason = "Dependency has class with Java version $javaVersion, max allowed is 5: ${fileDetails.name} in ${dep.name}"
}
fileDetails.stopVisiting();
stream.close()
}
}
if (failureReason) {
throw new GradleException(failureReason)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment