Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I override a property defined in build.gradle?

Tags:

gradle

How can I set a property in the build.gradle file and allow each developer to override it locally? I tried:

gradle.properties:

MY_NAME = "Jonathon"
MY_COLOR = "blue"

build.gradle:

ext.MY_NAME = "John Doe"
task showit <<{
  println "MY_NAME[" + MY_NAME + "]";
  println "MY_COLOR[" + MY_COLOR + "]";
}

gradle showit gives:

:showit
MY_NAME[John Doe]
MY_COLOR["blue"]

I thought that a property defined in a gradle.properties file at the project root would override a property with the same name defined in build.gradle, but this does not appear to be the case. It only fills in for a missing property.

like image 714
Jeff French Avatar asked Jan 17 '13 21:01

Jeff French


3 Answers

Check whether the project has a property, and if not, set it to the default value:

ext {
    if (!project.hasProperty('MY_NAME')) {
        MY_NAME = 'John Doe'
    }
}

See: https://docs.gradle.org/current/userguide/build_environment.html#sub:checking_for_project_properties

If you need to do this for multiple properties, you can define a function:

def setPropertyDefaultValueIfNotCustomized(propertyName, defaultValue) {
    if (!project.hasProperty(propertyName)) {
        ext[propertyName] = defaultValue
    }
}

ext {
    setPropertyDefaultValueIfNotCustomized('MY_NAME', 'John Doe')
}
like image 63
Johan Stuyts Avatar answered Sep 27 '22 19:09

Johan Stuyts


Similar to Johan Stuyts' answer, but as a one-liner:

ext.MY_NAME = project.properties['MY_NAME'] ?: 'John Doe'

Running gradle -PMY_NAME="Jeff F." showit gives MY_NAME[Jeff F.].

Running gradle showit gives MY_NAME[John Doe].

like image 28
Markus Pscheidt Avatar answered Sep 27 '22 17:09

Markus Pscheidt


i think you can define a local variable and then override it like this

  def dest = "name"

  task copy(type: Copy) {
     from "source"
     into name
  }

see this doc

like image 32
Rachel Gallen Avatar answered Sep 27 '22 17:09

Rachel Gallen