How do I define a property in my script based on a profile passed in on the command line?

Hi,

I’m using Gradle 2.7 on Mac Yosemite. I want to load a file into my src/main/resources directory based on the environment (“-Penv=xxx”) I’m running in. So I defined this block within my build.grade file

loadConfiguration()

def loadConfiguration() {
    def environment = hasProperty('env') ? env : 'dev'
    setProperty 'environment', environment
}

but this is dying with the error

* Where:
Build file '/Users/davea/Dropbox/my_workspace/myproject/build.gradle' line: 153

* What went wrong:
A problem occurred evaluating root project 'myproject'.
> No such property: environment for class: org.gradle.api.internal.project.DefaultProject_Decorated

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 1.743 secs
Daves-Mamyook-Pro-2:myproject davea$ vim build.gradle

Line 153 is the line “setProperty ‘environment’, environment”. What’s wrong with the above block or more generally, how do I set a script property to define what my environment is?

The method setProperty(String name, Object value) searches property with given name and override its value with given value. If the property is not found, MissingPropertyException will be thrown. You can find more detail information at DSL document on Project.

In your case, you can use extra properties as follows. Then the property named environment is available in your build script.

ext {
    environment = project.hasPropety('env') ? env : 'dev'
}