Skip to content

Commit

Permalink
flag: correct bool logic, add test (#22162)
Browse files Browse the repository at this point in the history
  • Loading branch information
larpon authored Sep 4, 2024
1 parent d5c2ebc commit 0d35f09
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion vlib/flag/flag_to.v
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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'
Expand Down
21 changes: 21 additions & 0 deletions vlib/flag/flag_to_bool_test.v
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit 0d35f09

Please sign in to comment.