What does `configurations.<config>` allow to iterate over? - groovy

In the gradle documentation in the section about groovy basic, we have an example:
configurations.runtime.each { File f -> println f }
What the code was supposed to print? I write the simple build script containig this line:
apply plugin: 'java'
configurations.runtime.each { File f -> println f }
dependencies{
project(':api') //This's just a project declared in the settings.gradle
}
and what the gradle check does is print nothing. What does it mean actually?

In general this will iterate over all files resolved for the specified configuration. In your case this configuration is runtime. As you havn't declared any runtime dependencies, no file is printed. Vahid is right that you should put this kind of statements into a task, otherwise it will be called at gradles configuration time on every build invocation, even when just asking for available tasks via "gradle tasks".

you should overwrite gradle check method:
check << {
configurations.runtime.each { File f -> println f }
}
then run
gradle check

Related

How to clear specific gradle cache files when running the "Clean project" command?

I have added the following task in my project's build.gradle file:
task('clearLibCache', type: Delete, group: 'MyGroup',
description: "Deletes any cached artifacts with the domain of com.test in the Gradle or Maven2 cache directories.") << {
def props = project.properties
def userHome = System.getProperty('user.home')
def domain = props['domain'] ?: 'com.test'
def slashyDomain = domain.replaceAll(/\./, '/')
file("${userHome}/.gradle/caches").eachFile { cacheFile ->
if (cacheFile.name =~ "^$domain|^resolved-$domain") delete cacheFile.path
}
delete "${userHome}/.m2/repository/$slashyDomain"
}
I'd like this task to be executed when I hit the "Clean project" menu, and only in this case.
How to do that ?
That "Clean project" menu item under the hood appears to do a couple of things (based on the output of the Gradle Console window when you click it):
A gradle clean, the equivalent of calling ./gradlew clean
Generate sources and dependencies for a debug build, including a mockable Android sources jar if needed.
I would make your task a dependency for the Gradle clean task, so that whenever the project is cleaned, this task is also invoked. This can be achieved by adding the line clean.dependsOn clearLibCache in your build.gradle after you declare the task.

Orchestrating Gradle build invocations with custom tasks

I’m trying to define two new Gradle tasks, buildAll and pubLocal, to run other tasks in a specific order.
When gradle buildAll is invoked, I want Gradle to do the same thing as if I had executed gradle clean build writePom (see below for writePom).
When gradle pubLocal is executed, I want Gradle to do the same thing as if gradle buildAll install had been executed.
Here’s my best attempt thus far:
// build.gradle
task writePom << {
pom {
project {
groupId 'mygroup'
artifactId 'mylib'
version version
inceptionYear '2015'
licenses {
license {
name 'Blah'
url 'blah'
distribution 'blah'
}
}
}
}.writeTo("build/libs/pom.xml")
}
task buildAll(dependsOn: clean, build, writePom)
task pubLocal(dependsOn: buildAll, install)
When I run gradle buildAll on this, I get:
myuser#mymachine:~/tmp/myapp$./gradlew buildAll
FAILURE: Build failed with an exception.
* Where:
Build file '/Users/myuser/tmp/myapp/build.gradle' line: 67
* What went wrong:
A problem occurred evaluating root project 'myapp'.
> Could not find method buildAll() for arguments [{dependsOn=task ':clean'}, task ':build', task ':writePom'] on root project 'myapp'.
Any ideas as to where I’m going awry?
This may be a left-over from copy-pasting, but your strings are not quoted consistently using standard single- or double-quotes. Example:
}.writeTo(“build/libs/pom.xml")
does not quote the string properly, as it opens with the “ character instead of ". Same with the single-quotes above it.
You can see from the way your code is highlighted, that everything in red is interpreted as a string. If this is the case in your actual code, the buildAll and pubLocal tasks will not be recognized, as they are part of a string rather than code.
UPDATE:
Since the above answer is irrelevant now, here is another possibility. The error message shows that only the "clean" task is listed in the dependsOn parameter. The buildAll task dependencies should be declared like this:
task buildAll(dependsOn: [clean, build, writePom])
Similar with the pubLocal task.
I'm using Gradle 2.4. The following file includes the Maven plugin, uses a list [] in the dependsOn, and ensures that clean must be executed before build:
apply plugin: 'maven'
task writePom << {
pom {
project {
groupId 'mygroup'
artifactId 'mylib'
version version
inceptionYear '2015'
licenses {
license {
name 'Blah'
url 'blah'
distribution 'blah'
}
}
}
}.writeTo("build/libs/pom.xml")
println "TRACER writePom"
}
task clean << { println "TRACER clean" }
task build << { println "TRACER build" }
build.mustRunAfter clean
task install << { println "TRACER install" }
task buildAll(dependsOn: [clean, build, writePom])
task pubLocal(dependsOn: [buildAll, install])
I get this output (minus Gradle 3 warnings):
bash-3.2$ gradle buildAll
:clean
TRACER clean
:build
TRACER build
:writePom
TRACER writePom
:buildAll
BUILD SUCCESSFUL
and this:
bash-3.2$ gradle pubLocal
:clean
TRACER clean
:build
TRACER build
:writePom
TRACER writePom
:buildAll
:install
TRACER install
:pubLocal
BUILD SUCCESSFUL

Copy and .# in file name

I faced with one gradle issue (or may be groovy related)
When I trying to copy file with .# in its name nothing is happened.
Example:
task c(type: Copy) {
from (".#webclasspath#")
into "destdir"
}
Please, could you provide way how to process such files?
seems that there is a bug in gradle, ant works just fine
task c_ant << {
ant.copy(file : '.#webclasspath#', todir : 'destdir')
}

gradle.buildStarted not triggered

I am not able to have buildStarted triggered in my gradle build, not sure what I am doing wrong.
I have a root project gradle file like this
version '1.0'
buildscript {
repositories {
maven { url 'http://repo.jfrog.org/artifactory/gradle-plugins' }
}
dependencies {
classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.1.0')
}
}
gradle.buildStarted {
println "buildStart"
}
gradle. buildFinished {
println "buildFinished"
}
apply plugin: 'groovy'
apply plugin: 'maven'
.........
buildFinished works as I am able to see corresponding println but buildStarted never seem to get triggered.
EDIT
Include init.gradle that uses build listener
class MyBuildAdapter extends BuildAdapter {
void buildStarted(Gradle gradle) {
println "buildStarted"
}
}
gradle.addBuildListener new MyBuildAdapter()
The problem is that the buildStarted event occurs before you get a chance to register a callback in a build script. You'll have to use one of the other hooks. For details, see Gradle.addBuildListener in the Javadoc.
I had the same issue in a custom plugin I wrote, and found that only projectsEvaluated callback is the one that gets executed before buildFinished in the BuildListener.
It's been 7 years, and finally Gradle got around to admitting that it didn't make sense to have this method in the first place. It'll be removed in Gradle 7.
https://docs.gradle.org/6.5.1/userguide/upgrading_version_5.html#apis_buildlistener_buildstarted_and_gradle_buildstarted_have_been_deprecated

How can I create a pathing jar in Gradle

When running groovyc in a Windows env, I am running into issues due to the length of the classpath, in my situation. I would like to work around this by creating a pathing jar, and then put that jar on the cp. How can I create a pathing jar w/ all of the classpath entries specified automatically in gradle and then add that jar to the cp?
Here is a tested solution:
task pathingJar(type: Jar) {
appendix = "pathing"
doFirst {
manifest {
attributes "Class-Path": configurations.compile.files.join(" ")
}
}
}
compileGroovy {
dependsOn(pathingJar)
classpath = files(pathingJar.archivePath)
}
Depending on your exact requirements, you might have to tweak this a bit. For example, if you have tests written in Groovy, you will also need a pathing Jar for the test compile class path. In this case you'll need to repeat above configuration as follows:
task testPathingJar(type: Jar) {
appendix = "testPathing"
doFirst {
manifest {
attributes "Class-Path": configurations.testCompile.files.join(" ")
}
}
}
compileTestGroovy {
dependsOn(testPathingJar)
classpath = files(testPathingJar.archivePath)
}
I finally got the "pathing jar" idea to work. I consider this to be a permanent workaround. This could be considered a solution if it is made part of gradle itself.
The original pathing jar code was provided by Peter, but it didn't work. The problem: classpath elements referenced in the pathing jar must be relative to the location of the pathing jar. So, this appears to work for me.
task pathingJar(type: Jar , dependsOn: 'cleanPathingJar') {
/**
* If the gradle_user_home env var has been set to
* C:\ on a Win7 machine, we may not have permission to write the jar to
* this directory, so we will write it to the caches subdir instead.
* This assumes a caches subdir containing the jars
* will always exist.
*/
gradleUserHome = new File(gradle.getGradleUserHomeDir(), "caches")
relativeClasspathEntries = configurations.compile.files.collect {
new File(gradleUserHome.getAbsolutePath()).toURI().
relativize(new File(it.getAbsolutePath()).toURI()).getPath()
}
appendix = "pathing"
destinationDir = gradleUserHome
doFirst {
manifest {
attributes "Class-Path": relativeClasspathEntries.join(" ")
}
}
}
compileGroovy {
dependsOn(pathingJar)
classpath = files(pathingJar.archivePath)
}
This is what helped me:
"The filename or extension is too long error" using gradle
In other words: use the com.github.ManifestClasspath plugin.
The other solutions did not work for me because the actual project main class ended up no being included in the classpath at execution time.

Resources