Skip to content

Instantly share code, notes, and snippets.

@esycat
Last active January 17, 2018 00:17
Show Gist options
  • Save esycat/7946550 to your computer and use it in GitHub Desktop.
Save esycat/7946550 to your computer and use it in GitHub Desktop.
/.gradle/
/build/
/buildSrc/
generated.conf
defaultTasks 'clean', 'generateConfig'
ext {
templatesDir = projectDir // config templates location
configTokens = [
db: [
host: 'localhost',
name: 'test',
user: 'test',
pass: ''
]
]
}
task generateConfig(type: GenerateTemplate) {
template = 'template.conf'
target = file('generated.conf')
expand configTokens // filter() can be used instead to replace tokens
}
task clean(type: Delete) {
delete generateConfig.target
}
/**
* Move this class to buildSrc/src/main/groovy under your project.
*/
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.Optional
import org.apache.tools.ant.filters.ReplaceTokens
class GenerateTemplate extends Copy {
public final static BEGIN_TOKEN = '{'
public final static END_TOKEN = '}'
private String template
private File target
@Optional
private Map<String, ?> properties
def GenerateTemplate() {
from(project.templatesDir)
}
public GenerateTemplate setTemplate(String name) {
this.template = name
include(template)
this
}
@Input
public String getTemplate() {
template
}
public GenerateTemplate setTarget(File file) {
this.target = file
into(target.getParent())
this
}
@OutputFile
public File getTarget() {
target
}
@Override
protected void configureRootSpec() {
super.configureRootSpec()
rename(template, target.getName())
}
/**
* Configures a filter to replace tokens in a template.
* The method should be called from configureRootSpec().
*/
private GenerateTemplate configureFilter() {
filter(ReplaceTokens, tokens: properties, beginToken: BEGIN_TOKEN, endToken: END_TOKEN)
this
}
}
db.host = ${db.host}
db.name = ${db.name}
db.user = ${db.user}
db.pass = ${db.pass}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment