Reputation: 811
I have two flavors in the gradle file for an Android app:
productFlavors {
production { }
devel { }
}
I have a configuration file that I need to copy to the app/
directory before any other tasks run when building the project. The is a configuration file per flavor, i.e.:
etc/configuration-production.json
etc/configuration-devel.json
When building devel
I need to do essentially this:
cp etc/configuration-devel.json app/configuration.json
When building production
:
cp etc/configuration-production.json app/configuration.json
How do I automate this in gradle? This copy needs to happen first and foremost when executing a build since some of the tasks need that app/configuration.json
file to be there.
I tried:
task copyConfig(type: Copy) {
from "etc/configuration-${Flavor.name}.json"
into "app/configuration.json"
}
build.dependsOn copyConfig
But didn't work. The copyConfig
task didn't run.
Upvotes: 3
Views: 2591
Reputation: 45402
You can add the following to your app
build.gradle
for copying your file from etc/configuration-XXX.json
to app/configuration.json
in the first statement of the respective tasks assembleDevel.*
& assembleProduction.*
:
def cp(copyType) {
println "copying " + "../etc/configuration-" + copyType + ".json"
copy {
from "../etc/configuration-" + copyType + ".json"
into '.'
rename { String fileName ->
fileName.replace("configuration-" + copyType + ".json", "configuration.json")
}
}
}
tasks.whenTaskAdded { task ->
if (task.name ==~ /assembleDevel.*/) {
task.doFirst() {
cp("devel")
}
} else if (task.name ==~ /assembleProduction.*/) {
task.doFirst() {
cp("production")
}
}
}
This is the required configuration :
app/
├── build.gradle
etc/
├── configuration-production.json
└── configuration-devel.json
If assembleDevel.*
/assembleProduction.*
are not the tasks you are looking for, you can replace them with for instance : prepareDevel.*Dependencies
/prepareProduction.*Dependencies
Upvotes: 4