Brant
Brant

Reputation: 15344

How can I transform a .properties file during a Gradle build?

As part of a deploy task in Gradle, I want to change the value of a property in foo.properties to point to a production database instead of a development database.

I'd rather not replace the whole file outright, as it's rather large and it means we would have to maintain two separate versions that only differ on a single line.

What is the best way to accomplish this?

Upvotes: 33

Views: 20816

Answers (5)

ssgao
ssgao

Reputation: 5571

You can use ReplaceTokens

Say you have a file called db.properties in src/main/java/resources/com.stackoverlow (the location doesn't matter) with the following content

database.url=@url@

Note that the @ surrounding the url text is required.

You can then define this in your build.gradle file.

processResources {
        filter ReplaceTokens, tokens: [
                "url": "https://stackoverflow.com"
        ]
}

When you build your code, this would replace @url@ with https://stackoverflow.com.

If you are only interested in applying this rule to a specific file, you can add a filesMatching

processResources {
    filesMatching('**/db.properties') {
        filter ReplaceTokens, tokens: [
                "url": "https://stackoverflow.com"
        ]
    }
}

See gradle doc for more explanation

Upvotes: 2

user2543120
user2543120

Reputation: 131

Create a properties object, then create the file object with the targeted properties file path, load the file on the properties object with load, set the desired property with setProperty, and save the changes with store.

def var = new Properties() 
File myfile = file("foo.properties");

var.load(myfile.newDataInputStream())
var.setProperty("db", "prod")
var.store(myfile.newWriter(), null)

Upvotes: 5

David
David

Reputation: 496

You can use the ant.propertyfile task:

    ant.propertyfile(
        file: "myfile.properties") {
        entry( key: "propertyName", value: "propertyValue")
        entry( key: "anotherProperty", operation: "del")
    }

Upvotes: 41

Shorn
Shorn

Reputation: 21554

You should be able to fire off an ant "replace" task that does what you want: http://ant.apache.org/manual/Tasks/replace.html

ant.replace(file: "blah", token: "wibble", value: "flibble")

Upvotes: 7

Peter Niederwieser
Peter Niederwieser

Reputation: 123996

A simple solution is to code a task that uses java.util.Properties to write the file. If you really want to incrementally update the file, you'll have to implement this on your own. Or maybe you find an Ant task that does what you want (all Ant tasks can be used as-is from Gradle). For best results, you should also declare the inputs and outputs of the task, so that Gradle only executes the tasks when the properties file needs to be changed.

Upvotes: 3

Related Questions