Gradle环境变量。从文件加载

时间:2018-05-24 12:09:47

标签: bash gradle environment-variables

我是Gradle的新手。

目前我有这个任务:

task fooTask {
    doLast {
        exec {
            environment 'FOO_KEY', '1234567' // Load from file here!
            commandLine 'fooScript.sh'
        }
    }
}

fooScript.sh

#!/bin/bash
echo $FOO_KEY

一切都很好。但我有env.file所有需要的环境变量。此文件在Docker构建器中使用。

env.file

FOO_KEY=1234567

问题:如何将env.file与Gradle environment一起使用来加载所有需要的环境。 PARAMS?

4 个答案:

答案 0 :(得分:4)

这个怎么样:

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

答案 1 :(得分:4)

我也给出了我的版本(检查行是否为空且没有注释,也不要覆盖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
            }
    }
}

但是实际上,我认为他们应该将此功能添加为exec插件属性!现在使用.env文件很普遍。

答案 2 :(得分:0)

以下代码是我能够生成的唯一代码,它满足在Android Studio中提供有效的“ UNIX标准环境文件导入”的两个最重要的要求:

  • 加载取决于构建类型的文件(至少:调试和发布)
  • 在Android代码中公开指定的环境变量,实际上不是作为环境变量,而是作为buildConfigFields内容。
ext {
    node_env = ""
}

android.applicationVariants.all { variant ->
    if (variant.name == "debug") {
        project.ext.set("node_env", "development")
    } else if (variant.name == "release") {
        project.ext.set("node_env", "production")
    }

    file("." + node_env + '.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.getProperty(key) == null) {
                System.setProperty("env.$key", value)
            }
        }
    }

    if (variant.name == "release") {
        android.signingConfigs.release.storeFile file(System.getProperty("env.ANDROID_APP_SIGNING_STOREFILE"))
        android.signingConfigs.release.keyAlias System.getProperty("env.ANDROID_APP_SIGNING_KEYALIAS")
        android.signingConfigs.release.storePassword System.getProperty("env.ANDROID_APP_SIGNING_STOREPASSWORD")
        android.signingConfigs.release.keyPassword System.getProperty("env.ANDROID_APP_SIGNING_KEYPASSWORD")
    }
    android.defaultConfig.buildConfigField "String", "ANDROID_APP_URL", "\"${System.getProperty("env.ANDROID_APP_URL")}\""
}

科特琳:

Log.i(TAG, BuildConfig.ANDROID_APP_URL)

请让我知道您对此的看法,因为我不能完全确定它的工作原理,尤其是选择要加载的好文件。

答案 3 :(得分:0)

有一些插件可以从 .env 文件中加载环境变量(例如这个 one

所以示例构建文件看起来像这样(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
}
相关问题