diff --git a/conf.v b/conf.v index c3865ca..3ebc194 100644 --- a/conf.v +++ b/conf.v @@ -2,6 +2,7 @@ module conf import os import toml +import datatypes { Set } // get_env_var tries to read the contents of the given environment variable. It // looks for either `${env.prefix}${field_name.to_upper()}` or @@ -54,7 +55,7 @@ pub fn load(conf LoadConfig) !T { // This array allows us to determine later whether the variable is actually // zero or just a null'ed struct field - mut has_value := map[string]bool{} + mut has_value := Set{} // Later, this could be read from an env var as well. path := conf.default_path @@ -77,7 +78,7 @@ pub fn load(conf LoadConfig) !T { // $compile_error('Unsupported config struct field type detected.') } - has_value[field.name] = true + has_value.add(field.name) } } } @@ -97,12 +98,31 @@ pub fn load(conf LoadConfig) !T { // $compile_error('Unsupported config struct field type detected.') } - has_value[field.name] = true + has_value.add(field.name) } - if !(has_value[field.name] or { false }) { + // Finally, if there's no env var present either, we check whether the + // variable has a default value + if !has_value.exists(field.name) { + mut has_default := false + + $if field.typ is string { + has_default = res.$(field.name) != '' + } $else $if field.typ is int { + has_default = res.$(field.name) != 0 + } + + if has_default { + has_value.add(field.name) + } + } + + // If there's no value provided in any way, we notify the user with an + // error. + if !has_value.exists(field.name) { return error("Missing config variable '$field.name' with no provided default. Either add it to the config file or provide it using an environment variable.") } } + return res } diff --git a/string_test.v b/string_test.v new file mode 100644 index 0000000..c498b11 --- /dev/null +++ b/string_test.v @@ -0,0 +1,35 @@ +module conf + +struct SingleConf { + some_string string +} + +struct SingleConfDefault { + some_string string = 'default' +} + +fn test_string_present_no_default() { + conf := load(default_path: 'test/string.toml')! + assert conf == SingleConf{ + some_string: 'hi' + } +} + +fn test_string_absent_no_default() { + conf := load(default_path: 'test/empty.toml') or { return } + assert false +} + +fn test_string_present_default() { + conf := load(default_path: 'test/string.toml')! + assert conf == SingleConfDefault{ + some_string: 'hi' + } +} + +fn test_string_absent_default() { + conf := load(default_path: 'test/empty.toml')! + assert conf == SingleConfDefault{ + some_string: 'default' + } +} diff --git a/test/empty.toml b/test/empty.toml new file mode 100644 index 0000000..e69de29 diff --git a/test/string.toml b/test/string.toml new file mode 100644 index 0000000..85c27d0 --- /dev/null +++ b/test/string.toml @@ -0,0 +1 @@ +some_string = "hi"