Quantcast
Channel: OCaml - Topics tagged dune
Viewing all articles
Browse latest Browse all 595

How to generate different code based on an environmental variable at build time

$
0
0

I would like to read a OCaml variable, based on an environmental variable that was passed at build time.

Currently I am doing the following:
env_gen.ml

let () =
  let env = Sys.getenv_opt "MY_ENV" |> Option.value ~default:"default" in
  let oc = open_out "env_generated.ml" in
  Printf.fprintf oc "let env = %S\n" env;
  close_out oc

in a dune file:

(rule
 (targets env_generated.ml)
 (deps env_gen.ml)
 (action (run ocaml env_gen.ml)))

This correctly gets MY_ENV:

MY_ENV=foo dune build --profile release

env_generator.ml will have let env = "foo"

However, if I run the build without cleaning up first:

dune build
MY_ENV=foo dune build --profile release

env_generator.ml ends up stale and will have let env = "default"

Is there a better built-in method to generate that file?
Is there a way to avoid it being cached and requiring a _build directory cleanup before running MY_ENV .. to avoid stale values?

5 posts - 3 participants

Read full topic


Viewing all articles
Browse latest Browse all 595

Trending Articles