kenv

Kotlin multiplatform DotEnv environment variable access

https://github.com/mooncloak/kenv

Science Score: 44.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
    Found CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (13.1%) to scientific vocabulary

Keywords

dotenv dotenv-parser env environment environment-variables kotlin kotlin-library kotlin-multiplatform
Last synced: 6 months ago · JSON representation ·

Repository

Kotlin multiplatform DotEnv environment variable access

Basic Info
  • Host: GitHub
  • Owner: mooncloak
  • License: apache-2.0
  • Language: Kotlin
  • Default Branch: develop
  • Homepage:
  • Size: 324 KB
Statistics
  • Stars: 1
  • Watchers: 0
  • Forks: 0
  • Open Issues: 0
  • Releases: 3
Topics
dotenv dotenv-parser env environment environment-variables kotlin kotlin-library kotlin-multiplatform
Created over 2 years ago · Last pushed about 1 year ago
Metadata Files
Readme License Code of conduct Citation Codeowners Security

README.md

kenv

Kotlin Multiplatform environment variable access. This project is a port of the Ruby dotenv project for Kotlin multiplatform. It allows loading environment variables from .env files, the platform's System, or from anywhere else.

```kotlin val kenv = Kenv { system() dotenv(path = "./.env") }

val value = kenv["MYENVIRONMENTVARIABLE"] ```

GitHub tag (latest by date)

[!Warning] Exclude any environment variables from your source control repositories to avoid leaking sensitive data. For git you can add the .env file paths to your .gitignore file.

Getting Started 🏁

Checkout the releases page to get the latest version.

GitHub tag (latest by date)

Repository

kotlin repositories { maven { url = uri("https://repo.repsy.io/mvn/mooncloak/public") } }

Dependencies

kotlin implementation("com.mooncloak.kodetools.kenv:kenv-core:VERSION")

Supported DotEnv Format 📄

.env, or "dotenv", files contain key-value pairs of environment variables in a format that is similar to Bash files that exported environment variables. This project supports a format that may slightly deviate from other formats supported by other "dotenv" libraries, but should generally be very similar. However, other than slight differences, the concept remains the same: to simply store environment variables in a file and access those environment variables when needed.

The variation of the "dotenv" file format that this library supports is described below.

Key-value pairs

Environment variables are stored in a "dotenv" file as key-value pairs where the key and value are separated via an equals signe (=):

KEY=VALUE AUTH_TOKEN=SOME_SECRET_VALUE

export statements

Before the key of an environment variable, the export modifier may optionally be provided. This allows these files to be sourced in Bash.

export KEY=VALUE export AUTH_TOKEN=SOME_SECRET_VALUE

Keys

Environment variable keys must consist only of letters (defined by Char.isLetter), numbers (defined by Char.isDigit), underscores, and periods. A key must start with either a letter or an underscore.

Values

A supported environment variable value must meet the following criteria:

  • MUST be either a single line or multiline value.
  • MAY contain whitespace (that will be trimmed) between the separating equals sign and the start of the value.
  • A single line value MAY be quoted with single or double quotes.
  • A single line value that is not surrounded with quotes is terminated by the first whitespace character or the end of the line.
  • A single line value that is surrounded with quotation marks, MAY contain whitespace characters and is terminated by the first non-escaped (preceded by a backslash) matching quotation mark, or the end of the line.
  • A multiline value begins MUST start and end with three matching, single or double quotation marks.
  • A multiline value MAY consist of multiple lines of content, including whitespaces.
  • A multiline value is terminated by a quotation mark set that matches its starting quotation mark set.
  • An environment variable value, single line or multiline, surrounded with double quotation marks, MAY contain environment variables references (more on this later).

``` NO_QUOTES=abc123

REFERENCED="Inline multiple lines with the\n newline character, and substitue the following with the reference value: ${SIMPLE}"

NONINTERPOLATED='Raw text without variable interpolation. The following does not get substituted with the referenced value: ${NOSUB}'

MULTILINE = """ long text here, e.g. a private SSH key """ ```

References and Interpolation

Environment variable values may reference previously defined environment variables from the same "dotenv" file. As long as the value is NOT surrounded with single quotation marks, then the referenced environment variables will be replaced with their actual values, or null if the value was not found. Environment variable references take the following format: ${REFERENCED_VARIABLE_KEY}.

Note: If an environment variable reference is escaped (preceded by a backslash), then it will be ignored.

USER=admin EMAIL=${USER}@example.org DATABASE_URL="postgres://${USER}@localhost/my_database"

Comments

Commented lines are ignored during parsing of the "dotenv" files. These lines start with either

  • A hash symbol - #
  • Two forward slashes - //
  • A forward slash and an asterisk - /*
  • An asterisk - *

The reason all these values are supported as starting line comments, is that it allows for the usage of both typical " dotenv" style line comments (#), and for Kotlin-esque style comments, including multiline comments.

``` /** * WARNING: Do not check this file into version control! * * It contains environment variables which should be kept secret. */

The following contains username and password to access the repository:

repoUser=username repoPassword=secretPassword

// TODO: Add required environment variables as needed. ```

Usage 👨‍💻

Kenv

Environment variables are accessed through the EnvironmentVariableStore component. EnvironmentVariableStores can be created to retrieve environment variables from the System, "dotenv" files, custom sources, or a combination of all of them. The Kenv class is an EnvironemntVariableStore instance that can easily be created and delegates to others sources defined during its construction. To construct a Kenv instance, use the Kenv constructor function:

kotlin val kenv = Kenv { system() dotenv(path = "./.env") }

The Kenv constructor function accepts a scoped builder function (builder: KenvBuilder.() -> Unit) as a parameter that is used to establish the sources of environment variables. The core functions that are available to add environment variable sources can be found on the KenvBuild class.

Order matters

The order in which these sources are established matters, as when attempting to retrieve an environment variable via a key, the resulting Kenv instance will work its way backwards through the sources until it retrieves a result. For the example above, the "dotenv" file located at the relative path "./.env" will be checked first for an environment variable, and if it did not contain the desired variable, the system will then be checked.

Access

Once you have a Kenv instance, or any other EnvironmentVariableStore instance, you can access the environment variables via the get function by passing in the key to the environment variable.

kotlin val value = kenv.get("key") // Or, kenv["key"] since `get` is the get operator function.

This will return an EnvironmentVariable.Value instance, whose String value can be retrieved via the value property.

kotlin val value: EnvironmentVariable.Value = kenv["key"] val stringValue = value.value

Typed Values

For convenience, there are functions to obtain and convert environment variables to their desired type:

kotlin val secret = kenv.getString("secret") val isDebug = kenv.getBooleanOrNull("is_debug") ?: false val appName = kenv.getStringOrDefault("app_name", defaultValue = "MyApp")

Delegation

There are convenience functions that are available to use Kotlin delegated properties to access environment variables:

kotlin val secret by kenv.stringOrNull() val isDebug by kenv.boolean("is_debug") val appName by kenv.string("app_name", defaultValue = "MyApp")

System

The System component can also be used directly to obtain environment variables from the underlying platform's system component.

kotlin System.getEnv("access_token")

Inspiration 🧠

This project was inspired by, yet completely independent of, the following open source projects:

| Project | Language | License | |-------------------------------------------------------------|------------|------------------------------------------------------------------------------| | dotenv | Ruby | MIT | | dotenv-kotlin | Kotlin JVM | Apache 2.0 | | dotenvy | Rust | MIT |

Documentation 📃

More detailed documentation is available in the docs folder. The entry point to the documentation can be found here.

Security 🛡️

For security vulnerabilities, concerns, or issues, please refer to the security policy for more information on appropriate approaches for disclosure.

Contributing ✍️

Outside contributions are welcome for this project. Please follow the code of conduct and coding conventions when contributing. If contributing code, please add thorough documents and tests. Thank you!

License ⚖️

``` Copyright 2023 mooncloak

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ```

Owner

  • Name: mooncloak
  • Login: mooncloak
  • Kind: organization
  • Email: support@mooncloak.com

Privacy focused apps

Citation (CITATION.cff)

cff-version: 1.2.0
message: "If you use this software, please cite it as below."
authors:
    - alias: "kodetools@mooncloak.com"
      website: "https://kodetools.mooncloak.codes"
contact:
    - alias: "kodetools@mooncloak.com"
      website: "https://kodetools.mooncloak.codes"
title: "kenv"
type: "software"
abstract: "Kotlin multi-platform environment variable access library."
license: "Apache-2.0"
keywords:
    - "kotlin"
    - "multiplatform"
    - "environment"
    - "variables"
    - "environment variables"
    - "kotlin multiplatform"
repository-code: "https://github.com/mooncloak/kenv"
url: "https://github.com/mooncloak/kenv"

GitHub Events

Total
  • Watch event: 1
  • Public event: 1
Last Year
  • Watch event: 1
  • Public event: 1

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 50
  • Total Committers: 2
  • Avg Commits per committer: 25.0
  • Development Distribution Score (DDS): 0.02
Past Year
  • Commits: 3
  • Committers: 1
  • Avg Commits per committer: 3.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Chris Keenan 1****N 49
Chris Keenan c****n@P****l 1

Issues and Pull Requests

Last synced: 9 months ago

All Time
  • Total issues: 0
  • Total pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Total issue authors: 0
  • Total pull request authors: 0
  • Average comments per issue: 0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 0
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 0
  • Pull request authors: 0
  • Average comments per issue: 0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
Pull Request Authors
Top Labels
Issue Labels
Pull Request Labels

Dependencies

.github/workflows/gradle-wrapper-validation.yml actions
  • actions/checkout v3 composite
  • gradle/wrapper-validation-action v1 composite
.github/workflows/publish.yml actions
  • actions/checkout v3 composite
  • actions/setup-java v3 composite
.github/workflows/refresh_versions.yml actions
  • EndBug/add-and-commit v9 composite
  • actions/checkout v3 composite
  • actions/setup-java v3 composite
  • gradle/gradle-build-action v2 composite
  • peterjgrainger/action-create-branch v2.2.0 composite
  • repo-sync/pull-request v2 composite
build.gradle.kts maven
buildSrc/build.gradle.kts maven
kenv-core/build.gradle.kts maven
  • com.squareup.okio:okio _ api
  • com.squareup.okio:okio-nodefilesystem _ implementation
  • com.squareup.okio:okio-wasifilesystem _ implementation
kotlin-js-store/yarn.lock npm
  • ansi-colors 4.1.3
  • ansi-regex 5.0.1
  • ansi-styles 4.3.0
  • anymatch 3.1.3
  • argparse 2.0.1
  • balanced-match 1.0.2
  • binary-extensions 2.2.0
  • brace-expansion 2.0.1
  • braces 3.0.2
  • browser-stdout 1.3.1
  • buffer-from 1.1.2
  • camelcase 6.3.0
  • chalk 4.1.2
  • chokidar 3.6.0
  • cliui 7.0.4
  • color-convert 2.0.1
  • color-name 1.1.4
  • debug 4.4.0
  • decamelize 4.0.0
  • diff 5.2.0
  • emoji-regex 8.0.0
  • escalade 3.1.1
  • escape-string-regexp 4.0.0
  • fill-range 7.0.1
  • find-up 5.0.0
  • flat 5.0.2
  • format-util 1.0.5
  • fs.realpath 1.0.0
  • fsevents 2.3.2
  • get-caller-file 2.0.5
  • glob 8.1.0
  • glob-parent 5.1.2
  • has-flag 4.0.0
  • he 1.2.0
  • inflight 1.0.6
  • inherits 2.0.4
  • is-binary-path 2.1.0
  • is-extglob 2.1.1
  • is-fullwidth-code-point 3.0.0
  • is-glob 4.0.3
  • is-number 7.0.0
  • is-plain-obj 2.1.0
  • is-unicode-supported 0.1.0
  • js-yaml 4.1.0
  • locate-path 6.0.0
  • log-symbols 4.1.0
  • minimatch 5.1.6
  • mocha 10.7.0
  • ms 2.1.3
  • normalize-path 3.0.0
  • once 1.4.0
  • p-limit 3.1.0
  • p-locate 5.0.0
  • path-exists 4.0.0
  • picomatch 2.3.1
  • randombytes 2.1.0
  • readdirp 3.6.0
  • require-directory 2.1.1
  • safe-buffer 5.2.1
  • serialize-javascript 6.0.2
  • source-map 0.6.1
  • source-map-support 0.5.21
  • string-width 4.2.3
  • strip-ansi 6.0.1
  • strip-json-comments 3.1.1
  • supports-color 7.2.0
  • supports-color 8.1.1
  • to-regex-range 5.0.1
  • typescript 5.5.4
  • workerpool 6.5.1
  • wrap-ansi 7.0.0
  • wrappy 1.0.2
  • y18n 5.0.8
  • yargs 16.2.0
  • yargs-parser 20.2.9
  • yargs-unparser 2.0.0
  • yocto-queue 0.1.0