gradle - call custom task before gradle repositories resolution takes place - gradle

I'm using gradle-7.2 I want to call custom task to derive svn branch and then use the same in repository URLs, couldn't find a way to do that.
this is my custom task in build.gradle:
task svninfo {
println "***svninfo***"
doLast {
new ByteArrayOutputStream().withStream { os ->
def result = exec {
executable = 'svn'
args = ['info']
standardOutput = os
}
def outputAsString = os.toString()
println "outputAsString #: $outputAsString"
def matchSvnBranch = outputAsString =~ /URL:.*\/branches\/(.*)\/deployready\/.*/
//def matchLastChangedRev = outputAsString =~ /Last Changed Rev: (\d+)/
def branchName=${matchSvnBranch[0][1]}
println "svn branch #: ${matchSvnBranch[0][1]}"
println "svn.branch #: ${branchName}"
ext.branch = branchName
}
}
}
repositories {
//svninfo() --- not working, getting error
maven {
url "myurl-$branch"
allowInsecureProtocol = true
}
}
Update:
As per the comment, i changed to doFirst {}, but still getting the error. Im not able to call svninfo task inside repositories closure. getting below error:
Could not find method svninfo() for arguments [] on repository container of type org.gradle.api.internal.artifacts.dsl.DefaultRepositoryHandler.
Please guide me on how to call svninfo() task before repositories evolution, so that i can use the variable branch in maven Url..

Okay, after couple of trial and errors, finally this worked:
def svninfo() {
println "***svninfo***"
new ByteArrayOutputStream().withStream { os ->
def result = exec {
executable = 'svn'
args = ['info']
standardOutput = os
}
def outputAsString = os.toString()
println "outputAsString #: $outputAsString"
def matchSvnBranch = outputAsString =~ /URL:.*\/branches\/(.*)\/deployready\/.*/
def branchName=matchSvnBranch[0][1]
println "svn branch #: ${matchSvnBranch[0][1]}"
println "svn.branch #: ${branchName}"
ext.branch = branchName
}
}
svninfo()
repositories {
maven {
url "myurl-$branch"
allowInsecureProtocol = true
}
}
Not sure why defining as task was not working. Now i'm trying to move this logic to init script as this is going to be common logic for modules.

Related

Skip variable checking in gradle configuration phase

I have some gradle script where i read some properties file (differen file in different execution configurations) and assign Properties obect to "ext" property in each task.
task provisionMongoDBCopyDockerfile(type: Copy, dependsOn: 'readTestConfiguration') {
from "${projectDir}/deployment/scripts/Dockerfile.mongodb"
into "/tmp/stand/mondodb"
expand(ext.stand)
filteringCharset = 'UTF-8'
}
task readTestConfiguration () {
def props = loadStandProperties('test')
println props
tasks.each {
it.ext.stand = props
println it.ext
}
}
but when i run gradle script i get this error: "Cannot get property 'stand' on extra properties extension as it does not exist" in line with "expand(ext.stand)". How can i solve this problem. I don't want to put all configuration parameters in "gradle.properties" and change it from configuration to configuration.
Consider the following (using Gradle 2.14.1). This effectively sets up a dependency in Configuration phase. Also it uses project.ext versus tasks.ext.
def readTestConfiguration = {
def props = loadStandProperties('test')
println props
project.ext.stand = props
}
def loadStandProperties (def env) {
// use mock data
return ["foo": "bar"]
}
tasks.whenTaskAdded { Task task ->
if (task.name == "provisionMongoDBCopyDockerfile") {
readTestConfiguration()
}
}
task provisionMongoDBCopyDockerfile(type: Copy) {
from "${projectDir}/in"
into "${projectDir}/out"
expand(project.ext.stand)
}

variable is read-only when it shouldn't be

When i execute this in my script
artifacts = ['abc123-com', 'abc123-ejb', 'abc123-spec', 'abc123-war', 'abc123-war2']
task clone_workspace() << {
for (item in artifacts) {
println item
}
}
i get
> Cannot set the value of read-only property 'artifacts' on root project 'abc123'.
I have tried scoping to project with project.artifacts, and to ext with project.ext.artifacts.
what am I doing wrong here?
The following minimalist Gradle file illustrates that project already has a property for artifacts (documented here):
println "TRACER : " + project.artifacts.class
output:
bash$ gradle
TRACER : class org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated
By contrast, this version of the original is happier:
def myArtifacts = ['abc123-com', 'abc123-ejb', 'abc123-spec', 'abc123-war', 'abc123-war2']
task clone_workspace() << {
for (item in myArtifacts) {
println item
}
}

Upload all productFlavors with crashlytics

My problem is simple but I don't find the solution. In my app, I have added crashlytics and I want to use beta to upload builds.
For one productFlavor I use the task called crashlyticsUploadDistribution<ProductFlavor>Release and before I have to assemble build with assemble<ProductFlavor>Release otherwise it can upload a wrong apk.
Now I want to merge this two tasks in only one so in my gradle.file
task prepareFabric(group: 'aat') {
println 'HereSTART'
dependsOn 'assemble<ProductFlavor>Release'
}
task publishRealeaseOnFabric(group: 'aat') {
mustRunAfter prepareFabric
println 'HereFINAL'
dependsOn 'crashlyticsUploadDistribution<ProductFlavor>Release'
}
Now when I execute my task (publishRealeaseOnFabric), print appears but the following line is not executed
dependsOn 'assemble<ProductFlavor>Release'
My question is : How can I make two tasks assemble<ProductFlavor>Release and then crashlyticsUploadDistribution<ProductFlavor>Release in one task ?
I use that it create all the flavors
//Creates the app for all the productFlavors
File crashlyticsProperties = new File("${project.projectDir.absolutePath}/fabric.properties")
applicationVariants.all { variant ->
variant.productFlavors.each { flavor ->
println("flavor : " + variant.name)
def variantSuffix = variant.name.capitalize()
def generatePropertiesTask = task("fabricGenerateProperties${variantSuffix}") << {
Properties properties = new Properties()
properties.put("apiKey", flavor.fabricApiKey)
properties.put("apiSecret", flavor.fabricApiSecret)
properties.store(new FileWriter(crashlyticsProperties), "")
}
def generateResourcesTask = project.tasks.getByName("fabricGenerateResources${variantSuffix}")
generateResourcesTask.dependsOn generatePropertiesTask
generateResourcesTask.doLast {
println "Removing fabric.properties"
crashlyticsProperties.delete()
}
}
}

Can't add String variable to my manifest

I have a build.gradle file and I want to insert some variables into my manifest. This is what I have
def dateformat = new java.text.SimpleDateFormat("yyyy.MM.dd")
version = dateformat.format(new Date());
int userlimit = System.properties['user.limit'] == null ? 1 : System.properties['user.limit'] as int
def owner = System.properties['owner'] == null ? 'Demo version' : System.properties['owner']
task release(dependsOn: [jar, libs, obfuscate]) {
doLast {
def classesDir = new File('expanded-libs')
classesDir.mkdir()
configurations.embed.each {
println "Unzipping $it to expanded-libs.."
ant.unzip(src: it, dest: 'expanded-libs')
}
task combinedJar(type: Jar) {
from zipTree('build/foo-bar-pg-' + version + '.jar')
from configurations.embed.collect { println "Adding $it to the fat jar"; zipTree(it) }
archiveName "../foo-bar-${version}${outputFileNameSuffix}.jar";
exclude 'META-INF/*'
duplicatesStrategy 'EXCLUDE'
manifest {
attributes 'Implementation-Title': 'Foo Bar Module', 'Implementation-Version': version, 'User-Limit': userlimit, 'Licensed-To': owner
}
}
combinedJar.execute()
}
}
Now the interesting thing is that it works without the 'Licensed-To': owner piece, but somehow I can't use that variable in the manifest. For integers, it works, but owner is a String.
This is the error message I get if I run gradle release -Downer="foo" -Duserlimit=20
* What went wrong:
Execution failed for task ':release'.
> Could not find method task() for arguments [{type=class org.gradle.api.tasks.bundling.Jar}, combinedJar, build_36jmpdf
2mspiolilq5o7ipbd86$_run_closure14_closure27_closure29#547a8dfd] on task ':release'.
Can anyone help me how could I put String typed JVM arguments into my manifest?
You missed a closing } brace after the manifest attributes.

(No such file or directory) how to make non existant file to be ignored by gradle

when i run the command 'gradle tasks' or anything for that fact, i got the following error:
Caused by: java.io.FileNotFoundException: /Users/maxit/workspace/Backbone/modules/contact-form/public/build/contact-src.js (No such file or directory)
Here is my gradle build file:
configurations {
sshAntTask
}
dependencies {
sshAntTask 'org.apache.ant:ant-jsch:1.7.1', 'jsch:jsch:0.1.29'
}
// Pull the plugin from Maven Central
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.eriwen:gradle-js-plugin:1.5.0'
}
}
// Invoke the plugin
apply plugin: 'js'
apply plugin:'base'
def appName = "some"
def version = "0.0.1"
def jsSrcDir = 'public/js'
javascript.source {
dev {
js {
srcDir jsSrcDir
include "*.js"
exclude "*.min.js"
}
}
prod {
js {
srcDir jsSrcDir
include "*.min.js"
}
}
}
task combineSrc(type: com.eriwen.gradle.js.tasks.CombineJsTask) {
source = ["${projectDir}/public/templates/templates.js","${projectDir}/public/js/models/contact_model.js", "${projectDir}/public/js/views/contact_form_view.js", "${projectDir}/public/js/app.js" ]
dest = file("${projectDir}/public/build/${appName}-src.js")
}
task appendJQuery(dependsOn: 'combineSrc') {
String backboneSrc = file(new File("${projectDir}/public/build/${appName}-src.js")).text
new File("${projectDir}/public/build/${appName}-jqueryWraped.js").withWriter{ out ->
out << "(function(\$){" + file("${projectDir}/public/build/${appName}-src.js").text + "})(jQuery); \n"
}
}
It appears, that gradle doesn't ignore a file that is none existant. The task 'combineSrc' hasn't been run, yet to create the file....and i am unable to run the task 'cobineSrc' to create the file in the first place. Its kind a dead end. what am i doing wrong and how to make this work? Thank you
The reason you're failing is, that all the stuff you currently doing during the configuration of the appendJQuery task should be done in the execution phase.
just refactor your appendJQuery task to do:
task appendJQuery(dependsOn: 'combineSrc') {
doLast{
String backboneSrc = file(new File("${projectDir}/public/build/${appName}-src.js")).text
new File("${projectDir}/public/build/${appName}-jqueryWraped.js").withWriter{ out ->
out << "(function(\$){" + file("${projectDir}/public/build/${appName}-src.js").text + "})(jQuery); \n"
}
}
}
hope that helps!
René

Resources