Gradle Environment variables. Load from file

There are plugins to load env vars from a .env file (e.g. this one)

So a sample build file will look something like this (Kotlin DSL)


plugins {
    id("co.uzzu.dotenv.gradle") version "1.1.0"
}

tasks.withType<Test> {
    useJUnitPlatform()
    //will pass the env vars loaded by the plugin to the environment of the tests
    environment = env.allVariables
}

I give also my version (check if line is not empty and not a comment, also donot override env var):

file('.env').readLines().each() {
        if (!it.isEmpty() && !it.startsWith("#")) {
            def pos = it.indexOf("=")
            def key = it.substring(0, pos)
            def value = it.substring(pos + 1)

            if (System.getenv(key) == null) {
                environment key, value
            }
    }
}

But actually, I think they should add this feature as a exec plugin property! It's quite common now to use .env file.


What about this :

task fooTask {
    doLast {
        exec {
            file('env.file').readLines().each() {
                def (key, value) = it.tokenize('=')
                environment key, value
            }
            commandLine 'fooScript.sh'
        }
    }
}