I am trying to write some key-value pairs to a properties file in a gradle task. I looked up that Gradle provides an api WriteProperties for that, but I was unable to use it.
I tried different approaches (I am learning Gradle, so I don't know if I used some incorrect syntax):
1.
task myTask {
doLast {
WriteProperties {
outputFile = file 'prop.properties'
encoding = 'UTF-8'
properties = [TEST:42]
}
}
}
task myTask {
doLast {
def writer by register(WriteProperties.class) {
outputFile = file 'prop.properties'
encoding = 'UTF-8'
properties = [TEST:42]
}
}
}
task myTask {
doLast {
// Other stuff
}
}
task writeProperty(type: WriteProperties) {
outputFile = file 'prop.properties'
encoding = 'UTF-8'
properties = [TEST:42]
}
writeProperty.dependsOn myTask
task myTask {
doLast {
// Other stuff
}
finalizedBy writeProperty
}
task writeProperty(type: WriteProperties) {
outputFile = file 'prop.properties'
encoding = 'UTF-8'
properties = [TEST:42]
}
task myTask {
doLast {
// Other stuff
}
}
class MyPlugin implements Plugin<Project>{
void apply(Project project) {
project.task('writeProperty') {
WriteProperties {
outputFile = file 'prop.properties'
encoding = 'UTF-8'
properties = [TEST:42]
}
}
}
}
apply plugin: MyPlugin
writeProperty.dependsOn myTask
None of them created a file with the values. Is there some other way to do it? I wanted to know the proper way of using the WriteProperties api, since the documentation did now have any helpful examples.
I found solutions with java syntax to create Properties() object and writing to file, but none with this api.
I'm creating a property file like so, using pure Gradle/Groovy:
file "$buildDir/prop.properties" write [ TEST:42 ].collect{ k, v -> "$k=$v" }.join( '\n' )
OR
file "$buildDir/prop.properties" withWriter{ out ->
[ TEST:42 ].each{ k, v -> out << k << '=' << v << '\n' }
}
Related
I have a Gradle build file which uses ProtoBuffer plugin and runs some tasks. At some point some tasks are run for some files, which are inputs to tasks.
I want to modify the set of files which is the input to those tasks. Say, I want the tasks to be run with files which are listed, one per line, in a particular file. How can I do that?
EDIT: Here is a part of rather big build.gradle which provides some context.
configure(protobufProjects) {
apply plugin: 'java'
ext {
protobufVersion = '3.9.1'
}
dependencies {
...
}
protobuf {
generatedFilesBaseDir = "$projectDir/gen"
protoc {
if (project.hasProperty('protocPath')) {
path = "$protocPath"
}
else {
artifact = "com.google.protobuf:protoc:$protobufVersion"
}
}
plugins {
...
}
generateProtoTasks {
all().each { task ->
...
}
}
sourceSets {
main {
java {
srcDirs 'gen/main/java'
}
}
}
}
clean {
delete protobuf.generatedFilesBaseDir
}
compileJava {
File generatedSourceDir = project.file("gen")
project.mkdir(generatedSourceDir)
options.annotationProcessorGeneratedSourcesDirectory = generatedSourceDir
}
}
The question is, how to modify the input file set for existing task (which already does something with them), not how to create a new task.
EDIT 2: According to How do I modify a list of files in a Gradle copy task? , it's a bad idea in general, as Gradle makes assumptions about inputs and outputs dependencies, which can be broken by this approach.
If you would have added the gradle file and more specific that would have been very helpful. I will try to give an example from what I have understood:
fun listFiles(fileName: String): List<String> {
val file = file(fileName).absoluteFile
val listOfFiles = mutableListOf<String>()
file.readLines().forEach {
listOfFiles.add(it)
}
return listOfFiles
}
tasks.register("readFiles") {
val inputFile: String by project
val listOfFiles = listFiles(inputFile)
listOfFiles.forEach {
val file = file(it).absoluteFile
file.readLines().forEach { println(it) }
}
}
Then run the gradle like this: gradle -PinputFile=<path_to_the_file_that_contains_list_of_files> readFiles
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.
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 copySpec include closure not working:
def fileList = ["hello/world.xml"]
task foo(type: Copy) {
from (zipTree("/path/a.zip")) {
include { elem ->
fileList.contains(elem.path)
}
}
}
The a.zip contains "hello/world.xml".
Message:
Skipping task 'foo' as it has no source files and no previous output files.
A copySpec closure needs to be used with a copy task.
Your code is just the copy task, which requires a destination to copy into.
Your code should be more like this:
def fileList = ["hello/world.xml"]
def filesToCopy = copySpec {
from (zipTree("/path/a.zip")) {
include { elem ->
fileList.contains(elem.path)
}
}
}
task foo(type: Copy) {
into 'build/target/docs'
with filesToCopy
}
See the API for more detail: https://docs.gradle.org/3.3/dsl/org.gradle.api.tasks.Copy.html
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 ....
}