How to pass parameters or arguments into a gradle task

Nathan Russell picture Nathan Russell · Dec 5, 2013 · Viewed 122.7k times · Source

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;

Answer

Bipi picture Bipi · Oct 22, 2014

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.