feat: prevent fields with invalid types
parent
a1ab5d55b3
commit
5fd74631eb
17
conf.v
17
conf.v
|
@ -51,6 +51,17 @@ fn (ld LoadConfig) get_env_var(field_name string) !(bool, string) {
|
|||
// given from an environment variable, a value defined in the config file or a
|
||||
// configured default if present, in that order.
|
||||
pub fn load<T>(ld LoadConfig) !T {
|
||||
// Ensure all struct fields consist of supported types
|
||||
$for field in T.fields {
|
||||
$if field.typ is string || field.typ is int {
|
||||
} $else {
|
||||
// I'd prefer changing this to $compile_error, but as of V 0.3.2,
|
||||
// this seems to be bugged. If I replace this call with a
|
||||
// $compile_error call, the error *always* happens, even if all
|
||||
// fields are correct.
|
||||
return error('Field $field.name is of an unsupported type.')
|
||||
}
|
||||
}
|
||||
mut res := T{}
|
||||
|
||||
// This array allows us to determine later whether the variable is actually
|
||||
|
@ -73,9 +84,6 @@ pub fn load<T>(ld LoadConfig) !T {
|
|||
res.$(field.name) = s.string()
|
||||
} $else $if field.typ is int {
|
||||
res.$(field.name) = s.int()
|
||||
// This seems to not work in V 0.3.2
|
||||
//} $else {
|
||||
// $compile_error('Unsupported config struct field type detected.')
|
||||
}
|
||||
|
||||
has_value.add(field.name)
|
||||
|
@ -93,9 +101,6 @@ pub fn load<T>(ld LoadConfig) !T {
|
|||
res.$(field.name) = env_value
|
||||
} $else $if field.typ is int {
|
||||
res.$(field.name) = env_value.int()
|
||||
// This seems to not work in V 0.3.2
|
||||
//} $else {
|
||||
// $compile_error('Unsupported config struct field type detected.')
|
||||
}
|
||||
|
||||
has_value.add(field.name)
|
||||
|
|
|
@ -0,0 +1,10 @@
|
|||
module conf
|
||||
|
||||
struct WrongTypeConfig {
|
||||
f map[string]string
|
||||
}
|
||||
|
||||
fn test_wrong_type() {
|
||||
conf := load<WrongTypeConfig>() or { return }
|
||||
assert false
|
||||
}
|
|
@ -181,3 +181,8 @@ fn test_int_absent_default_empty() {
|
|||
some_int: 0
|
||||
}
|
||||
}
|
||||
|
||||
/* fn test_int_wrong_type() { */
|
||||
/* conf := load<SingleConf>(default_path: 'test/int_wrong_type.toml') or { return } */
|
||||
/* assert false */
|
||||
/* } */
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
some_int = '1'
|
Loading…
Reference in New Issue