Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add getenv_strict variant #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions src/ppx_getenv.ml
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,27 @@ open Ppxlib

let getenv s = try Sys.getenv s with Not_found -> ""

let expander ~loc ~path:_ = function
let getenv_strict ~loc s =
try Sys.getenv s
with Not_found -> Location.raise_errorf ~loc "[%%getenv_strict] not set: %s" s

let expander ~strict ~loc ~path:_ = function
| (* Should have a single structure item, which is evaluation of a constant string. *)
PStr [{ pstr_desc =
Pstr_eval ({ pexp_loc = loc;
pexp_desc = Pexp_constant (Pconst_string (sym, _, None)); _ }, _); _ }] ->
(* Replace with a constant string with the value from the environment. *)
Ast_builder.Default.estring ~loc (getenv sym)
Ast_builder.Default.estring ~loc (if strict then getenv_strict ~loc sym else getenv sym)
| _ ->
Location.raise_errorf ~loc "[%%getenv] accepts a string, e.g. [%%getenv \"USER\"]"

let extension =
Context_free.Rule.extension
(Extension.declare "getenv" Expression Ast_pattern.(__) expander)
(Extension.declare "getenv" Expression Ast_pattern.(__) (expander ~strict:false))

let extension_strict =
Context_free.Rule.extension
(Extension.declare "getenv_strict" Expression Ast_pattern.(__) (expander ~strict:true))

let () = Ppxlib.Driver.register_transformation ~rules:[extension] "ppx_getenv"
let () = Ppxlib.Driver.register_transformation ~rules:[extension_strict] "ppx_getenv_strict"