Current section

Files

Jump to
dotenv_gleam src dotenv_gleam.erl
Raw

src/dotenv_gleam.erl

-module(dotenv_gleam).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-define(FILEPATH, "src/dotenv_gleam.gleam").
-export([config_with/1, config/0]).
-export_type([dot_env_error/0]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-type dot_env_error() :: {error_reading_env_file, simplifile:file_error()}.
-file("src/dotenv_gleam.gleam", 52).
?DOC(
" Tries to load environment variables from a file specified in the current\n"
" working directory.\n"
" this function returns a result with the error if it's not possible to read\n"
" the file.\n"
"\n"
" ## Examples\n"
"\n"
" ```gleam\n"
" > let assert Ok(Nil) = config_with(\"path/to/.env\")\n"
" > envoy.get(\"TEST\")\n"
" Ok(\"test\")\n"
" ```\n"
"\n"
" ```gleam\n"
" > use _ <- result.try(config_with(\"path/to/.env\"))\n"
" > envoy.get(\"TEST\")\n"
" Ok(\"test\")\n"
" ```\n"
).
-spec config_with(binary()) -> {ok, nil} | {error, dot_env_error()}.
config_with(File) ->
gleam@result:map(
begin
_pipe = simplifile:read(File),
gleam@result:map_error(
_pipe,
fun(Field@0) -> {error_reading_env_file, Field@0} end
)
end,
fun(Env_file) -> _pipe@1 = gleam@string:split(Env_file, <<"\n"/utf8>>),
_pipe@2 = gleam@list:filter(
_pipe@1,
fun(Line) -> Line /= <<""/utf8>> end
),
gleam@list:each(
_pipe@2,
fun(Line@1) ->
Splited_line = gleam@string:split(Line@1, <<"="/utf8>>),
Key = begin
_pipe@3 = gleam@list:first(Splited_line),
_pipe@4 = gleam@result:unwrap(_pipe@3, <<""/utf8>>),
gleam@string:trim(_pipe@4)
end,
Value = begin
_pipe@5 = gleam@list:drop(Splited_line, 1),
_pipe@6 = gleam@string:join(_pipe@5, <<"="/utf8>>),
gleam@string:trim(_pipe@6)
end,
envoy_ffi:set(Key, Value)
end
) end
).
-file("src/dotenv_gleam.gleam", 30).
?DOC(
" Tries to load environment variables from a `.env` file in the current\n"
" working directory.\n"
" this function returns a result with the error if it's not possible to read\n"
" the file.\n"
"\n"
" ## Examples\n"
"\n"
" ```gleam\n"
" > let assert Ok(Nil) = config()\n"
" > envoy.get(\"TEST\")\n"
" Ok(\"test\")\n"
" ```\n"
"\n"
" ```gleam\n"
" > use _ <- result.try(config())\n"
" > envoy.get(\"TEST\")\n"
" Ok(\"test\")\n"
" ```\n"
).
-spec config() -> {ok, nil} | {error, dot_env_error()}.
config() ->
config_with(<<".env"/utf8>>).