[variables] How to pass parameters or arguments into a gradle task

I have a gradle build script into which I am trying to include Eric Wendelin's css plugin - http://eriwen.github.io/gradle-css-plugin/

Its easy enough to implement, and because I only want minification (rather than combining and gzipping), I've got the pertinent parts of the build script looking like this:

minifyCss {
    source = "src/main/webapp/css/brandA/styles.css"
    dest = "${buildDir}/brandA/styles.css"
    yuicompressor {
        lineBreakPos = -1
    }
}

war {
    baseName = 'ex-ren'
}

war.doFirst {
    tasks.myTask.minifyCss.execute()
}

This is perfect - when I run the gradle war task, it calls the minifyCss task, takes the source css file, and creates a minified version in the buildDir

However, I have a handful of css files which need minify-ing, but not combining into one file (hence I'm not using the combineCss task)

What I'd like to be able to do is make the source and dest properties (assuming that's the correct terminology?) of the minifyCss task reference variables of some sort - either variables passed into the task in the signature, or global variables, or something ...

Something like this I guess (which doesn't work):

minifyCss(sourceFile, destFile) {
    source = sourceFile
    dest = destFile
    yuicompressor {
        lineBreakPos = -1
    }
}

war {
    baseName = 'ex-ren'
}

war.doFirst {
    tasks.myTask.minifyCss.execute("src/main/webapp/css/brandA/styles.css", "${buildDir}/brandA/styles.css")
    tasks.myTask.minifyCss.execute("src/main/webapp/css/brandB/styles.css", "${buildDir}/brandB/styles.css")
    tasks.myTask.minifyCss.execute("src/main/webapp/css/brandC/styles.css", "${buildDir}/brandC/styles.css")
}

This doesn't work either:

def sourceFile = null
def destFile = null

minifyCss {
    source = sourceFile
    dest = destFile
    yuicompressor {
        lineBreakPos = -1
    }
}

war {
    baseName = 'ex-ren'
}

war.doFirst {
    sourceFile = "src/main/webapp/css/brandA/styles.css"
    destFile = "${buildDir}/brandA/styles.css"
    tasks.myTask.minifyCss.execute()
}

For the life of me I cannot work out how to call a task and pass variables in :(

Any help very much appreciated;

This question is related to variables groovy parameters gradle

The answer is


If the task you want to pass parameters to is of type JavaExec and you are using Gradle 5, for example the application plugin's run task, then you can pass your parameters through the --args=... command line option. For example gradle run --args="foo --bar=true".

Otherwise there is no convenient builtin way to do this, but there are 3 workarounds.

1. If few values, task creation function

If the possible values are few and are known in advance, you can programmatically create a task for each of them:

void createTask(String platform) {
   String taskName = "myTask_" + platform;
   task (taskName) {
      ... do what you want
   }
}

String[] platforms = ["macosx", "linux32", "linux64"];
for(String platform : platforms) {
    createTask(platform);
}

You would then call your tasks the following way:

./gradlew myTask_macosx

2. Standard input hack

A convenient hack is to pass the arguments through standard input, and have your task read from it:

./gradlew myTask <<<"arg1 arg2 arg\ in\ several\ parts"

with code below:

String[] splitIntoTokens(String commandLine) {
    String regex = "(([\"']).*?\\2|(?:[^\\\\ ]+\\\\\\s+)+[^\\\\ ]+|\\S+)";
    Matcher matcher = Pattern.compile(regex).matcher(commandLine);
    ArrayList<String> result = new ArrayList<>();
    while (matcher.find()) {
        result.add(matcher.group());
    }
    return result.toArray();   
}

task taskName, {
        doFirst {
            String typed = new Scanner(System.in).nextLine();
            String[] parsed = splitIntoTokens(typed);
            println ("Arguments received: " + parsed.join(" "))
            ... do what you want
        } 
 }

You will also need to add the following lines at the top of your build script:

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;

3. -P parameters

The last option is to pass a -P parameter to Gradle:

./gradlew myTask -PmyArg=hello

You can then access it as myArg in your build script:

task myTask {
    doFirst {
       println myArg
       ... do what you want
    }
}

Credit to @789 for his answer on splitting arguments into tokens


You should consider passing the -P argument in invoking Gradle.

From Gradle Documentation :

--project-prop Sets a project property of the root project, for example -Pmyprop=myvalue. See Section 14.2, “Gradle properties and system properties”.

Considering this build.gradle

task printProp << {
    println customProp
}

Invoking Gradle -PcustomProp=myProp will give this output :

$ gradle -PcustomProp=myProp printProp
:printProp
myProp

BUILD SUCCESSFUL

Total time: 3.722 secs

This is the way I found to pass parameters.


task mathOnProperties << {
    println Integer.parseInt(a)+Integer.parseInt(b)
    println new Integer(a) * new Integer(b)
}

$ gradle -Pa=3 -Pb=4 mathOnProperties
:mathOnProperties
7
12

BUILD SUCCESSFUL

I would suggest the method presented on the Gradle forum:

def createMinifyCssTask(def brand, def sourceFile, def destFile) {
    return tasks.create("minify${brand}Css", com.eriwen.gradle.css.tasks.MinifyCssTask) {
        source = sourceFile
        dest = destFile
    }
}

I have used this method myself to create custom tasks, and it works very well.


Its nothing more easy.

run command: ./gradlew clean -PjobId=9999

and

in gradle use: println(project.gradle.startParameter.projectProperties)

You will get clue.


Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to groovy

Jenkins pipeline how to change to another folder groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding Run bash command on jenkins pipeline Try-catch block in Jenkins pipeline script How to print a Groovy variable in Jenkins? Jenkins pipeline if else not working How to set and reference a variable in a Jenkinsfile Jenkins: Can comments be added to a Jenkinsfile? How to define and use function inside Jenkins Pipeline config? Jenkins: Cannot define variable in pipeline stage

Examples related to parameters

Stored procedure with default parameters AngularJS ui router passing data between states without URL C#: HttpClient with POST parameters HTTP Request in Swift with POST method In Swift how to call method with parameters on GCD main thread? How to pass parameters to maven build using pom.xml? Default Values to Stored Procedure in Oracle How do you run a .exe with parameters using vba's shell()? How to set table name in dynamic SQL query? How to pass parameters or arguments into a gradle task

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)