Fill array/args programmatically in Groovy/Gradle - gradle

I am trying to fix the args-argument for the executing programm for this Gradle task:
task generateResources(type: JavaExec) {
group = 'build'
description = 'Generate resource bundle from excel file'
mainClass.set('com.project.MainClass')
ext {
destDir = ''
sourceFile = ''
isDir = false
setInputDir = { input ->
xlxsTree = fileTree(input).matching { include '*.xls' }
xlxsTree.files.each {
args[1] = "$it" //how can I add all matching files???
}
}
setOutput = { output ->
outputs.dir(output)
destDir = output
args[0] = destDir
}
}
setInputDir("${project.projectDir}\\src\\main\\resources\\properties")
setOutput("${project.buildDir}\\resources\\generatedProperties")
logging.captureStandardOutput LogLevel.INFO
onlyIf {
!sourceFile.empty
}
classpath = project.configurations.resbundles
doFirst {
args args
jvmArgs '-Dfile.encoding=ISO-8859-15'
}
The args-argument in doLast{} should contain all file paths ending with .xls, e. g. ["C:\...\src\main\resources\properties\destdir", "C:\...\resources\generatedProperties\file1", "C:\...\resources\generatedProperties\file2"].
My approach is not working at all, I just tried to make it compile for at least one input file.

Related

Skipping task as it has no source files and no previous output files

This is my build.gradle which has three tasks (one for downloading the zip, one for unzipping it and other for executing the sh file). These tasks are dependent on each other. I am using Gradle 6. As these are dependent tasks I have used following command:
gradlew C
I get the error:
Skipping task 'B' as it has no source files and no previous output files.
build.gradle:
task A {
description = 'Rolls out new changes'
doLast {
def url = "https://${serverName}/xxx/try.zip"
def copiedZip = 'build/newdeploy/try.zip'
logger.lifecycle("Downloading $url...")
file('build/newdeploy').mkdirs()
ant.get(src: url, dest: copiedZip, verbose: true)
}
}
task B (type: Copy, dependsOn: 'A') {
doLast {
def zipFile = file('build/newdeploy/try.zip')
def outputDir = file("build/newdeploy")
from zipTree(zipFile)
into outputDir
}
}
task C (type: Exec, dependsOn: 'B') {
doLast {
workingDir 'build/newdeploy/try/bin'
executable 'sh'
args arguments, url
ext.output = { return standardOutput.toString() }
}
}
I tried following and it worked. Rather than adding a separate task to copy, added the copy function in the task A itself
task A {
description = 'Rolls out new changes'
doLast {
def url = "https://${serverName}/xxx/try.zip"
def copiedZip = 'build/newdeploy/try.zip'
logger.lifecycle("Downloading $url...")
file('build/newdeploy').mkdirs()
ant.get(src: url, dest: copiedZip, verbose: true)
def outputDir = file("build/newdeploy")
copy {
from zipTree(zipFile)
into outputDir
}
}
}
task C (type: Exec, dependsOn: 'A') {
doLast {
workingDir 'build/newdeploy/try/bin'
executable 'sh'
args arguments, url
ext.output = { return standardOutput.toString() }
}
}

Gradle zip task with lazy include property includes itself

Hi I got this zip task which works great:
def dir = new File("${projectDir.parentFile}/test/")
task testZip(type: Zip) {
from dir
destinationDirectory = dir
include 'toast/**'
archiveFileName = 'test.zip'
}
but then when I make the include property lazy (because I need to in my real case)
def dir = new File("${projectDir.parentFile}/test/")
task testZip(type: Zip) {
from dir
destinationDirectory = dir
include {
'toast/**'
}
archiveFileName = 'test.zip'
}
then it creates a zip that includes everything in the folder, (so the generated archive too). In this test case the inner zip is just corrupted (doesn't run infinitely) but in the real world case it does make an infinite zip. (Not sure why, maybe my best case has too few or small files). Either way the test case shows the problem, the generated zip contains a zip even though it should only contain the toast directory and all of its content.
How do I fix this? I need a lazy include because the directory I want to include is computed by other tasks. I get the exact same problem with Tar except it refuses to create the archive since it includes itself.
Using exclude '*.zip' is a dumb workaround which makes the archive include other folders I don't want. I only want to include a specific folder, lazyly.
Here's what the monster looks like in the real world case. I basically need to retrieve the version of the project from Java to then use that version to name the folders I'm packaging. (Making a libGDX game and packaging it with a jre using packr). The problematic tasks are 'makeArchive_' + platform.
String jumpaiVersion;
task fetchVersion(type: JavaExec) {
outputs.upToDateWhen { jumpaiVersion != null }
main = 'net.jumpai.Version'
classpath = sourceSets.main.runtimeClasspath
standardOutput new ByteArrayOutputStream()
doLast {
jumpaiVersion = standardOutput.toString().replaceAll("\\s+", "")
}
}
def names = [
'win64' : "Jumpai-%%VERSION%%-Windows-64Bit",
'win32' : "Jumpai-%%VERSION%%-Windows-32Bit",
'linux64' : "Jumpai-%%VERSION%%-Linux-64Bit",
'linux32' : "Jumpai-%%VERSION%%-Linux-32Bit",
'mac' : "Jumpai-%%VERSION%%-Mac.app"
]
def platforms = names.keySet() as String[]
def jdks = [
'win64' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-win_x64.zip',
'win32' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-win_i686.zip',
'linux64' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-linux_x64.tar.gz',
'linux32' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-linux_i686.tar.gz',
'mac' : 'https://cdn.azul.com/zulu/bin/zulu9.0.7.1-jdk9.0.7-macosx_x64.zip'
]
def formats = [
'win64' : 'ZIP',
'win32' : 'ZIP',
'linux64' : 'TAR_GZ',
'linux32' : 'TAR_GZ',
'mac' : 'ZIP'
]
File jdksDir = new File(project.buildscript.sourceFile.parentFile.parentFile, 'out/jdks')
File gameJar = new File("${projectDir.parentFile}/desktop/build/libs/Jumpai.jar")
File gameData = new File("${projectDir.parentFile}/desktop/build/libs/Jumpai.data")
File packrDir = new File("${projectDir.parentFile}/out/packr/")
File minimalTmpDir = new File("${projectDir.parentFile}/desktop/build/libs/minimal-tmp")
task minimizeGameJar {
dependsOn ':desktop:dist'
doFirst {
minimalTmpDir.mkdirs()
copy {
from zipTree(gameJar)
into minimalTmpDir
}
for(file in minimalTmpDir.listFiles())
if(file.getName().contains("humble"))
file.delete()
}
}
task makeMinimal(type: Zip) {
dependsOn minimizeGameJar
dependsOn fetchVersion
from minimalTmpDir
include '**'
archiveFileName = provider {
"Jumpai-${->jumpaiVersion}-Minimal.jar"
}
destinationDir packrDir
doLast {
minimalTmpDir.deleteDir()
}
}
task copyGameJar(type: Copy) {
outputs.upToDateWhen { gameData.exists() }
dependsOn ':desktop:dist'
from gameJar.getAbsolutePath()
into gameData.getParentFile()
rename("Jumpai.jar", "Jumpai.data")
}
task setWindowsIcons(type: Exec) {
dependsOn fetchVersion
workingDir '.'
commandLine 'cmd', '/c', 'set_windows_icons.bat', "${->jumpaiVersion}"
}
for(platform in platforms) {
task("getJdk_" + platform) {
String url = jdks[platform]
File jdkDir = new File(jdksDir, platform + "-jdk")
File jdkFile = new File(jdkDir, url.split("/").last())
outputs.upToDateWhen { jdkFile.exists() }
doFirst {
if(!jdkDir.exists())
jdkDir.mkdirs()
if(jdkFile.exists())
{
println jdkFile.getName() + " is already present"
return
}
else
{
println "Downloading " + jdkFile.getName()
new URL(url).withInputStream {
i -> jdkFile.withOutputStream { it << i }
}
}
for(file in jdkDir.listFiles()) {
if(file.equals(jdkFile))
continue
if(file.isFile()) {
if (!file.delete())
println "ERROR: could not delete " + file.getAbsoluteFile()
} else if(!file.deleteDir())
println "ERROR: could not delete content of " + file.getAbsoluteFile()
}
if(url.endsWith(".tar.gz"))// don't mix up archive type of what we downloaded vs archive type of what we compress (in formats)
{
copy {
from tarTree(resources.gzip(jdkFile))
into jdkDir
}
}
else if(url.endsWith(".zip"))
{
copy {
from zipTree(jdkFile)
into jdkDir
}
}
}
}
File packrInDir = new File(packrDir, platform)
String platformRawName = names[platform]
task("packr_" + platform, type: JavaExec) {
outputs.upToDateWhen { new File(packrDir, platformRawName.replace("%%VERSION%%", jumpaiVersion)).exists() }
dependsOn fetchVersion
dependsOn copyGameJar
dependsOn 'getJdk_' + platform
main = 'com.badlogicgames.packr.Packr'
classpath = sourceSets.main.runtimeClasspath
args 'tools/res/packr_config/' + platform + '.json'
workingDir = project.buildscript.sourceFile.parentFile.parentFile
doLast {
File packrOutDir = new File(packrDir, platformRawName.replace("%%VERSION%%", jumpaiVersion));
packrOutDir.deleteDir()
if(packrOutDir.exists())
{
println "ERROR Could not delete packr output " + packrOutDir.getAbsolutePath()
return
}
if(!packrInDir.renameTo(packrOutDir))
println "ERROR Could not rename packr output dir for " + packrInDir.getName()
}
}
if(formats[platform] == 'ZIP')
{
task('makeArchive_' + platform, type: Zip) {
if(platform.contains("win"))
dependsOn setWindowsIcons
dependsOn fetchVersion
dependsOn 'packr_' + platform
from packrDir
destinationDirectory = packrDir
include {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + "/"
}
archiveFileName = provider {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + ".zip"
}
}
}
else if(formats[platform] == 'TAR_GZ')
{
task('makeArchive_' + platform, type: Tar) {
dependsOn 'packr_' + platform
from packrDir
destinationDirectory = packrDir
include {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + '/**'
}
archiveFileName = provider {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + ".tar.gz"
}
extension 'tar'
compression = Compression.GZIP
}
}
else
println 'Unsupported format for ' + platform
}
task deploy {
dependsOn makeMinimal
for(platform in platforms)
dependsOn 'makeArchive_' + platform
}
How do I fix this? I need a lazy include because the directory I want to include is computed by other tasks. I get the exact same problem with Tar except it refuses to create the archive since it includes itself.
You can get what you want by using the doFirst method and modifiying the tasks properties with the passed action.
task('makeArchive_' + platform, type: Zip) {
if(platform.contains("win"))
dependsOn setWindowsIcons
dependsOn fetchVersion
dependsOn 'packr_' + platform
from packrDir
destinationDirectory = packrDir
archiveFileName = provider {
platformRawName.replace("%%VERSION%%", jumpaiVersion) + ".zip"
}
doFirst {
def includeDir = platformRawName.replace("%%VERSION%%", jumpaiVersion)
// Include only files and directories from 'includeDir'
include {
it.relativePath.segments[ 0 ].equalsIgnoreCase(includeDir)
}
}
}
Please have also a look at this answer to a similar question. My solution is just a workaround. If you know your version at configuration phase you can achieve what you want more easily. Writing your own custom tasks or plugins can also help to clean up your build script.

Custom gradle script for Detekt with multi-module project

I'm trying to create a custom gradle task that will run the different detekt profiles I have setup.
Here is my Detekt config:
detekt {
version = "1.0.0.RC6-4"
profile("main") {
input = "$projectDir/app/src/main/java"
output = "$projectDir/app/build/reports/detekt"
config = "$projectDir/config/detekt-config.yml"
}
profile("app") {
input = "$projectDir/app/src/main/java"
output = "$projectDir/app/build/reports/detekt"
}
profile("database") {
input = "$projectDir/database/src/main/java"
output = "$projectDir/database/build/reports/detekt"
}
profile("logging") {
input = "$projectDir/logging/src/main/java"
output = "$projectDir/logging/build/reports/detekt"
}
profile("network") {
input = "$projectDir/network/src/main/java"
output = "$projectDir/network/build/reports/detekt"
}
}
And here is what I'm trying for the custom gradle task:
task detektAll {
group = 'verification'
dependsOn 'detektCheck'
doLast {
println "\n##################################################" +
"\n# Detekt'ed all the things! Go you! #" +
"\n##################################################"
}
}
I need to add -Ddetekt.profile=app and the others for each profile.
How can I accomplish this?

gradle processResources: file path conversion

Grade: how to customize processResources to change the resource file path in the jar?
For example:
foo/a.xml --> foo/bar/a.xml
something similar to:
copy tree with gradle and change structure?
copy {
from("${sourceDir}") {
include 'modules/**/**'
}
into(destDir)
eachFile {details ->
// Top Level Modules
def targetPath = rawPathToModulesPath(details.path)
details.path = targetPath
}
}
....
def rawPathToModulesPath(def path) {
// Standard case modules/name/src -> module-name/src
def modified=path.replaceAll('modules/([^/]+)/.*src/(java/)?(.*)', {"module-${it[1]}/src/${it[3]}"})
return modified
}
How to add this in processResources? Thanks.
processResources is a task of type Copy. Therefore you should be able to do
processResources {
eachFile {details ->
// Top Level Modules
def targetPath = rawPathToModulesPath(details.path)
details.path = targetPath
}
}

Suppress Gradle's JavaExec output

I have gradle code below and I don't know how to avoid huge output generated by JavaExec task. I haven't found any option of JavaExec for it. If anyone knows better way of ignoring it, please share it.
def getStubOutput() {
return new FileOutputStream(new File("${buildDir}/temp"))
}
configure(project(':jradius:dictionary-min')) {
evaluationDependsOn(':jradius')
sourceSets {
main {
java {
srcDir "${projectDir}/target/dictionary-src"
}
}
}
dependencies {
compile project(':jradius:core')
}
task genSources(type: JavaExec) {
main = 'net.jradius.freeradius.RadiusDictionary'
classpath configurations.all
args = ["net.jradius.dictionary", "${projectDir}/../freeradius/dict-min", "${projectDir}/target/dictionary-src"]
maxHeapSize = "800m"
standardOutput = getStubOutput()
}
jar {
archiveName = "jradius-dictionary-min-1.1.5-SNAPSHOT.jar"
}
genSources.dependsOn ':jradius:cloneJradius'
compileJava.dependsOn genSources
}
I simply use a dummy OutputStream that does nothing in its write method:
def dummyOutputStream = new OutputStream() {
#Override
public void write(int b) {}
}
exec {
executable = name
standardOutput = dummyOutputStream
errorOutput = dummyOutputStream
ignoreExitValue = true
}
A great solution I came across is to modify the logging level of the task. If you set it to INFO, then it will squelch all the output of that task, unless gradle is run with --info.
Alternatively, you can set the level to LogLevel.QUIET, which will completely silence it.
task chatty(type: Exec) {
....
logging.captureStandardOutput LogLevel.INFO
}
As in the comment I thought that standardOutput can be set to null but the following piece of code (taken from: org.gradle.process.internal.AbstractExecHandleBuilder) shows that's not possible:
public AbstractExecHandleBuilder setStandardOutput(OutputStream outputStream) {
if (outputStream == null) {
throw new IllegalArgumentException("outputStream == null!");
}
this.standardOutput = outputStream;
return this;
}
What You can do is to redirect the output to temporary file (file will be deleted!) with this oneliner:
task genSources(type: JavaExec) {
main = 'net.jradius.freeradius.RadiusDictionary'
classpath configurations.all
args = ["net.jradius.dictionary", "${projectDir}/../freeradius/dict-min", "${projectDir}/target/dictionary-src"]
maxHeapSize = "800m"
standardOutput = { def f = File.createTempFile('aaa', 'bbb' ); f.deleteOnExit(); f.newOutputStream() }()
}
or if You'd like to save this output for further reading:
task genSources(type: JavaExec) {
main = 'net.jradius.freeradius.RadiusDictionary'
classpath configurations.all
args = ["net.jradius.dictionary", "${projectDir}/../freeradius/dict-min", "${projectDir}/target/dictionary-src"]
maxHeapSize = "800m"
standardOutput = new File(project.buildDir, 'radius.log').newOutputStream()
}
The last option is to add apache commons-io to script dependencies and set standardOutput to NullOutputStream. In can be done as follows:
import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'commons-io:commons-io:2.4'
}
}
task genSources(type: JavaExec) {
main = 'net.jradius.freeradius.RadiusDictionary'
classpath configurations.all
args = ["net.jradius.dictionary", "${projectDir}/../freeradius/dict-min", "${projectDir}/target/dictionary-src"]
maxHeapSize = "800m"
standardOutput = NULL_OUTPUT_STREAM
}
That's all that comes to my head.
This disables the standard output from a javaExec task:
task myCustomTask(type: javaExec) {
standardOutput = new ByteArrayOutputStream()
classpath = ...
main = ...
args ....
}

Resources