flag: fix panic if flag value was not provided (#6478)

pull/6480/head
spaceface777 2020-09-25 15:31:35 +02:00 committed by GitHub
parent ae48b709ed
commit aa1d5fcbdd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 2 deletions

View File

@ -113,13 +113,13 @@ fn (mut fs FlagParser) parse_value(longhand string, shorthand byte) []string {
} }
if (arg.len == 2 && arg[0] == `-` && arg[1] == shorthand ) || arg == full { if (arg.len == 2 && arg[0] == `-` && arg[1] == shorthand ) || arg == full {
if i+1 >= fs.args.len { if i+1 >= fs.args.len {
panic("Missing argument for '$longhand'") return []
} }
nextarg := fs.args[i+1] nextarg := fs.args[i+1]
if nextarg.len > 2 && nextarg[..2] == '--' { if nextarg.len > 2 && nextarg[..2] == '--' {
//It could be end of input (--) or another argument (--abc). //It could be end of input (--) or another argument (--abc).
//Both are invalid so die. //Both are invalid so die.
panic("Missing argument for '$longhand'") return []
} }
found_entries << fs.args[i+1] found_entries << fs.args[i+1]
to_delete << i to_delete << i

View File

@ -352,3 +352,13 @@ fn test_single_dash() {
flag_update := fp.bool('update', `u`, false, 'Update tools') flag_update := fp.bool('update', `u`, false, 'Update tools')
assert flag_update == false assert flag_update == false
} }
fn test_optional_flags() {
mut fp := flag.new_flag_parser(['-a', '10', '-b'])
a := fp.int_opt('some-flag', `a`, '') or {
assert false
return
}
b := fp.string_opt('another-flag', `b`, '') or { 'some_default_value' }
assert b == 'some_default_value'
}