diff --git a/vlib/cli/README.md b/vlib/cli/README.md new file mode 100644 index 0000000000..93d8d62cd6 --- /dev/null +++ b/vlib/cli/README.md @@ -0,0 +1,30 @@ +Usage example: + +```v +module main + +import os +import cli + +fn main() { + mut app := cli.Command{ + name: 'example-app' + description: 'example-app' + execute: fn (cmd cli.Command) ? { + println('hello app') + return + } + commands: [ + cli.Command{ + name: 'sub' + execute: fn (cmd cli.Command) ? { + println('hello subcommand') + return + } + }, + ] + } + app.setup() + app.parse(os.args) +} +``` diff --git a/vlib/cli/command.v b/vlib/cli/command.v index a082da394b..3466cfa7b8 100644 --- a/vlib/cli/command.v +++ b/vlib/cli/command.v @@ -89,6 +89,13 @@ pub fn (mut cmd Command) add_command(command Command) { cmd.commands << subcmd } +pub fn (mut cmd Command) setup() { + for mut subcmd in cmd.commands { + subcmd.parent = cmd + subcmd.setup() + } +} + pub fn (mut cmd Command) add_flags(flags []Flag) { for flag in flags { cmd.add_flag(flag) diff --git a/vlib/cli/command_test.v b/vlib/cli/command_test.v index 341ef22e38..22ce800692 100644 --- a/vlib/cli/command_test.v +++ b/vlib/cli/command_test.v @@ -145,6 +145,27 @@ fn test_if_global_flag_gets_set_in_subcommand() { cmd.parse(['command', '-flag', 'value', 'subcommand']) } +fn test_command_setup() { + mut cmd := cli.Command{ + name: 'root' + commands: [ + cli.Command{ + name: 'child' + commands: [ + cli.Command{ + name: 'child-child' + }, + ] + }, + ] + } + assert isnil(cmd.commands[0].parent) + assert isnil(cmd.commands[0].commands[0].parent) + cmd.setup() + assert cmd.commands[0].parent.name == 'root' + assert cmd.commands[0].commands[0].parent.name == 'child' +} + // helper functions fn empty_func(cmd cli.Command) ? { }