From a153ec5951ac4dbf2cb8e465c349326a9d4a132e Mon Sep 17 00:00:00 2001 From: Miccah Date: Fri, 19 Feb 2021 04:43:18 -0600 Subject: [PATCH] cli: ensure that required flags are set (#8826) --- examples/cli.v | 14 +++++++------- vlib/cli/command.v | 2 +- vlib/cli/command_test.v | 17 +++++++++++++++++ 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/examples/cli.v b/examples/cli.v index 3a80e78d19..66a8eb21d1 100644 --- a/examples/cli.v +++ b/examples/cli.v @@ -32,17 +32,17 @@ fn main() { description: 'Number of times the message gets printed.' }) greet_cmd.add_flag(Flag{ - flag: .string - name: 'fun' - multiple: true - description: 'Just a dumby flags to show multiple.' + flag: .string + name: 'fun' + multiple: true + description: 'Just a dumby flags to show multiple.' }) cmd.add_command(greet_cmd) cmd.setup() cmd.parse(os.args) } -fn greet_func(cmd Command) { +fn greet_func(cmd Command) ? { language := cmd.flags.get_string('language') or { panic('Failed to get `language` flag: $err') } @@ -76,10 +76,10 @@ fn greet_func(cmd Command) { } } -fn greet_pre_func(cmd Command) { +fn greet_pre_func(cmd Command) ? { println('This is a function running before the main function.\n') } -fn greet_post_func(cmd Command) { +fn greet_post_func(cmd Command) ? { println('\nThis is a function running after the main function.') } diff --git a/vlib/cli/command.v b/vlib/cli/command.v index 92c0a55764..69467bcf2a 100644 --- a/vlib/cli/command.v +++ b/vlib/cli/command.v @@ -267,7 +267,7 @@ fn (cmd Command) check_version_flag() { fn (cmd Command) check_required_flags() { for flag in cmd.flags { - if flag.required && flag.value.len > 0 { + if flag.required && flag.value.len == 0 { full_name := cmd.full_name() println('Flag `$flag.name` is required by `$full_name`') exit(1) diff --git a/vlib/cli/command_test.v b/vlib/cli/command_test.v index 7543f9c09c..aae7199c85 100644 --- a/vlib/cli/command_test.v +++ b/vlib/cli/command_test.v @@ -117,6 +117,23 @@ fn test_if_multiple_flags_get_set() { cmd.parse(['command', '-flag', 'value', '-value', '42']) } +fn test_if_required_flags_get_set() { + mut cmd := cli.Command{ + name: 'command' + execute: flag_should_have_value_of_42 + } + cmd.add_flag(cli.Flag{ + flag: .string + name: 'flag' + }) + cmd.add_flag(cli.Flag{ + flag: .int + name: 'value' + required: true + }) + cmd.parse(['command', '-flag', 'value', '-value', '42']) +} + fn flag_is_set_in_subcommand(cmd cli.Command) ? { flag := cmd.flags.get_string('flag') or { panic(err) } assert flag == 'value'