Skip to content

Instantly share code, notes, and snippets.

@benweidig
Last active February 13, 2017 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benweidig/cf7836d8bc4e75425b9e450d4b474a10 to your computer and use it in GitHub Desktop.
Save benweidig/cf7836d8bc4e75425b9e450d4b474a10 to your computer and use it in GitHub Desktop.
(Blog) Java for shell scripting
ext.mainClass = "com.example.Main"
import java.nio.file.Files
import java.nio.file.Paths
task shellScript(type: Jar) {
// Create fat Jar
doFirst {
from {
(configurations.runtime).collect {
it.isDirectory() ? it : zipTree(it)
}
}
}
// Set entry point
manifest {
attributes("Main-Class": mainClass)
}
// Connect with actual Jar task
with jar
// Build single executable file
doLast {
// Set name, location and make sure the location exists
def executableName = jar.archiveName.replace(".jar", "")
def executablePath = Paths.get(project.buildDir.getAbsolutePath(), "executable", executableName)
Files.createDirectories(executablePath.getParent())
// Write sheband to file. It will be overwritten.
def shebang = "#!/usr/bin/java -jar\n"
Files.write(executablePath, shebang.getBytes());
// Write fat Jar file content to the script
def jarPath = Paths.get(jar.archivePath.getAbsolutePath())
def jarBytes = java.nio.file.Files.readAllBytes(jarPath)
Files.write(executablePath, jarBytes, java.nio.file.StandardOpenOption.APPEND)
// Make it executable
executablePath.toFile().setExecutable(true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment