Last active
February 13, 2017 07:49
-
-
Save benweidig/cf7836d8bc4e75425b9e450d4b474a10 to your computer and use it in GitHub Desktop.
(Blog) Java for shell scripting
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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