dune icon indicating copy to clipboard operation
dune copied to clipboard

dotenv support

Open yawaramin opened this issue 6 months ago • 3 comments

Desired Behavior

Dune should support a project-wide .env file.

Dune should automatically run executables in the current project with an environment that includes all environment variables defined in a .env file in the project root directory, if such a file is found.

Example

With a project like:

.env
dune
dune-project
main.ml

Where .env contains FOO=bar and dune contains (executable (name main)).

When we run dune exec ./main.exe, the main executable should have access to the FOO environment variable with the value bar.

yawaramin avatar Jun 11 '25 02:06 yawaramin

What do you gain over running dune inside your dotenv runner? E.g. $ dotenvx run dune exec ..

rgrinberg avatar Jun 12 '25 22:06 rgrinberg

Make the local DX easier. Same as with dune implementing watch mode itself instead of relying on a third-party tool.

A related question: if we use opam exec with dotenvx, which goes first?

opam exec -- dotenvx run dune exec ...
# or
dotenvx run opam exec -- dune exec ...

If dune automatically injects an environment from a .env file, we don't have to even think about this.

yawaramin avatar Jun 13 '25 02:06 yawaramin

Same as with dune implementing watch mode itself instead of relying on a third-party tool.

We did that in early versions. The approach was later abandoned because every 3rd party tool we've tried had either quality or portability issues. There is nothing fundamentally wrong with this approach though.

In your first invocation, your dotenv runner can be looked in an opam package.

In your second invocation, your opam binary can be customized via the.env file.

Which is better probably depends on the use case.

If dune has to read the dotenv file, then dune can no longer be looked up from the dotenv environment. That would mean that for opam users for example, one would still need to do opam exec -- dune .. to load the .env environment.

There is indeed one advantage for dune to load the .env file though: dune would be able to automatically reload it in watch mode. I don't know if this is enough to justify implementing this feature. It's certainly not enough to motivate me to do it, but if someone else is interested, I wouldn't personally mind.

rgrinberg avatar Jun 14 '25 00:06 rgrinberg