feat: prevent fields with invalid types

main
Jef Roosens 2022-12-28 19:43:10 +01:00
parent a1ab5d55b3
commit 5fd74631eb
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
4 changed files with 27 additions and 6 deletions

17
conf.v
View File

@ -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 // given from an environment variable, a value defined in the config file or a
// configured default if present, in that order. // configured default if present, in that order.
pub fn load<T>(ld LoadConfig) !T { 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{} mut res := T{}
// This array allows us to determine later whether the variable is actually // 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() 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()
// This seems to not work in V 0.3.2
//} $else {
// $compile_error('Unsupported config struct field type detected.')
} }
has_value.add(field.name) has_value.add(field.name)
@ -93,9 +101,6 @@ pub fn load<T>(ld 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()
// This seems to not work in V 0.3.2
//} $else {
// $compile_error('Unsupported config struct field type detected.')
} }
has_value.add(field.name) has_value.add(field.name)

10
conf_test.v 100644
View File

@ -0,0 +1,10 @@
module conf
struct WrongTypeConfig {
f map[string]string
}
fn test_wrong_type() {
conf := load<WrongTypeConfig>() or { return }
assert false
}

View File

@ -181,3 +181,8 @@ fn test_int_absent_default_empty() {
some_int: 0 some_int: 0
} }
} }
/* fn test_int_wrong_type() { */
/* conf := load<SingleConf>(default_path: 'test/int_wrong_type.toml') or { return } */
/* assert false */
/* } */

View File

@ -0,0 +1 @@
some_int = '1'