Giter Club home page Giter Club logo

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

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?

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.

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.

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

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!

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.

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

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.

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("\"", ""));

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.

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.

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.

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)

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/

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();

.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

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.)

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)

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()));

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.