1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/examples/cli.v

61 lines
1.3 KiB
V
Raw Normal View History

2019-11-21 15:03:12 +03:00
module main
2020-04-26 14:49:31 +03:00
import cli
import os
2019-11-21 15:03:12 +03:00
fn main() {
mut cmd := cli.Command{
2020-04-26 14:49:31 +03:00
name: 'cli',
2019-11-21 15:03:12 +03:00
description: 'An example of the cli library',
version: '1.0.0',
2020-01-02 20:09:24 +03:00
parent: 0
2019-11-21 15:03:12 +03:00
}
mut greet_cmd := cli.Command{
name: 'greet',
description: 'Prints greeting in different languages',
2020-03-10 18:11:17 +03:00
pre_execute: greet_pre_func,
2019-11-21 15:03:12 +03:00
execute: greet_func,
2020-03-10 18:11:17 +03:00
post_execute: greet_post_func,
2020-01-02 20:09:24 +03:00
parent: 0
2019-11-21 15:03:12 +03:00
}
greet_cmd.add_flag(cli.Flag{
2020-04-26 14:49:31 +03:00
flag: .string,
2019-11-21 15:03:12 +03:00
required: true,
name: 'language',
abbrev: 'l',
description: 'Language of the message'
})
greet_cmd.add_flag(cli.Flag{
flag: .int,
name: 'times',
value: '3',
description: 'Number of times the message gets printed'
})
cmd.add_command(greet_cmd)
cmd.parse(os.args)
}
fn greet_func(cmd cli.Command) {
language := cmd.flags.get_string('language') or { panic('failed to get \'language\' flag: $err') }
times := cmd.flags.get_int('times') or { panic('failed to get \'times\' flag: $err') }
for i in 0..times {
2019-11-21 15:03:12 +03:00
match language {
'english' { println('Hello World') }
'german' { println('Hallo Welt') }
'dutch' { println('Hallo Wereld') }
else { println('unsupported language') }
}
}
}
2020-03-10 18:11:17 +03:00
fn greet_pre_func(cmd cli.Command) {
println('This is a function running before the main function')
}
fn greet_post_func(cmd cli.Command) {
println('This is a function running after the main function')
}