Skip to content

nbottarini/env-kt

Repository files navigation

Maven License: MIT CI Status

env

Tiny library to ease the use of environment variables with support for .env files.

Installation

Gradle (Kotlin)

repositories {
    mavenCentral()
}

dependencies {
    implementation("dev.botta:env:2.0.0")
}

Gradle (Groovy)

repositories {
    mavenCentral()
}

dependencies {
    implementation 'dev.botta:env:2.0.0'
}

Maven

<dependency>
    <groupId>dev.botta</groupId>
    <artifactId>env</artifactId>
    <version>2.0.0</version>
</dependency>

Usage

val myEnvValue: String? = Env["my-env-var"]

val myEnvValue: String? = Env.get("my-env-var")

val myEnvValue: String = Env.get("my-env-var", "default value")

val myEnvValue: String = Env.getOrThrow("my-env-var") // Throws IllegalArgumentException if env var is not present

val allEnvVars = Env.getAll()

.env

You can create a .env file in the project directory to set environment variables for your development environment.

Sample .env file:

VAR1=VALUE1
VAR2=VALUE2

It is recommended to ignore the .env file from git. You can commit a sample .env.dist file with the default environment variables (without sensitive values like passwords).

The system environment variables takes precedence over .env variables.

By default, the library tries to find the .env file in the working dir and in the parent dirs.

You can specify additional directories to search:

Env.addSearchPath('./myDir')

Search paths must be configured before accessing any environment variable.

Usage in gradle files

buildscript {
    repositories { mavenCentral() }
    dependencies {
        classpath("dev.botta:env:2.0.0")
    }
}

Env.addSearchPath(rootProject.projectDir.absolutePath)

project.ext {
    set("JDBC_URL", "jdbc:postgresql://${Env["DB_HOST"]}:${Env["DB_PORT"]}/${Env["DB_NAME"]}")
}

About

Tiny library to ease the use of environment variables with support for .env files

Resources

License

Stars

Watchers

Forks

Packages

No packages published