gradle execute task after build - gradle

I am building my project with gradle, with the following build.gradle file:
project('a'){
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'application'
buildDir = 'build'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
repositories {
mavenCentral()
}
dependencies {
compile 'org.slf4j:slf4j-api:1.7.7'
}
}
When I input the gradle build command, I want gradle to execute a task after the build.
I found a mustRunAfter on the Internet, and I have tried a variety of ways but failed.
Please tell me if you know how.

What you need is finalizedBy, see the following script:
apply plugin: 'java'
task finalize {
doLast {
println('finally!')
}
}
build.finalizedBy(finalize)
Here are the docs.

Nowadays you can use a BuildListener, it just works. Below is an example written in kotlin DSL
build.gradle.kts
plugins {
id("com.android.application")
id("kotlin-android")
id("kotlin-kapt")
}
android {
//[..]
project.gradle.addBuildListener(object : BuildListener {
override fun buildStarted(gradle: Gradle) {}
override fun settingsEvaluated(settings: Settings) {}
override fun projectsLoaded(gradle: Gradle) {}
override fun projectsEvaluated(gradle: Gradle) {}
override fun buildFinished(result: BuildResult) {
// add what you need to do here
println("finally!")
}
})
}
dependencies {
//[...]
}

Related

Gradle will not publish artifact?

Gradle v4.10.2
I’m building a Gradle Java plugin, and it builds. However when I run ./gradlew publish it does nothing, i.e., the artifact doesn’t get published. Here’s my build.gradle file (I have all the variables defined in my gradle.properties file). Also, if I just run ./gradlew publish w/o running ./gradlew build first, it doesn’t run the build phase. What am I missing in my build.gradle file? Thanks.
plugins {
id 'java'
id 'maven'
id 'maven-publish'
}
apply plugin: 'java'
apply plugin: 'maven'
apply plugin: 'maven-publish'
group=project.groupId
version = '0.0.1'
jar {
manifest {
attributes 'artifactId': project.artifactId,
'groupId': project.groupId,
'version': project.version
}
baseName artifactId
doLast {
println "artifactId: $project.artifactId\ngroupId: $project.groupId\nversion: $version"
}
}
dependencies {
compile gradleApi()
}
// For publishigh to S3 maven repo
publishing {
repositories {
maven {
url "s3://" + s3_bucket
credentials(AwsCredentials) {
accessKey AWS_ACCESS_KEY
secretKey AWS_SECRET_KEY
}
}
}
}
RTFM. I was missing the publications block inside the publishing block. Here’s the whole block
publishing {
publications {
myLibrary(MavenPublication) {
from components.java
}
}
repositories {
maven {
url "s3://" + s3_bucket
credentials(AwsCredentials) {
accessKey AWS_ACCESS_KEY
secretKey AWS_SECRET_KEY
}
}
}
}

Apply plugin configuration in init.gradle script

I want to install some packages locally for all my projects, e.g. dependency-analyse. But I need to actually configure the plugin - also in the init script.
initscript {
repositories {
jcenter()
}
dependencies {
classpath "ca.cutterslade.gradle:gradle-dependency-analyze:1.3.0"
}
}
allprojects {
apply plugin: ca.cutterslade.gradle.analyze.AnalyzeDependenciesPlugin
}
This init script works fine and applies the plugin, but unfortunately, the default setting is that the plugin fails the build. I would like to just log a warning.
For that I need to add configs:
analyzeClassesDependencies {
justWarn = true
}
analyzeTestClassesDependencies {
justWarn = true
}
but when I try to add it in the init.gradle file:
initscript {
repositories {
jcenter()
}
dependencies {
classpath "ca.cutterslade.gradle:gradle-dependency-analyze:1.3.0"
}
}
allprojects {
apply plugin: ca.cutterslade.gradle.analyze.AnalyzeDependenciesPlugin
analyzeClassesDependencies {
justWarn = true
}
analyzeTestClassesDependencies {
justWarn = true
}
}
I get an error:
FAILURE: Build failed with an exception.
* Where:
Initialization script '/Users/<my-user>/.gradle/init.gradle' line: 13
* What went wrong:
Could not find method analyzeClassesDependencies() for arguments [init_2y9p9if69e8553k9fsvzz4a28$_run_closure1$_closure2#3e17c37a] on root project 'my-project' of type org.gradle.api.Project.
Anybody an idea of how I can apply plugin configuration?
I tried the gradle forum but didn't get any answer, so I hope to get some more help here :)
AnalyzeDependenciesPlugin will add different tasks depending on which plugin is applied to your project. For example analyzeClassesDependencies and analyzeTestClassesDependencies will be declared only when java plugin is applied (see how this plugin is implemented here : https://github.com/wfhartford/gradle-dependency-analyze/blob/master/src/main/groovy/ca/cutterslade/gradle/analyze/AnalyzeDependenciesPlugin.groovy )
So you just need to apply java plugin before you apply the AnalyzeDependenciesPlugin in your allprojects configuration closure:
allprojects {
apply plugin: "java" // <= apply Java plugin here
apply plugin: ca.cutterslade.gradle.analyze.AnalyzeDependenciesPlugin
analyzeClassesDependencies {
justWarn = true
}
analyzeTestClassesDependencies {
justWarn = true
}
}

Control the gradle task execute order

I have a strange problem about gradle task recently.
Assume I have a simple gradle config as follows
apply plugin: "java"
apply plugin: "maven"
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "com.diffplug.gradle.spotless:spotless:2.0.0"
}
}
apply plugin: "com.diffplug.gradle.spotless"
spotless {
java {
eclipseFormatFile 'format.xml' // XML file dumped out by the Eclipse formatter
}
}
spotlessJavaCheck.dependsOn(processResources)
version = '1.0-SNAPSHOT'
I just want to set the depends on relationship for the spotless check. After I run a build, the error looks like this
> Could not find property 'spotlessJavaCheck' on root project 'gradle-helloworld'.
I have done something similar with other plugins, it works well, but not for this spotless plugin.
Br,
Tim
Spotless Gradle plugin does magic at configuration time.
You need to set the dependency after evaluation time, once the magic is done:
afterEvaluate {
tasks['spotlessJavaCheck'].dependsOn processResources
}

Gradle: buildscript's resolution strategy

Is it possible to set the resolution strategy for the builscript, so that the version of a gradle plugin can be set centrally? For example:
build.gradle:
buildscript {
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin'
}
}
apply from: 'common.gradle'
apply plugin: 'spring-boot'
dependencies {
...
}
common.gradle:
allprojects { project ->
buildscript {
repositories {
jcenter()
}
}
configurations.all {
resolutionStrategy {
eachDependency { details ->
if (details.requested.group == 'org.springframework.boot' and details.requested.name == 'spring-boot-gradle-plugin')
details.useVersion '1.3.1.RELEASE'
}
}
}
}
I've tried about 100 different variants of the above, all result in an error saying the spring boot gradle plugin version can't be resolved (which is still empty)
A slightly different approach to centrally set the plugin version: use init.gradle
In your init.gradle:
allprojects {
ext.springBootGradlePluginVersion = '1.3.1.RELEASE'
println "spring-boot-gradle-plugin version set in init.gradle to $springBootGradlePluginVersion"
}
Then in your individual projects:
buildscript {
dependencies {
classpath "org.springframework.boot:spring-boot-gradle-plugin:$springBootGradlePluginVersion"
}
}
apply from: 'common.gradle'
apply plugin: 'spring-boot'
You can either use a global init.gradle in your home folder, or invoke it per project while running gradle with the -I command line option.

Upload only war/jar files in gradle(restrict zip/tar generation and upload)

My build script is like as follows. I use gradle build command to build and gradle upload command to upload the artifact. My problem is a tar,zip file is also generated with this command and get uploaded. I dont want it. Only things I would like to get uploaded is 'jar' and 'war' files.
I have also a related question posted by me yesterday here.
More details(I have excluded some unwanted code)
build file in root
allprojects {
apply plugin: 'maven'
group = 'groupid'
version = '1.0-SNAPSHOT'
}
subprojects {
apply plugin: 'java'
sourceCompatibility = 1.7
targetCompatibility = 1.7
repositories {
maven {
credentials {
username "$nexusUser"
password "$nexusPass"
}
url "$nexusUrl"
}
}
uploadArchives {
repositories {
mavenDeployer {
repository(url: "$nexusSnapshotUrl") {
authentication(userName: "$nexusUser", password: "$nexusPass")
}
}
}
}
}
ext.comlib = [ // Groovy map literal
junit3: "junit:junit:3.8",
junit4: "junit:junit:4.9",
spring_core: "org.springframework:spring-core:3.1",
hibernate_validator : "org.hibernate:hibernate-validator:5.1.3.Final",
spring_core : "org.springframework.security:spring-security-core:4.0.2.RELEASE",
spring_security_web: "org.springframework.security:spring-security-web:4.0.2.RELEASE",
spring_security_config: "org.springframework.security:spring-security-config:4.0.2.RELEASE",
spring_boot_starter_test: "org.springframework.boot:spring-boot-starter-test:1.2.5.RELEASE",
spring_boot_starter_actuator: "org.springframework.boot:spring-boot-starter-actuator:1.2.5.RELEASE",
spring_boot_plugin_gradle: "org.springframework.boot:spring-boot-gradle-plugin:1.2.6.RELEASE",
asciidoctor_gradle_plugin: "org.asciidoctor:asciidoctor-gradle-plugin:1.5.1",
asciidoctor_pdf_plugin: "org.asciidoctor:asciidoctorj-pdf:1.5.0-alpha.9"/*,
sl4j_api: "org.slf4j:slf4j-api:1.7.12",
sl4j_log4j: "org.slf4j:slf4j-log4j12:1.7.12",
logback_classic: "ch.qos.logback:logback-classic:1.1.3",
logback_core: "ch.qos.logback:logback-core:1.1.3"*/
]
build file in sub module
apply plugin: 'spring-boot'
group = 'com.group.id'
apply from: "../build.gradle"
apply plugin: 'org.asciidoctor.gradle.asciidoctor'
apply plugin: 'war'
description = 'module name'
dependencies {
compile "someothermodule:commonapi:1.0.0-SNAPSHOT"
compile "io.springfox:springfox-swagger2:2.0.1"
compile project(':dependingproject1:dependingproject2')
compile comlib.spring_boot_starter_actuator
compile comlib.spring_core
compile comlib.spring_security_web
compile comlib.spring_security_config
testCompile(comlib.spring_boot_starter_test) {
exclude(module: 'commons-logging')
}
testCompile comlib.junit4
providedCompile comlib_app.spring_boot_plugin_tomcat
testCompile "io.springfox:springfox-staticdocs:2.0.3"
testCompile "org.springframework:spring-test:4.1.7.RELEASE"
}
ext {
swaggerOutputDir = file("src/docs/asciidoc/generated")
asciiDocOutputDir = file("${buildDir}/asciidoc")
}
test {
systemProperty 'org.springframework.restdocs.outputDir', asciiDocOutputDir
systemProperty 'io.springfox.staticdocs.outputDir', swaggerOutputDir
}
//spring boot plugin
buildscript {
repositories {
maven {
credentials {
username "$nexusUser"
password "$nexusPass"
}
url "$nexusCentral"
}
maven {
credentials {
username "$nexusUser"
password "$nexusPass"
}
url "$nexusThirdParty"
}
}
dependencies {
classpath(comlib.spring_boot_plugin_gradle)
}
}
Included the following code snippet in my gradle file
[distZip, distTar].each { task -> configurations.archives.artifacts.removeAll
{ it.class.simpleName == "ArchivePublishArtifact" && it.archiveTask == task }
task.enabled = false
}
For more details refer this link. Its issue with spring boot plugin.
arjuncc's solution doesn't seem to work on Gradle 4.10.2, so here's one that works and uses public APIs, hopefully it will continue to work.
configurations.archives.artifacts.removeAll {
// exclude from the archives configuration all artifacts that were generated by distZip & distTar
def depTasks = it.getBuildDependencies().getDependencies()
depTasks.contains(distZip) || depTasks.contains(distTar)
}
More or less the same as ajuncc's solution, but perhaps a bit more simple. Remove all .tar artifacts from the archives configuration:
configurations.archives.artifacts.removeAll {PublishArtifact publishArtifact -> publishArtifact.type == 'tar'}

Resources