Giter VIP home page Giter VIP logo

dotenv-kotlin's Introduction

🗝️ dotenv-kotlin

Coverage Status Maven Central Codacy Badge All Contributors

A port of the Ruby dotenv project for Java and Kotlin. Load environment variables from a .env file.

dotenv

Looking for the pure Java version? Get dotenv-java.

Why dotenv?

Storing configuration in the environment is one of the tenets of a twelve-factor app. Anything that is likely to change between deployment environments–such as resource handles for databases or credentials for external services–should be extracted from the code into environment variables.

But it is not always practical to set environment variables on development machines or continuous integration servers where multiple projects are run. Dotenv load variables from a .env file into ENV when the environment is bootstrapped.

-- Brandon Keepers

Environment variables listed in the host environment override those in .env.

Use dotenv.get("...") instead of Java's System.getenv(...).

Install

Looking for the pure Java variant (no Kotlin), get dotenv-java.

Maven

<dependency>
    <groupId>io.github.cdimascio</groupId>
    <artifactId>dotenv-kotlin</artifactId>
    <version>6.4.1</version>
</dependency>

Previous versions

Gradle

Gradle Groovy DSL

implementation 'io.github.cdimascio:dotenv-kotlin:6.4.1'

Gradle Kotlin DSL

implementation("io.github.cdimascio:dotenv-kotlin:6.4.1")

Usage

Use dotenv.get("...") instead of Java's System.getenv(...). Here's why.

Create a .env file in the root of your project

# formatted as key=value
MY_ENV_VAR1=some_value
MY_EVV_VAR2=some_value

With Java

import io.github.cdimascio.dotenv.Dotenv;

Dotenv dotenv = Dotenv.load();
dotenv.get("MY_ENV_VAR1");

or with Kotlin

import io.github.cdimascio.dotenv.dotenv

val dotenv = dotenv()
dotenv["MY_ENV_VAR1"]

Android Usage

  • Create an assets folder

  • Add env (no dot) to the assets folder.

  • Configure dotenv to search /assets for a file with name env

     val dotenv = dotenv {
         directory = "/assets"
         filename = "env" // instead of '.env', use 'env'
     }
     dotenv["MY_ENV_VAR1"]

Note: The above configuration is required because dot files in /assets do not appear to resolve on Android. (Seeking recommendations from the Android community on how dotenv-kotlin configuration should work in order to provide the best experience for Android developers)

Alternatively, if you are using Provider android.resource you may specify

 directory = "android.resource://com.example.dimascio.myapp/raw"

Flutter Usage

Advices to use the package in the native Android layer prior to the flutter initialization.

  • Create an assets folder inside /android/app/src/main/
  • Add env (not dot) file to the assets folder.
  • Configure dotenv to search ./assets for a file with name env.
	val dotenv = dotenv {
	    directory = "./assets"
	    filename = "env" // instead of '.env', use 'env'
	}
	dotenv["MY_ENV_VAR1"] ?: ""
  • Is a good practice to ignore the env file from the repository. For this purpose you can use the .gitignore inside the android folder

Advanced Usage

Configure

Configure dotenv-kotlin once in your application.

With Java

Dotenv dotenv = Dotenv.configure()
        .directory("./some/path")
        .ignoreIfMalformed()
        .ignoreIfMissing()
        .load();

or with Kotlin

val dotenv = dotenv {
    directory = "./some/path"
    ignoreIfMalformed = true
    ignoreIfMissing = true
}

Get environment variables

Note, environment variables specified in the host environment take precedence over those in .env.

With Java

dotenv.get("HOME");
dotenv.get("MY_ENV_VAR1", "default value");

or with Kotlin

dotenv["HOME"]
dotenv["MY_ENV_VAR1"] ?: "default value"

Iterate over environment variables

Note, environment variables specified in the host environment take precedence over those in .env.

With Java

for (DotenvEntry e : dotenv.entries()) {
    System.out.println(e.getKey());
    System.out.println(e.getValue());
}

or with Kotlin

for (e in dotenv.entries()) {
    println(e.key)
    println(e.value)
}

Configuration options

optional directory

  • path specifies the directory containing .env. Dotenv first searches for .env using the given path on the filesystem. If not found, it searches the given path on the classpath. If directory is not specified it defaults to searching the current working directory on the filesystem. If not found, it searches the current directory on the classpath.

    Java example

     Dotenv
       .configure()
       .directory("/some/path")
       .load()

    Kotlin Dsl example

     dotenv {
       directory = "/some/path"
     }

optional filename

  • Use a filename other than .env. Recommended for use with Android (see details)

    Java example

     Dotenv
       .configure()
       .filename("myenv")
       .load();

    Kotlin Dsl example

     dotenv {
         filename = "myenv"
     }

optional ignoreIfMalformed

  • Do not throw when .env entries are malformed. Malformed entries are skipped.

    Java example

     Dotenv
       .configure()
       .ignoreIfMalformed()
       .load();

    Kotlin Dsl example

     dotenv {
       ignoreIfMalformed = true
     }

optional ignoreIfMissing

  • Do not throw when .env does not exist. Dotenv will continue to retrieve environment variables that are set in the environment e.g. dotenv["HOME"]

    Java example

     Dotenv
       .configure()
       .ignoreIfMissing()
       .load();

    Kotlin Dsl example

     dotenv {
       ignoreIfMissing = true
     }

optional systemProperties

  • Load environment variables into System properties, thus making all environment variables accessible via System.getProperty(...)

    Java example

     Dotenv
       .configure()
       .systemProperties()
       .load();

    Kotlin Dsl example

     dotenv {
       systemProperties = true
     }

Examples

FAQ

Q: Should I deploy a .env to e.g. production?

A: Tenant III of the 12 factor app methodology states "The twelve-factor app stores config in environment variables". Thus, it is not recommended to provide the .env file to such environments. dotenv, however, is super useful in e.g a local development environment as it enables a developer to manage the environment via a file which is more convenient.

Using dotenv in production would be cheating. This type of usage, however is an anti-pattern.

Q: Why should I use dotenv.get("MY_ENV_VAR") instead of System.getenv("MY_ENV_VAR")

A: Since Java does not provide a way to set environment variables on a currently running process, vars listed in .env cannot be set and thus cannot be retrieved using System.getenv(...).

Q: Can I use System.getProperty(...) to retrieve environment variables?

A: Sure. Use the systemProperties option. Or after initializing dotenv set each env var into system properties manually. For example:

Java

Dotenv dotenv = Dotenv.configure().load();
dotenv.entries().forEach(e -> System.setProperty(e.getKey(), e.getValue()));
System.getProperty("MY_VAR");

Kotlin

val dotenv = dotenv()
dotenv.entries().forEach { (key, value) -> System.setProperty(key, value) }

Q: Should I have multiple .env files?

A: No. We strongly recommend against having a "main" .env file and an "environment" .env file like .env.test. Your config should vary between deploys, and you should not be sharing values between environments.

In a twelve-factor app, env vars are granular controls, each fully orthogonal to other env vars. They are never grouped together as “environments”, but instead are independently managed for each deploy. This is a model that scales up smoothly as the app naturally expands into more deploys over its lifetime.

– The Twelve-Factor App

Q: Should I commit my .env file?

A: No. We strongly recommend against committing your .env file to version control. It should only include environment-specific values such as database passwords or API keys. Your production database should have a different password than your development database.

Q: What happens to environment variables that were already set?

A: dotenv-kotlin will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.

Q: What about variable expansion in .env?

A: We haven't been presented with a compelling use case for expanding variables and believe it leads to env vars that are not "fully orthogonal" as The Twelve-Factor App outlines. Please open an issue if you have a compelling use case.

Q: Can I supply a multi-line value?

A: dotenv-kotlin exhibits the same behavior as Java's System.getenv(...), thus if a multi-line value is needed you might consider encoding it via e.g. Base64. see this comment for details.

Note and reference: The FAQs present on motdotla's dotenv node project page are so well done that I've included those that are relevant in the FAQs above.

Contributors

Contributions are welcome!


Carmine DiMascio

💻 📖 🚇

Arniu Tseng

💻 📖 🚇

Paul Woolcock

🤔

Playacem

💻

Clément P.

💻

Harry Henry Gebel

📖

NyCode

📖

see CONTRIBUTING.md

License

see LICENSE (Apache 2.0)

Buy Me A Coffee

dotenv-kotlin's People

Contributors

allcontributors[bot] avatar amalpotra avatar arniu avatar cdimascio avatar cleymax avatar codacy-badger avatar dependabot[bot] avatar harryhenrygebel avatar nycodeghg avatar paulschwarz avatar playacem avatar tomasatisocco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

dotenv-kotlin's Issues

Support when no .env file is present

Currently Dotenv will throw an error if it is loaded when no .env file is present in the project. This causes a couple of problems especially when dealing with CI.

It is advised to not include the .env file in source control, this means there will be no .env file present when a service like Travis CI downloads the repository for testing. A service like Travis CI does export plenty of environment variables that can be used. Besides that CI services offer ways to export custom environment variables.

However it would be weird to have to switch between methods of retrieving environment variables just because you don't have the file. Just because there is no .env file present doesn't mean that there are no environment variables that are needed.

Perhaps a warning would be in order. Perhaps including an error for env variables that are not specified. (Note that leaving a variable might be different from not including one. A password can be blank for instance.)

Crashes on Android version 7 and older

Detected crashes for users using older versions of Android (API <= 24, i.e. Android 7 and older).
Setup is in line with your docs/examples and works just fine for newer versions of Android.

Stack traces:

Fatal Exception: java.lang.NoClassDefFoundError
Failed resolution of: Ljava/nio/file/Paths;

io.github.cdimascio.dotenv.internal.DotenvReader.read (DotenvReader.java:33)
io.github.cdimascio.dotenv.internal.DotenvParser.lines (DotenvParser.java:52)
io.github.cdimascio.dotenv.internal.DotenvParser.parse (DotenvParser.java:34)
io.github.cdimascio.dotenv.DotenvBuilder.load (DotenvBuilder.java:77)
io.github.cdimascio.dotenv.DslKt.dotenv (DslKt.java:19)
se.collectorbank.collectorbankbankapp.activities.CollectorActivity. (CollectorActivity.java:48)
se.collectorbank.collectorbankbankapp.activities.LoginActivity.access$startMainActivity (LoginActivity.java:58)
java.lang.Class.newInstance (Class.java)
android.app.Instrumentation.newActivity (Instrumentation.java:1083)
android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2682)
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2864)
android.app.ActivityThread.-wrap12 (ActivityThread.java)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1567)
android.os.Handler.dispatchMessage (Handler.java:105)
android.os.Looper.loop (Looper.java:156)
android.app.ActivityThread.main (ActivityThread.java:6517)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:942)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:832)

Caused by java.lang.ClassNotFoundException
Didn't find class "java.nio.file.Paths" on path: DexPathList[[zip file "/data/app/se.collector.bankapp-1/base.apk"],nativeLibraryDirectories=[/data/app/se.collector.bankapp-1/lib/arm64, /system/lib64, /vendor/lib64, /system/vendor/lib64, /product/lib64]]

dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:56)
java.lang.ClassLoader.loadClass (ClassLoader.java:380)
java.lang.ClassLoader.loadClass (ClassLoader.java:312)
arrow_right
io.github.cdimascio.dotenv.internal.DotenvReader.read (DotenvReader.java:33)
io.github.cdimascio.dotenv.internal.DotenvParser.lines (DotenvParser.java:52)
io.github.cdimascio.dotenv.internal.DotenvParser.parse (DotenvParser.java:34)
io.github.cdimascio.dotenv.DotenvBuilder.load (DotenvBuilder.java:77)
io.github.cdimascio.dotenv.DslKt.dotenv (DslKt.java:19)
se.collectorbank.collectorbankbankapp.activities.CollectorActivity. (CollectorActivity.java:48)
se.collectorbank.collectorbankbankapp.activities.LoginActivity.access$startMainActivity (LoginActivity.java:58)
java.lang.Class.newInstance (Class.java)
android.app.Instrumentation.newActivity (Instrumentation.java:1083)
android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2682)
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2864)
android.app.ActivityThread.-wrap12 (ActivityThread.java)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1567)
android.os.Handler.dispatchMessage (Handler.java:105)
android.os.Looper.loop (Looper.java:156)
android.app.ActivityThread.main (ActivityThread.java:6517)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:942)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:832)

Not working correctly when I execute a jar after gradle build

Hello, I am building a spring boot application with java-dotenv.

The .env is under "src/main/resources" folder and the application works perfectly when I start the application in my IDE(Intellj Idea).

A jar file is created by gradle when I build the project and I will get the following errors if I execute the jar file directly.

Suppressed: io.github.cdimascio.dotenv.DotEnvException: Could not find .\.env on the file system

I have read this project for reference and the project I created is similar to the kotlin-spring-mvc-template.

Not sure what was wrong. I would appreciate if you would give me some help.

Make dotenv env variables available in System.getProperty() too

Q: Why should I use dotenv.get(“MY_ENV_VAR”) instead of System.getenv(“MY_ENV_VAR”)
A: Since Java does not provide a way to set environment variables on a currently running process, vars listed in .env cannot be set and thus cannot be retrieved using System.getenv(…).

Given that System.getenv("MY_ENV_VAR") doesn't allow adding new environment variables at runtime, the other option is to plug the dotenv configured variables into System.setProperty().

This will allow libraries to use either System.getProperty("MY_ENV_VAR") or dotenv.get("MY_ENV_VAR").

A simple change would look like this after Dotenv is created.

Dotenv
   .load()
   .entries()
   .filter(entry -> System.getProperty(entry.getKey) == null)
   .forEach(entry -> System.setProperty(entry.getKey(), entry.getValue()));

Directory configuration not working correctly

I put the .env file inside / src / main / resources but still still giving the following error when I run .jar.

Caused by: io.github.cdimascio.dotenv.DotEnvException: Could not find ./.env on the classpath
	at io.github.cdimascio.dotenv.internal.ClasspathHelper.loadFileFromClasspath(ClassPathHelper.kt:37)
	at io.github.cdimascio.dotenv.internal.DotenvReader.read(DotenvReader.kt:36)
	at io.github.cdimascio.dotenv.internal.DotenvParser.parse(DotenvParser.kt:26)
	at io.github.cdimascio.dotenv.DotenvBuilder.load(Dotenv.kt:119)
	at io.github.cdimascio.dotenv.Dotenv$Instance.load(Dotenv.kt:32)
	at io.github.cdimascio.dotenv.Dotenv.load(Dotenv.kt)
	at com.org.teammove.utils.UtilDotenv.getEnv(UtilDotenv.java:10)
	at com.org.teammove.utils.UtilConectorPostgreSQL.getHOST_LOGIN(UtilConectorPostgreSQL.java:8)
	at com.org.teammove.autenticacao.AutenticacaoDatabaseConfig.dataSource(AutenticacaoDatabaseConfig.java:15)
	at com.org.teammove.autenticacao.AutenticacaoDatabaseConfig$$EnhancerBySpringCGLIB$$c94cd15a.CGLIB$dataSource$0(<generated>)
	at com.org.teammove.autenticacao.AutenticacaoDatabaseConfig$$EnhancerBySpringCGLIB$$c94cd15a$$FastClassBySpringCGLIB$$e0a583b5.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
	at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
	at com.org.teammove.autenticacao.AutenticacaoDatabaseConfig$$EnhancerBySpringCGLIB$$c94cd15a.dataSource(<generated>)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
	... 50 more

Version used is 5.1.1

I ended up viewing the other issues created, but none solved my problem.

HOME test failures on Windows

I just made a fresh fork of java-dotenv and after cloning my fork and running mvn test i receive a lot of test failures. The error is always the same.

[ERROR] Failures:
[ERROR]   DotEnvDslTest.dotenvIgnoreMalformed:34 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvDslTest.dotenvIgnoreMissing:91 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvDslTest.resourceCurrent:72 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvDslTest.resourceFilename:60 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvDslTest.resourceRelative:47 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvTest.dotenvFilename:57 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvTest.dotenvIgnoreMalformed:38 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvTest.dotenvIgnoreMissing:101 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvTest.resourceCurrent:82 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR]   DotEnvTest.resourceRelative:70 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[INFO]
[ERROR] Tests run: 14, Failures: 10, Errors: 0, Skipped: 0

In my real world project I fixed this [issue #11] by specifying the directory as ".":
Dotenv.configure().directory(".").ignoreIfMissing().load();

Errors when attempting to start it from a jar.

The error;

Exception in thread "main" java.lang.IncompatibleClassChangeError: Method 'io.github.cdimascio.dotenv.DotenvBuilder io.github.cdimascio.dotenv.Dotenv.configure()' must be Methodref constant
        at io.github.cdimascio.dotenv.DslKt.dotenv(Dsl.kt:13)
        at bot.hibikibot.HibikiBot.<clinit>(HibikiBot.kt:45)
        at bot.hibikibot.HibikiBotKt.main(HibikiBot.kt:154)
        at bot.hibikibot.HibikiBotKt$main$2.invoke(HibikiBot.kt)
        at bot.hibikibot.HibikiBotKt$main$2.invoke(HibikiBot.kt)
        at kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt$createCoroutineUnintercepted$$inlined$createCoroutineFromSuspendFunction$IntrinsicsKt__IntrinsicsJvmKt$1.invokeSuspend(IntrinsicsJvm.kt:205)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlin.coroutines.ContinuationKt.startCoroutine(Continuation.kt:115)
        at kotlin.coroutines.jvm.internal.RunSuspendKt.runSuspend(RunSuspend.kt:19)
        at bot.hibikibot.HibikiBotKt.main(HibikiBot.kt)

Code;

    val env = dotenv {
        directory = "./resources"
        filename = "hb.env"
    }
    
    var token: String = env["PROD_TOKEN"]!!

    if (args.any { it == "--dev" }) {
        token = env["DEV_TOKEN"]!!
    }

5.1.3 library version does not resolve correctly .env file location in jar file.

Steps to reproduce:

  • checkout project: https://github.com/cdimascio/kotlin-spring-mvc-template

  • replace 3.1.3 library version with 5.1.3

  • create .env file under src/main/resources

  • verify that running gradle bootRun command resolves .env file location correctly.
    image

  • verify that running gradle bootJar && java -jar build/libs/example-service-1.0.0.jar doesn't resolve .env files location properly
    image

Tested also with 3.1.3 version and it was working correctly back then.

Update:
Last working version: 3.1.4
First not working version: 3.1.5

How does this work with compiled jars?

Cool project! I'd like to try it and I just had a couple questions.

When the jar file is compiled, are the env vars compiled with it? is there a way to do that? or should the .env file reside next to the jar file for it to be read?

question - incorporating into build.gradle

what's the best practice for integrating this library as early as possible in a gradle based spring boot app? i was hoping that all gradle tasks (for example db migration tasks) would ingest the .env and use that configuration.

Getting environment variables inside docker container

How to get environment variables inside docker container?
Use Case:

Lets say I want to pass environment variables to my docker container but I don't want to make .env file part of the docker image. I would set environment variables in docker's yaml file and they will be available to the application running inside the container through System.getenv(). However In my case dotenv.load() would throw exception that /.env file is not on classpath. However dotenv does gets environment variables from system but in the scenario where .env isn't part of the container then it would fail throwing the exception.

Option to only load .env file env vars

I'm using this dotenv Java implementation in a scripted Jenkins pipeline and would like to load env vars from a CI env vars file we pull down from S3.

Apologies if this is stated somewhere in the code or documentation (I poked around extensively, but could not find anything). I would like to only load env vars from a .env file and not mix them w/ system/host env vars.

I have this:

@Grab('io.github.cdimascio:java-dotenv:5.0.1')
import io.github.cdimascio.dotenv.Dotenv
import io.github.cdimascio.dotenv.DotenvEntry

Dotenv dotenv = Dotenv.configure()
  .filename("ci-env-file-test")
  .ignoreIfMissing()
  .load()

for (DotenvEntry e : dotenv.entries()) {
    System.out.println("${e.getKey()}=${e.getValue()}")
}

This outputs the env vars in my test CI env vars file, but also mixes them with my system/host env vars. I see the use case for this, for sure. I also saw: https://github.com/cdimascio/java-dotenv/issues/25, which seems to imply the dotenv.entries() in v5.0.0 and below would do what I want, but @Grab'ing that version (w/ my code above) still returns the env vars from my CI test file and my system/host env vars.

Am I missing a param I can pass to the configure .load()... or?

ps: this is a great lib!

Multiline value

Is there any way to use a multi-line value in the .env file?

I've tried using double quotes, single quotes, backticks plus the \n char but I get the literal \n characters in the string when evaluated in Java code.

DotenvReader logic is flawed

While debugging issue #11 I found some interesting behaviour in the following tests:

  • DotEnvTest#dotenvMissing
  • DotEnvTest#dotenvIgnoreMissing
  • DotEnvDslTest#dotenvMissing
  • DotEnvDslTest#dotenvIgnoreMissing

I added the following line to the DotEnvReader: println("[dotenv] location: $location"), which results in the following output for all the above tests: [dotenv] location: /missing//.env

All tests have setting the directory with the value /missing/.env in common.
I guess we need to swap the order of operations to remove the duplicate slash.
The current solution would reduce the following valid path /missing/.env/ to the wrong /missing/

kotlin libs are required

Hi There,
I was happy to find your project, However I found that it requires kotlin libraries to run.
Trying the following failed.

            <groupId>io.github.cdimascio</groupId>
            <artifactId>java-dotenv</artifactId>
            <version>5.2.2</version>
            <exclusions>
                <exclusion>
                    <groupId>org.jetbrains.kotlin</groupId>
                    <artifactId>kotlin-stdlib</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

Is there no way we can compile this project for Java runtime only?
I need to keep my dependencies as light as possible, expected this project to be very small and not requiring any additional libraries.

Thanks.

Making dotenv variables globally available

I was wondering if there was any way to make the variables in the .env file globally available throughout my entire java application.

It seems as though configuring and loading the variables returns a Map of sorts from which you can retrieve all of the values. However I have to configure and load this variable in every file from which I wish to use it.

Dotenv env = Dotenv.configure().directory("./").load();

Is there any way I can load them once and use them everywhere? Perhaps even through the native System.getenv() static method? Running the configuration and loading once from my public static main method or something.

Android support

Can this lib work on Android? here is the error I got when trying to use it

 java.lang.NoClassDefFoundError: Failed resolution of: Ljava/nio/file/Paths;
                                                             at io.github.cdimascio.dotenv.internal.DotenvReader.read(DotenvReader.kt:20)
                                                             at io.github.cdimascio.dotenv.internal.DotenvParser.parse(DotenvParser.kt:18)
                                                             at io.github.cdimascio.dotenv.DotenvBuilder.load(Dotenv.kt:43)
                                                             at io.github.cdimascio.dotenv.Dotenv$Instance.load(Dotenv.kt:9)
                                                             at io.github.cdimascio.dotenv.Dotenv.load(Dotenv.kt)

Directory configuration not working correctly

OS: MacOS v10.13.4
Java version: JavaSE-1.8
Dotenv version: 3.1.0


When configuring the directory Dotenv uses it seems to make a difference weather or not you use a dot in the path.

The following code works just fine:

Dotenv env = Dotenv.configure().directory("./").load();

However this code throws an error:

Dotenv env = Dotenv.configure().directory("/").load();
Exception in thread "main" io.github.cdimascio.dotenv.DotEnvException: Could not find /.env on the classpath
	at io.github.cdimascio.dotenv.internal.ClasspathHelper.loadFileFromClasspath(ClassPathHelper.kt:28)
	at io.github.cdimascio.dotenv.internal.DotenvReader.read(DotenvReader.kt:26)
	at io.github.cdimascio.dotenv.internal.DotenvParser.parse(DotenvParser.kt:18)
	at io.github.cdimascio.dotenv.DotenvBuilder.load(Dotenv.kt:48)
	at dotenv_test.Main.main(Main.java:9)

Removing the configuration entirely should according to the documentation load the dotenv file from the root of the project: ./ however this throws an error too. Which seems especially weird to me.

Quoted variable

How works with quoted variables?

export JDBC_URL="jdbc:hive2://[domain]:10000/default;principal=hive/_HOST@[REALM]"
String url = JDBC_URL;
Connection conn = DriverManager.getConnection(url.replace("\"", ""));

Getting an error when running a jar that uses dotenv

Error: Could not find or load main class io.cdimascio.DotenvKt

It happens when I try to run the jar from a docker container. I guess the docker doesn't find the java classpath for Dotenv.

I use gradle - so in the dependencies I have: compile 'io.github.cdimascio:java-dotenv:5.2.1'

Any ideas what to do? Do I need the actual Dotenv.kt file in my project?

@cdimascio

.env file and Travis

Afternoon,

Thanks for this, been trying to learn Java and using this file for a project I am building.

Just wanted to ask as I am currently having an issue with regards to Travis-ci and it reading my .env file. I know we shouldn't upload it to Github so have kept the file locally but when my setup goes through Travis before loading to Heroku it gives me the following error message:

io.github.cdimascio.dotenv.DotEnvException: Could not find /.env on the classpath

Would this be a situation where I have to set the classpath somewhere for it to know where to get the environment variables from? Know I have used .env with Node.js and didn't commit the files to GitHub but t knew the variables when the project was launched to Heroku.

Apologies if I sound a bit of a beginner. Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.