feat: hopefully allow configuring zero as value

main
Jef Roosens 2022-12-28 16:42:19 +01:00
parent 8b0cb4ab2d
commit d705dc0ec1
1 changed files with 18 additions and 16 deletions

34
conf.v
View File

@ -40,9 +40,9 @@ fn get_env_var(prefix string, field_name string, file_suffix string) !string {
[params] [params]
pub struct LoadConfig { pub struct LoadConfig {
prefix string prefix string
file_suffix string = '_FILE' file_suffix string = '_FILE'
default_path string default_path string
} }
// load<T> attempts to create an object of type T from the given path to a toml // load<T> attempts to create an object of type T from the given path to a toml
@ -52,8 +52,12 @@ pub struct LoadConfig {
pub fn load<T>(conf LoadConfig) !T { pub fn load<T>(conf LoadConfig) !T {
mut res := T{} mut res := T{}
// Later, this could be read from an env var as well. // This array allows us to determine later whether the variable is actually
path := conf.default_path // zero or just a null'ed struct field
mut has_value := map[string]bool{}
// Later, this could be read from an env var as well.
path := conf.default_path
if os.exists(path) { if os.exists(path) {
// We don't use reflect here because reflect also sets any fields not // We don't use reflect here because reflect also sets any fields not
@ -68,7 +72,11 @@ pub fn load<T>(conf LoadConfig) !T {
res.$(field.name) = s.string() res.$(field.name) = s.string()
} $else $if field.typ is int { } $else $if field.typ is int {
res.$(field.name) = s.int() res.$(field.name) = s.int()
} $else {
$compile_error('Unsupported config struct field type detected.')
} }
has_value[field.name] = true
} }
} }
} }
@ -83,20 +91,14 @@ pub fn load<T>(conf LoadConfig) !T {
res.$(field.name) = env_value res.$(field.name) = env_value
} $else $if field.typ is int { } $else $if field.typ is int {
res.$(field.name) = env_value.int() res.$(field.name) = env_value.int()
} $else {
$compile_error('Unsupported config struct field type detected.')
} }
has_value[field.name] = true
} }
// Now, we check whether a value is present. If there isn't, that means if !(has_values[field.name] or { false }) {
// it isn't in the config file, nor is there a default or an env var.
mut has_value := false
$if field.typ is string {
has_value = res.$(field.name) != ''
} $else $if field.typ is int {
has_value = res.$(field.name) != 0
}
if !has_value {
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 error("Missing config variable '$field.name' with no provided default. Either add it to the config file or provide it using an environment variable.")
} }
} }