Where to write `env` stanza in a dune file to modify environment variables

Hi !
I need to modify environment variables to compile a project. I work with dune and I saw there and there that one can modify environment variables during dune building process, using env stanza. However, I do not understand where to write env stanza to make it work.
Here is my dune file:

(env
    (_
     (env-vars
       (DB_HOST localhost)
       (DB_PORT 3000)
       (DB_NAME db)
       (DB_PASSWORD "***")
     )
    )
)

(library
  (name administrative_book)
  (libraries type pgocaml pgocaml_ppx ocsigen-start.server)
  (preprocess (pps ppx_deriving.std pgocaml pgocaml_ppx))
  
)

When I try dune build core/administrative_book/administrative_book.a, I get an error message showing me that environment variable was not the ones I defined in dune file.
I tried to put env stanza after or inside library stanza (inside it stated that env stanza was not suited there).
In case, I have no dune-workspace file, and here is my dune-project file:

(lang dune 2.0)
(name myproject)
(version 1.0)

Do you know where to write env stanza ?
Thank you for your help !

1 Like

This looks like a bug in Dune indeed. However and assuming this bug is fixed, note that if dune doesn’t know that a ppx rewriter reads these environment variables, it will not re-build things when you change the value of these variables.

You can declare that the ppx rewriter will read these by adding a preprocessor_deps field:

(library
  (name administrative_book)
  (libraries type pgocaml pgocaml_ppx ocsigen-start.server)
  (preprocessor_deps (env_var DB_HOST) (env_var DB_PORT) ...)
  (preprocess (pps ppx_deriving.std pgocaml pgocaml_ppx))
  
)

Alternatively, a preferred method is to pass information to ppx rewriters via cookies. In the definition of the ppx rewriter you could add:

(library
 (name pgocaml)
 (kind
  (ppx_rewriter
   (cookies
    (DB_HOST %{env:DB_HOST})
    (DB_PORT %{env:DB_PORT))
    ...)))

and access it inside the ppx rewriter via the cookies API.

3 Likes

Thanks a lot @jeremiedimino ! In fact there is no such bug there, I just messed up with the names of environment variables, sorry for this. Anyway, I keep your solution in my mind in case I encounter a problem with ppx regarding this.
Have a good day !

No problem, have a good day too !