This commit is contained in:
swrup 2025-11-11 02:07:51 +01:00
parent aa2ff7b2f0
commit 2f3113f55d
11742 changed files with 1223940 additions and 0 deletions

View file

@ -0,0 +1,24 @@
# ppx_get_env
This folder contains an example of a very simple ppx rewriter that will expand
`[%get_env "SOME_ENV_VAR"]` into the value of the env variable `SOME_ENV_VAR` at compile time,
as a string.
E.g., assuming we set `MY_VAR="foo"`, it will turn:
```ocaml
let () = print_string [%get_env "MY_VAR"]
```
into:
```ocaml
let () = print_string "foo"
```
Note that this is just a toy example and we'd actually advise you against this type of ppx
that have side effects or rely heavily on the file system or env variables unless you absolutely know
what you are doing.
In particular in this case it won't work well with dune since dune won't know about the dependency
on the env variables specified in the extension's payload.

View file

@ -0,0 +1,4 @@
(library
(name ppx_get_env)
(kind ppx_rewriter)
(libraries ppxlib))

View file

@ -0,0 +1,20 @@
open Ppxlib
let expand ~ctxt env_var =
let loc = Expansion_context.Extension.extension_point_loc ctxt in
match Sys.getenv env_var with
| value -> Ast_builder.Default.estring ~loc value
| exception Not_found ->
let ext =
Location.error_extensionf ~loc "The environement variable %s is unbound"
env_var
in
Ast_builder.Default.pexp_extension ~loc ext
let my_extension =
Extension.V3.declare "get_env" Extension.Context.expression
Ast_pattern.(single_expr_payload (estring __))
expand
let rule = Ppxlib.Context_free.Rule.extension my_extension
let () = Driver.register_transformation ~rules:[ rule ] "get_env"