From d5c2ebce05a2ec23bb8ec38c8ad8ac5b7d7745dd Mon Sep 17 00:00:00 2001 From: yuyi Date: Thu, 5 Sep 2024 03:48:22 +0800 Subject: [PATCH] flag: fix parse_bool_value() (#22160) --- vlib/flag/flag.v | 18 +++++++++++++---- vlib/flag/flag_parse_test.v | 39 +++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 vlib/flag/flag_parse_test.v diff --git a/vlib/flag/flag.v b/vlib/flag/flag.v index 10a53b88b6..8f47a89b8c 100644 --- a/vlib/flag/flag.v +++ b/vlib/flag/flag.v @@ -302,10 +302,20 @@ fn (mut fs FlagParser) parse_bool_value(longhand string, shorthand u8) !string { fs.args.delete(i) return val } - if arg.len > 1 && arg[0] == `-` && arg[1] != `-` && arg.index_u8(shorthand) != -1 { - // -abc is equivalent to -a -b -c - fs.args[i] = arg.replace(shorthand.ascii_str(), '') // -abc -> -bc - return 'true' + if arg.len > 1 && arg[0] == `-` && arg[1] != `-` { + mut found := false + for j in 1 .. arg.len - 1 { + if arg[j].is_space() { + break + } else if arg[j] == shorthand { + found = true + } + } + if found { + // -abc is equivalent to -a -b -c + fs.args[i] = arg.replace(shorthand.ascii_str(), '') // -abc -> -bc + return 'true' + } } } return error("parameter '${longhand}' not found") diff --git a/vlib/flag/flag_parse_test.v b/vlib/flag/flag_parse_test.v new file mode 100644 index 0000000000..a7761efba8 --- /dev/null +++ b/vlib/flag/flag_parse_test.v @@ -0,0 +1,39 @@ +import flag + +pub struct Options { +pub: + verbosity int + dump_usage bool +pub mut: + additional_args []string + archs []string + v_flags []string + api_level string +} + +fn test_flag_parse() { + args := ['/my/app', '-v', '3', '-f', '-d sdl_memory_no_gc', '-f', '-d shy_use_wren', '--api', + '21', '--archs', 'arm64-v8a', '/path/to/input.v'] + + mut fp := flag.new_flag_parser(args) + fp.application('bug') + fp.version('0.2.0') + fp.description('bugged') + fp.arguments_description('not important') + + fp.skip_executable() + + mut opt := Options{ + v_flags: fp.string_multi('flag', `f`, 'Additional flags for the V compiler') + archs: fp.string('archs', 0, 'arm64-v8a,armeabi-v7a,x86,x86_64', 'Comma separated string with any of archs').split(',') + dump_usage: fp.bool('help', `h`, false, 'Show this help message and exit') + verbosity: fp.int_opt('verbosity', `v`, 'Verbosity level 1-3') or { 0 } + api_level: fp.string('api', 0, '21', 'Android API level to use (--list-apis)') + } + + opt.additional_args = fp.finalize() or { panic(err) } + + assert opt.v_flags[0] == '-d sdl_memory_no_gc' + assert opt.v_flags[1] == '-d shy_use_wren' // looks like the builtin support for `-h` eats the "h" in this flag + assert opt.dump_usage == false +}