cli: various improvements (#6180)

pull/6188/head
Lukas Neubert 2020-08-20 23:14:53 +02:00 committed by GitHub
parent b88569c845
commit 93e6c3df6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 71 additions and 73 deletions

View File

@ -1,29 +1,30 @@
module main module main
import cli import cli { Command, Flag }
import os import os
fn main() { fn main() {
mut cmd := cli.Command{ mut cmd := Command{
name: 'cli' name: 'cli'
description: 'An example of the cli library.' description: 'An example of the cli library.'
version: '1.0.0' version: '1.0.0'
} }
mut greet_cmd := cli.Command{ mut greet_cmd := Command{
name: 'greet' name: 'greet'
description: 'Prints greeting in different languages.' description: 'Prints greeting in different languages.'
required_args: 1
pre_execute: greet_pre_func pre_execute: greet_pre_func
execute: greet_func execute: greet_func
post_execute: greet_post_func post_execute: greet_post_func
} }
greet_cmd.add_flag(cli.Flag{ greet_cmd.add_flag(Flag{
flag: .string flag: .string
required: true required: true
name: 'language' name: 'language'
abbrev: 'l' abbrev: 'l'
description: 'Language of the message.' description: 'Language of the message.'
}) })
greet_cmd.add_flag(cli.Flag{ greet_cmd.add_flag(Flag{
flag: .int flag: .int
name: 'times' name: 'times'
value: '3' value: '3'
@ -33,23 +34,24 @@ fn main() {
cmd.parse(os.args) cmd.parse(os.args)
} }
fn greet_func(cmd cli.Command) { fn greet_func(cmd Command) {
language := cmd.flags.get_string('language') or { language := cmd.flags.get_string('language') or {
panic("Failed to get \'language\' flag: $err") panic('Failed to get `language` flag: $err')
} }
times := cmd.flags.get_int('times') or { times := cmd.flags.get_int('times') or {
panic("Failed to get \'times\' flag: $err") panic('Failed to get `times` flag: $err')
} }
name := cmd.args[0]
for _ in 0 .. times { for _ in 0 .. times {
match language { match language {
'english' { 'english' {
println('Hello World') println('Welcome $name')
} }
'german' { 'german' {
println('Hallo Welt') println('Willkommen $name')
} }
'dutch' { 'dutch' {
println('Hallo Wereld') println('Welkom $name')
} }
else { else {
println('Unsupported language') println('Unsupported language')
@ -60,10 +62,10 @@ fn greet_func(cmd cli.Command) {
} }
} }
fn greet_pre_func(cmd cli.Command) { fn greet_pre_func(cmd Command) {
println('This is a function running before the main function.\n') println('This is a function running before the main function.\n')
} }
fn greet_post_func(cmd cli.Command) { fn greet_post_func(cmd Command) {
println('\nThis is a function running after the main function.') println('\nThis is a function running after the main function.')
} }

View File

@ -1,6 +1,6 @@
module cli module cli
type FnCommandCallback fn (cmd Command)? type FnCommandCallback = fn (cmd Command) ?
pub fn (f FnCommandCallback) str() string { pub fn (f FnCommandCallback) str() string {
return 'FnCommandCallback=>' + ptr_str(f) return 'FnCommandCallback=>' + ptr_str(f)
@ -23,6 +23,7 @@ pub mut:
parent &Command = 0 parent &Command = 0
commands []Command commands []Command
flags []Flag flags []Flag
required_args int
args []string args []string
} }
@ -48,6 +49,7 @@ pub fn (cmd Command) str() string {
} }
res << ' commands: $cmd.commands' res << ' commands: $cmd.commands'
res << ' flags: $cmd.flags' res << ' flags: $cmd.flags'
res << ' required_args: $cmd.required_args'
res << ' args: $cmd.args' res << ' args: $cmd.args'
res << '}' res << '}'
return res.join('\n') return res.join('\n')
@ -78,13 +80,13 @@ pub fn (mut cmd Command) add_commands(commands []Command) {
} }
pub fn (mut cmd Command) add_command(command Command) { pub fn (mut cmd Command) add_command(command Command) {
for existing_cmd in cmd.commands { mut subcmd := command
if existing_cmd.name == command.name { if cmd.commands.contains(subcmd.name) {
println("command with the same name \'$command.name\' already exists") println('Command with the name `$subcmd.name` already exists')
exit(1) exit(1)
}
} }
cmd.commands << command subcmd.parent = cmd
cmd.commands << subcmd
} }
pub fn (mut cmd Command) add_flags(flags []Flag) { pub fn (mut cmd Command) add_flags(flags []Flag) {
@ -94,11 +96,9 @@ pub fn (mut cmd Command) add_flags(flags []Flag) {
} }
pub fn (mut cmd Command) add_flag(flag Flag) { pub fn (mut cmd Command) add_flag(flag Flag) {
for existing_flag in cmd.flags { if cmd.flags.contains(flag.name) {
if existing_flag.name == flag.name { println('Flag with the name `$flag.name` already exists')
println("flag with the same name \'$flag.name\' already exists") exit(1)
exit(1)
}
} }
cmd.flags << flag cmd.flags << flag
} }
@ -115,9 +115,6 @@ pub fn (mut cmd Command) parse(args []string) {
cmd.commands.sort(a.name < b.name) cmd.commands.sort(a.name < b.name)
} }
cmd.args = args[1..] cmd.args = args[1..]
for i in 0 .. cmd.commands.len {
cmd.commands[i].parent = cmd
}
if !cmd.disable_flags { if !cmd.disable_flags {
cmd.parse_flags() cmd.parse_flags()
} }
@ -126,10 +123,12 @@ pub fn (mut cmd Command) parse(args []string) {
fn (mut cmd Command) add_default_flags() { fn (mut cmd Command) add_default_flags() {
if !cmd.disable_help && !cmd.flags.contains('help') { if !cmd.disable_help && !cmd.flags.contains('help') {
cmd.add_flag(help_flag(!cmd.flags.contains('h') && cmd.has_abbrev_flags())) use_help_abbrev := !cmd.flags.contains('h') && cmd.flags.have_abbrev()
cmd.add_flag(help_flag(use_help_abbrev))
} }
if cmd.version != '' && !cmd.flags.contains('version') { if !cmd.disable_version && cmd.version != '' && !cmd.flags.contains('version') {
cmd.add_flag(version_flag(!cmd.flags.contains('v') && cmd.has_abbrev_flags())) use_version_abbrev := !cmd.flags.contains('v') && cmd.flags.have_abbrev()
cmd.add_flag(version_flag(use_version_abbrev))
} }
} }
@ -137,7 +136,7 @@ fn (mut cmd Command) add_default_commands() {
if !cmd.disable_help && !cmd.commands.contains('help') && cmd.is_root() { if !cmd.disable_help && !cmd.commands.contains('help') && cmd.is_root() {
cmd.add_command(help_cmd()) cmd.add_command(help_cmd())
} }
if cmd.version != '' && !cmd.commands.contains('version') { if !cmd.disable_version && cmd.version != '' && !cmd.commands.contains('version') {
cmd.add_command(version_cmd()) cmd.add_command(version_cmd())
} }
} }
@ -150,18 +149,18 @@ fn (mut cmd Command) parse_flags() {
mut found := false mut found := false
for i in 0 .. cmd.flags.len { for i in 0 .. cmd.flags.len {
mut flag := &cmd.flags[i] mut flag := &cmd.flags[i]
if flag.matches(cmd.args, cmd.has_abbrev_flags()) { if flag.matches(cmd.args, cmd.flags.have_abbrev()) {
found = true found = true
flag.found = true flag.found = true
cmd.args = flag.parse(cmd.args, cmd.has_abbrev_flags()) or { cmd.args = flag.parse(cmd.args, cmd.flags.have_abbrev()) or {
println('failed to parse flag ${cmd.args[0]}: $err') println('Failed to parse flag `${cmd.args[0]}`: $err')
exit(1) exit(1)
} }
break break
} }
} }
if !found { if !found {
println('invalid flag: ${cmd.args[0]}') println('Command `$cmd.name` has no flag `${cmd.args[0]}`')
exit(1) exit(1)
} }
} }
@ -190,6 +189,12 @@ fn (mut cmd Command) parse_commands() {
cmd.execute_help() cmd.execute_help()
} }
} else { } else {
if cmd.required_args > 0 {
if cmd.required_args > cmd.args.len {
println('Command `$cmd.name` needs at least $cmd.required_args arguments')
exit(1)
}
}
cmd.check_required_flags() cmd.check_required_flags()
if int(cmd.pre_execute) > 0 { if int(cmd.pre_execute) > 0 {
cmd.pre_execute(*cmd) or { cmd.pre_execute(*cmd) or {
@ -210,16 +215,6 @@ fn (mut cmd Command) parse_commands() {
} }
} }
fn (cmd Command) has_abbrev_flags() bool {
mut has_abbrev := false
for flag in cmd.flags {
if flag.abbrev != '' {
has_abbrev = true
}
}
return has_abbrev
}
fn (cmd Command) check_help_flag() { fn (cmd Command) check_help_flag() {
if !cmd.disable_help && cmd.flags.contains('help') { if !cmd.disable_help && cmd.flags.contains('help') {
help_flag := cmd.flags.get_bool('help') or { help_flag := cmd.flags.get_bool('help') or {
@ -233,7 +228,7 @@ fn (cmd Command) check_help_flag() {
} }
fn (cmd Command) check_version_flag() { fn (cmd Command) check_version_flag() {
if cmd.version != '' && cmd.flags.contains('version') { if !cmd.disable_version && cmd.version != '' && cmd.flags.contains('version') {
version_flag := cmd.flags.get_bool('version') or { version_flag := cmd.flags.get_bool('version') or {
return return
} // ignore error and handle command normally } // ignore error and handle command normally
@ -251,7 +246,7 @@ fn (cmd Command) check_required_flags() {
for flag in cmd.flags { for flag in cmd.flags {
if flag.required && flag.value == '' { if flag.required && flag.value == '' {
full_name := cmd.full_name() full_name := cmd.full_name()
println("flag \'$flag.name\' is required by \'$full_name\'") println('Flag `$flag.name` is required by `$full_name`')
exit(1) exit(1)
} }
} }
@ -274,7 +269,7 @@ fn (cmds []Command) get(name string) ?Command {
return cmd return cmd
} }
} }
return error("command \'$name\' not found.") return error('Command `$name` not found')
} }
fn (cmds []Command) contains(name string) bool { fn (cmds []Command) contains(name string) bool {
@ -285,4 +280,3 @@ fn (cmds []Command) contains(name string) bool {
} }
return false return false
} }

View File

@ -51,7 +51,6 @@ fn test_if_command_has_default_version_subcommand_if_version_is_set() {
assert has_command(cmd, 'version') assert has_command(cmd, 'version')
} }
fn flag_should_be_set(cmd cli.Command) ? { fn flag_should_be_set(cmd cli.Command) ? {
flag := cmd.flags.get_string('flag')? flag := cmd.flags.get_string('flag')?
assert flag == 'value' assert flag == 'value'
@ -83,7 +82,6 @@ fn test_if_flag_gets_set_with_abbrev() {
cmd.parse(['command', '--flag', 'value']) cmd.parse(['command', '--flag', 'value'])
} }
fn flag_should_have_value_of_42(cmd cli.Command) ? { fn flag_should_have_value_of_42(cmd cli.Command) ? {
flag := cmd.flags.get_string('flag')? flag := cmd.flags.get_string('flag')?
assert flag == 'value' assert flag == 'value'
@ -107,7 +105,6 @@ fn test_if_multiple_flags_get_set() {
cmd.parse(['command', '-flag', 'value', '-value', '42']) cmd.parse(['command', '-flag', 'value', '-value', '42'])
} }
fn flag_is_set_in_subcommand(cmd cli.Command) ? { fn flag_is_set_in_subcommand(cmd cli.Command) ? {
flag := cmd.flags.get_string('flag') or { flag := cmd.flags.get_string('flag') or {
panic(err) panic(err)

View File

@ -26,7 +26,7 @@ pub fn (flags []Flag) get_all_found() []Flag {
pub fn (flag Flag) get_bool() ?bool { pub fn (flag Flag) get_bool() ?bool {
if flag.flag != .bool { if flag.flag != .bool {
return error('invalid flag type') return error('Invalid flag type')
} }
return flag.value == 'true' return flag.value == 'true'
} }
@ -47,7 +47,7 @@ pub fn (flags []Flag) get_bool_or(name string, or_value bool) bool {
pub fn (flag Flag) get_int() ?int { pub fn (flag Flag) get_int() ?int {
if flag.flag != .int { if flag.flag != .int {
return error('invalid flag type') return error('Invalid flag type')
} }
return flag.value.int() return flag.value.int()
} }
@ -68,7 +68,7 @@ pub fn (flags []Flag) get_int_or(name string, or_value int) int {
pub fn (flag Flag) get_float() ?f64 { pub fn (flag Flag) get_float() ?f64 {
if flag.flag != .float { if flag.flag != .float {
return error('invalid flag type') return error('Invalid flag type')
} }
return flag.value.f64() return flag.value.f64()
} }
@ -89,7 +89,7 @@ pub fn (flags []Flag) get_float_or(name string, or_value f64) f64 {
pub fn (flag Flag) get_string() ?string { pub fn (flag Flag) get_string() ?string {
if flag.flag != .string { if flag.flag != .string {
return error('invalid flag type') return error('Invalid flag type')
} }
return flag.value return flag.value
} }
@ -148,7 +148,7 @@ fn (mut flag Flag) parse_raw(args []string) ?[]string {
flag.value = args[1] flag.value = args[1]
return args[2..] return args[2..]
} }
return error('missing argument for $flag.name') return error('Missing argument for `$flag.name`')
} }
fn (mut flag Flag) parse_bool(args []string) ?[]string { fn (mut flag Flag) parse_bool(args []string) ?[]string {
@ -171,7 +171,7 @@ fn (flags []Flag) get(name string) ?Flag {
return flag return flag
} }
} }
return error('flag $name not found.') return error('Flag `$name` not found')
} }
fn (flags []Flag) contains(name string) bool { fn (flags []Flag) contains(name string) bool {
@ -183,10 +183,12 @@ fn (flags []Flag) contains(name string) bool {
return false return false
} }
fn (flags []Flag) have_abbrev() bool {
fn (mut flags []Flag) sort2() { mut have_abbrev := false
flags.sort_with_compare(fn (a, b &Flag) int { for flag in flags {
return compare_strings(&a.name, &b.name) if flag.abbrev != '' {
}) have_abbrev = true
}
}
return have_abbrev
} }

View File

@ -15,7 +15,7 @@ fn help_flag(with_abbrev bool) Flag {
flag: .bool flag: .bool
name: 'help' name: 'help'
abbrev: sabbrev abbrev: sabbrev
description: 'Prints help information' description: 'Prints help information.'
} }
} }
@ -23,7 +23,7 @@ fn help_cmd() Command {
return Command{ return Command{
name: 'help' name: 'help'
usage: '<command>' usage: '<command>'
description: 'Prints help information' description: 'Prints help information.'
execute: print_help_for_command execute: print_help_for_command
} }
} }
@ -42,7 +42,7 @@ fn print_help_for_command(help_cmd Command) ? {
} }
if !found { if !found {
args := help_cmd.args.join(' ') args := help_cmd.args.join(' ')
print('invalid command: $args') print('Invalid command: $args')
return return
} }
} }
@ -63,6 +63,9 @@ fn (cmd Command) help_message() string {
if cmd.commands.len > 0 { if cmd.commands.len > 0 {
help += ' [commands]' help += ' [commands]'
} }
for i in 0 .. cmd.required_args {
help += ' <arg$i>'
}
if cmd.usage.len > 0 { if cmd.usage.len > 0 {
help += ' $cmd.usage' help += ' $cmd.usage'
} }
@ -72,7 +75,7 @@ fn (cmd Command) help_message() string {
} }
mut abbrev_len := 0 mut abbrev_len := 0
mut name_len := min_description_indent_len mut name_len := min_description_indent_len
if cmd.has_abbrev_flags() { if cmd.flags.have_abbrev() {
for flag in cmd.flags { for flag in cmd.flags {
abbrev_len = max(abbrev_len, flag.abbrev.len + spacing + 1) // + 1 for '-' in front abbrev_len = max(abbrev_len, flag.abbrev.len + spacing + 1) // + 1 for '-' in front
name_len = max(name_len, abbrev_len + flag.name.len + spacing + 2) // + 2 for '--' in front name_len = max(name_len, abbrev_len + flag.name.len + spacing + 2) // + 2 for '--' in front
@ -92,10 +95,10 @@ fn (cmd Command) help_message() string {
help += 'Flags:\n' help += 'Flags:\n'
for flag in cmd.flags { for flag in cmd.flags {
mut flag_name := '' mut flag_name := ''
if flag.abbrev != '' && cmd.has_abbrev_flags() { if flag.abbrev != '' && cmd.flags.have_abbrev() {
abbrev_indent := ' '.repeat(abbrev_len - flag.abbrev.len - 1) // - 1 for '-' in front abbrev_indent := ' '.repeat(abbrev_len - flag.abbrev.len - 1) // - 1 for '-' in front
flag_name = '-$flag.abbrev$abbrev_indent--$flag.name' flag_name = '-$flag.abbrev$abbrev_indent--$flag.name'
} else if cmd.has_abbrev_flags() { } else if cmd.flags.have_abbrev() {
abbrev_indent := ' '.repeat(abbrev_len) abbrev_indent := ' '.repeat(abbrev_len)
flag_name = '$abbrev_indent--$flag.name' flag_name = '$abbrev_indent--$flag.name'
} else { } else {

View File

@ -6,14 +6,14 @@ fn version_flag(with_abbrev bool) Flag {
flag: .bool flag: .bool
name: 'version' name: 'version'
abbrev: sabbrev abbrev: sabbrev
description: 'Prints version information' description: 'Prints version information.'
} }
} }
fn version_cmd() Command { fn version_cmd() Command {
return Command{ return Command{
name: 'version' name: 'version'
description: 'Prints version information' description: 'Prints version information.'
execute: version_func execute: version_func
} }
} }