diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..30fb9dd --- /dev/null +++ b/.env.example @@ -0,0 +1,12 @@ +PORT= + +APP_NAME= +APP_ENV= +APP_KEY= +APP_DEBUG= +APP_URL= +APP_TIMEZONE= + +DATABASE_URL= +SECRET_KEY= +API_TOKEN= diff --git a/src/dot_env.gleam b/src/dot_env.gleam index 08e5342..a486a15 100644 --- a/src/dot_env.gleam +++ b/src/dot_env.gleam @@ -1,7 +1,9 @@ import dot_env/env import dot_env/internal/parser +import dot_env/internal/template import gleam/bool import gleam/io +import gleam/option.{type Option, None, Some} import gleam/result.{try} import gleam/string import simplifile @@ -11,6 +13,10 @@ pub type Opts { Opts( /// The path to the .env file relative to the project root eg. .env and src/.env are two different things, .env points to the root of the project, src/.env points to the src folder in the root of the project path: String, + /// Warn if variables defined in the template file (by default `{path}.example`) are missing from both the `.env` file and the environment. + validate_template: Bool, + /// Specify a template_path (by default `{path}.example` if not set explicitly) + template_path: Option(String), /// Print debug information if something goes wrong debug: Bool, /// Force all keys to be uppercase @@ -24,11 +30,20 @@ pub type Opts { } pub opaque type DotEnv { - DotEnv(path: String, debug: Bool, capitalize: Bool, ignore_missing_file: Bool) + DotEnv( + path: String, + validate_template: Bool, + template_path: Option(String), + debug: Bool, + capitalize: Bool, + ignore_missing_file: Bool, + ) } pub const default = DotEnv( path: ".env", + validate_template: True, + template_path: None, debug: True, capitalize: True, ignore_missing_file: True, @@ -44,6 +59,23 @@ pub fn new_with_path(path: String) -> DotEnv { DotEnv(..default, path: path) } +/// Set whether to warn if variables defined in the template file (by default `{path}.example`) are missing from both the `.env` file and the environment. +/// +/// If set to `True`, a warning will be printed for any missing variables. +pub fn set_validate_template( + instance: DotEnv, + validate_template: Bool, +) -> DotEnv { + DotEnv(..instance, validate_template: validate_template) +} + +/// Set a specific file path to use as the template for environment variable validation. +/// +/// If not set, it defaults to the path of the `.env` file with `.example` appended (e.g., `.env.example`). +pub fn set_template_path(instance: DotEnv, template_path: String) -> DotEnv { + DotEnv(..instance, template_path: Some(template_path)) +} + /// Set whether to print debug information in the current DotEnv instance pub fn set_debug(instance: DotEnv, debug: Bool) -> DotEnv { DotEnv(..instance, debug: debug) @@ -88,6 +120,8 @@ pub fn path(instance: DotEnv) -> String { pub fn load(dotenv: DotEnv) -> Nil { load_with_opts(Opts( path: dotenv.path, + validate_template: dotenv.validate_template, + template_path: dotenv.template_path, debug: dotenv.debug, capitalize: dotenv.capitalize, ignore_missing_file: dotenv.ignore_missing_file, @@ -119,22 +153,42 @@ pub fn load_default() -> Nil { /// /// ```gleam /// import dot_env +/// import gleam/option.{None} /// /// pub fn main() { -/// dot_env.load_with_opts(dot_env.Opts(path: "src/.env", debug: False, capitalize: False)) +/// dot_env.load_with_opts(dot_env.Opts( +/// path: "src/.env", +/// validate_template: True, +/// template_path: None, +/// debug: False, +/// capitalize: False, +/// ignore_missing_file: False, +/// )) /// } /// ``` pub fn load_with_opts(opts: Opts) { let dotenv = case opts { - Opts(path, debug, capitalize, ignore_missing_file) -> - DotEnv(path, debug, capitalize, ignore_missing_file) + Opts( + path, + validate_template, + template_path, + debug, + capitalize, + ignore_missing_file, + ) -> + DotEnv( + path, + validate_template, + template_path, + debug, + capitalize, + ignore_missing_file, + ) Default -> default } - let state = dotenv |> load_and_return_error - - case state { - Ok(_) -> Nil + case load_and_return_error(dotenv) { + Ok(config) -> validate_template(dotenv, config) Error(msg) -> { use <- bool.guard(when: !dotenv.debug, return: Nil) io.println_error(msg) @@ -142,16 +196,46 @@ pub fn load_with_opts(opts: Opts) { } } -fn load_and_return_error(dotenv: DotEnv) -> Result(Nil, String) { +fn load_and_return_error( + dotenv: DotEnv, +) -> Result(List(#(String, String)), String) { use content <- try( - read_file(dotenv) + read_file(dotenv.path) |> handle_file_result(dotenv.ignore_missing_file), ) - use kv_pairs <- try(parser.parse(content)) + use config <- try(parser.parse(content)) + + use _ <- try(dotenv |> recursively_set_environment_variables(config)) - dotenv - |> recursively_set_environment_variables(kv_pairs) + Ok(config) +} + +fn validate_template(dotenv: DotEnv, config: List(#(String, String))) -> Nil { + use <- bool.guard(when: !dotenv.validate_template, return: Nil) + + let template_path = case dotenv.template_path { + Some(path) -> path + None -> dotenv.path <> ".example" + } + + let res = { + use content <- try( + read_file(template_path) + |> handle_file_result(dotenv.ignore_missing_file), + ) + use config_example <- try(parser.parse(content)) + + template.missing_keys(config, config_example, dotenv.capitalize) |> Ok + } + + case res { + Ok(missing) -> warn_missing_keys(missing) + Error(error) -> { + use <- bool.guard(when: !dotenv.debug, return: Nil) + io.println_error(error <> "\nSkipping template check") + } + } } fn handle_file_result( @@ -186,9 +270,9 @@ fn recursively_set_environment_variables( } } -fn read_file(dotenv: DotEnv) -> Result(String, String) { +fn read_file(path: String) -> Result(String, String) { use is_file <- result.try( - simplifile.is_file(dotenv.path) + simplifile.is_file(path) |> result.map_error(with: fn(_) { "Failed to access file, ensure the file exists and is a readable file" }), @@ -196,17 +280,33 @@ fn read_file(dotenv: DotEnv) -> Result(String, String) { use <- bool.guard( when: !is_file, - return: Error("Specified file at `" <> dotenv.path <> "` does not exist"), + return: Error("Specified file at `" <> path <> "` does not exist"), ) use contents <- result.try( - simplifile.read(dotenv.path) + simplifile.read(path) |> result.map_error(with: fn(_) { "Unable to read file at `" - <> dotenv.path + <> path <> "`, ensure the file exists and is readable" }), ) Ok(contents) } + +fn warn_missing_keys(keys: List(String)) { + case keys { + [] -> Nil + _ -> { + let joined_vars = string.join(keys, with: ", ") + let warning_msg = + "The following variables were defined in the example file but are missing from both the `.env` file and the environment:\n" + <> " " + <> joined_vars + <> "\n" + <> "Make sure to add them to your env file." + io.println_error(warning_msg) + } + } +} diff --git a/src/dot_env/internal/template.gleam b/src/dot_env/internal/template.gleam new file mode 100644 index 0000000..972580b --- /dev/null +++ b/src/dot_env/internal/template.gleam @@ -0,0 +1,35 @@ +import dot_env/env +import gleam/dict +import gleam/list +import gleam/string + +pub fn missing_keys( + config: List(#(String, String)), + config_example: List(#(String, String)), + capitalize: Bool, +) -> List(String) { + let config_dict = dict.from_list(config) + + list.fold(config_example, [], fn(acc, kv) { + let #(key, _) = kv + + let look_up_key = case capitalize { + True -> string.uppercase(key) + False -> key + } + + let is_set = has_env(look_up_key) || dict.has_key(config_dict, key) + case is_set { + True -> acc + False -> [key, ..acc] + } + }) + |> list.reverse +} + +fn has_env(key: String) -> Bool { + case env.get_string(key) { + Ok(_) -> True + Error(_) -> False + } +} diff --git a/src/dot_env_ffi.mjs b/src/dot_env_ffi.mjs index ce0a773..5bfc1b2 100644 --- a/src/dot_env_ffi.mjs +++ b/src/dot_env_ffi.mjs @@ -62,7 +62,7 @@ export function get_env(key) { } if (value == Nil || value === undefined) { - return new GleamError(Nil); + return new GleamError(`key ${key} is not set`); } return new GleamOk(value); diff --git a/test/dot_env_test.gleam b/test/dot_env_test.gleam index d13a621..9131c2b 100644 --- a/test/dot_env_test.gleam +++ b/test/dot_env_test.gleam @@ -1,5 +1,7 @@ import dot_env.{Opts} import dot_env/env +import dot_env/internal/template +import gleam/option.{None} import gleeunit import gleeunit/should @@ -44,6 +46,8 @@ pub fn load_missing_env_file_test() { // This should not fail or crash dot_env.load_with_opts(Opts( path: ".definitely_not_a_real_file", + validate_template: False, + template_path: None, debug: True, capitalize: True, ignore_missing_file: True, @@ -81,6 +85,8 @@ pub fn load_default_test() { pub fn load_normal_test() { dot_env.load_with_opts(Opts( path: ".env.normal", + validate_template: False, + template_path: None, debug: True, capitalize: True, ignore_missing_file: False, @@ -191,6 +197,8 @@ pub fn load_normal_test() { pub fn load_multiline_test() { dot_env.load_with_opts(Opts( path: ".env.multiline", + validate_template: False, + template_path: None, debug: True, capitalize: True, ignore_missing_file: False, @@ -257,6 +265,8 @@ pub fn load_multiline_test() { pub fn get_bool_test() { dot_env.load_with_opts(Opts( path: ".env.booleans", + validate_template: False, + template_path: None, debug: True, capitalize: True, ignore_missing_file: False, @@ -274,3 +284,36 @@ pub fn get_bool_test() { env.get_bool("BOOL_TRUE") |> should.equal(Ok(True)) } + +pub fn no_missing_keys_test() { + let config = [ + #("PORT", "9000"), + #("HOST", "localhost"), + ] + + let example = [ + #("PORT", ""), + #("HOST", ""), + ] + + template.missing_keys(config, example, True) + |> should.equal([]) +} + +pub fn missing_keys_test() { + let config = [ + #("PORT", "9000"), + ] + + let example = [ + #("PORT", ""), + #("HOST", ""), + #("DATABASE_URL", ""), + ] + + template.missing_keys(config, example, True) + |> should.equal([ + "HOST", + "DATABASE_URL", + ]) +}