From 9c74fb0449ebe23daf3122d1e949d0baafe7867c Mon Sep 17 00:00:00 2001 From: zakuro Date: Thu, 12 Aug 2021 15:25:28 +0900 Subject: [PATCH] cli: fix bug that caused help to panic (#11157) --- vlib/cli/help.v | 7 ++++- vlib/cli/help_test.v | 65 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 vlib/cli/help_test.v diff --git a/vlib/cli/help.v b/vlib/cli/help.v index 6c4ccf5bc..f47f90ed7 100644 --- a/vlib/cli/help.v +++ b/vlib/cli/help.v @@ -78,7 +78,9 @@ fn (cmd Command) help_message() string { mut name_len := cli.min_description_indent_len if cmd.posix_mode { for flag in cmd.flags { - abbrev_len = max(abbrev_len, flag.abbrev.len + cli.spacing + 1) // + 1 for '-' in front + if flag.abbrev != '' { + abbrev_len = max(abbrev_len, flag.abbrev.len + cli.spacing + 1) // + 1 for '-' in front + } name_len = max(name_len, abbrev_len + flag.name.len + cli.spacing + 2) // + 2 for '--' in front } for command in cmd.commands { @@ -86,6 +88,9 @@ fn (cmd Command) help_message() string { } } else { for flag in cmd.flags { + if flag.abbrev != '' { + abbrev_len = max(abbrev_len, flag.abbrev.len + cli.spacing + 1) // + 1 for '-' in front + } name_len = max(name_len, abbrev_len + flag.name.len + cli.spacing + 1) // + 1 for '-' in front } for command in cmd.commands { diff --git a/vlib/cli/help_test.v b/vlib/cli/help_test.v new file mode 100644 index 000000000..62cb37e63 --- /dev/null +++ b/vlib/cli/help_test.v @@ -0,0 +1,65 @@ +module cli + +fn test_help_message() { + mut cmd := Command{ + name: 'command' + description: 'description' + commands: [ + Command{ + name: 'sub' + description: 'subcommand' + }, + Command{ + name: 'sub2' + description: 'another subcommand' + }, + ] + flags: [ + Flag{ + flag: .string + name: 'str' + description: 'str flag' + }, + Flag{ + flag: .bool + name: 'bool' + description: 'bool flag' + abbrev: 'b' + }, + Flag{ + flag: .string + name: 'required' + abbrev: 'r' + required: true + }, + ] + } + assert cmd.help_message() == r'Usage: command [flags] [commands] + +description + +Flags: + -str str flag + -b -bool bool flag + -r -required (required) + +Commands: + sub subcommand + sub2 another subcommand +' + + cmd.posix_mode = true + assert cmd.help_message() == r'Usage: command [flags] [commands] + +description + +Flags: + --str str flag + -b --bool bool flag + -r --required (required) + +Commands: + sub subcommand + sub2 another subcommand +' +} -- 2.30.2