cli: ensure that required flags are set (#8826)

pull/8833/head
Miccah 2021-02-19 04:43:18 -06:00 committed by GitHub
parent 3f3bec45fa
commit a153ec5951
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 8 deletions

View File

@ -42,7 +42,7 @@ fn main() {
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.')
}

View File

@ -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)

View File

@ -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'