-module(envie_ffi). -export([get_env/1, set_env/2, unset_env/1, all_env/0, read_file/1, rescue/1]). get_env(Name) when is_binary(Name) -> case os:getenv(binary_to_list(Name)) of false -> {error, nil}; Value -> {ok, list_to_binary(Value)} end. set_env(Name, Value) when is_binary(Name), is_binary(Value) -> os:putenv(binary_to_list(Name), binary_to_list(Value)), nil. unset_env(Name) when is_binary(Name) -> os:unsetenv(binary_to_list(Name)), nil. all_env() -> Env = os:getenv(), lists:foldl( fun(Entry, Acc) -> case string:split(Entry, "=", leading) of [Key, Value] -> maps:put(list_to_binary(Key), list_to_binary(Value), Acc); [Key] -> maps:put(list_to_binary(Key), <<>>, Acc); _ -> Acc end end, #{}, Env ). read_file(Path) when is_binary(Path) -> case file:read_file(Path) of {ok, Content} -> {ok, Content}; {error, _} -> {error, nil} end. rescue(Fn) -> try {ok, Fn()} catch Class:Reason:Stacktrace -> Msg = io_lib:format("~p:~p at ~p", [Class, Reason, Stacktrace]), {error, list_to_binary(lists:flatten(Msg))} end.