From 0d35f0948c2a9530edc172e4676a15e73420d165 Mon Sep 17 00:00:00 2001 From: larpon <768942+larpon@users.noreply.github.com> Date: Wed, 4 Sep 2024 22:13:50 +0200 Subject: [PATCH] flag: correct bool logic, add test (#22162) --- vlib/flag/flag_to.v | 3 ++- vlib/flag/flag_to_bool_test.v | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 vlib/flag/flag_to_bool_test.v diff --git a/vlib/flag/flag_to.v b/vlib/flag/flag_to.v index be97ff447a..d8094ce2ff 100644 --- a/vlib/flag/flag_to.v +++ b/vlib/flag/flag_to.v @@ -832,6 +832,7 @@ fn keep_at_max(str string, max int) string { pub fn (fm FlagMapper) to_struct[T](defaults ?T) !T { // Generate T result mut result := defaults or { T{} } + the_default := defaults or { T{} } $if T is $struct { struct_name := T.name @@ -907,7 +908,7 @@ pub fn (fm FlagMapper) to_struct[T](defaults ?T) !T { if arg := f.arg { return error('can not assign `${arg}` to bool field `${field.name}`') } - result.$(field.name) = true + result.$(field.name) = !the_default.$(field.name) } $else $if field.typ is string { trace_dbg_println('${@FN}: assigning (string) ${struct_name}.${field.name} = ${f.arg or { 'ERROR' diff --git a/vlib/flag/flag_to_bool_test.v b/vlib/flag/flag_to_bool_test.v new file mode 100644 index 0000000000..b8784c52a3 --- /dev/null +++ b/vlib/flag/flag_to_bool_test.v @@ -0,0 +1,21 @@ +import flag + +const gnu_args_bool_flags = ['--no-parallel', '--nocache', '--stay', '--nix'] + +struct BoolConfig { + mix bool + nix bool + parallel bool = true @[long: 'no-parallel'] + cache bool @[long: nocache] + no_stay bool @[long: 'stay'] +} + +fn test_bool_flags() { + bf, _ := flag.to_struct[BoolConfig](gnu_args_bool_flags, style: .long)! + + assert bf.mix == false + assert bf.nix == true + assert bf.parallel == false + assert bf.cache == true + assert bf.no_stay == true +}