Skip to content

Instantly share code, notes, and snippets.

@silas
Last active March 1, 2023 07:35
Show Gist options
  • Save silas/b2454f259ce600056d455e57351bdf68 to your computer and use it in GitHub Desktop.
Save silas/b2454f259ce600056d455e57351bdf68 to your computer and use it in GitHub Desktop.
Load `.env` into gradle run
def static getenv(path = ".env") {
def env = [:]
def file = new File(path)
if (file.exists()) {
file.eachLine { line ->
line = line.trim()
if (line != "" && !line.startsWith("#")) {
def pair = line.split("=", 2)
env[pair[0].trim()] = pair.length == 2 ? pair[1].trim() : ""
}
}
}
return env
}
run {
getenv().each { name, value -> environment name, value }
}
@mitasov-ra
Copy link

As I stumbled upon this gist from search, I put my improved version here. I fixed some issues, such as:

  • tokenize splits line not into two substrings but into as many as '=' chars it have. Needs to be replaced with split('=', 2)
  • empty lines are not ignored. Added if for that
def static getenv(path = ".env") {
    def env = [:]

    def file = new File(path)
    if (file.exists()) {
        file.eachLine { line ->
            def pair = line.split("=", 2)
            if (pair.length == 2) {
                def (name, value) = pair
                env[name.trim()] = value.trim()
            }
        }
    }

    return env
}

run {
    getenv().each { name, value -> environment name, value }
}

It's still not perfect as any comments in .env file would break everything, but it's a bit better already

@silas
Copy link
Author

silas commented Feb 23, 2023

@mitasov-ra Cool, updated original to include your fix and basic comment filtering.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment