v/examples/cli.v

86 lines
1.7 KiB
V
Raw Normal View History

2019-11-21 13:03:12 +01:00
module main
2020-08-20 23:14:53 +02:00
import cli { Command, Flag }
2020-04-26 13:49:31 +02:00
import os
2019-11-21 13:03:12 +01:00
fn main() {
2020-08-20 23:14:53 +02:00
mut cmd := Command{
name: 'cli'
description: 'An example of the cli library.'
version: '1.0.0'
2019-11-21 13:03:12 +01:00
}
2020-08-20 23:14:53 +02:00
mut greet_cmd := Command{
name: 'greet'
description: 'Prints greeting in different languages.'
usage: '<name>'
2020-08-20 23:14:53 +02:00
required_args: 1
pre_execute: greet_pre_func
execute: greet_func
post_execute: greet_post_func
2019-11-21 13:03:12 +01:00
}
2020-08-20 23:14:53 +02:00
greet_cmd.add_flag(Flag{
flag: .string
required: true
name: 'language'
abbrev: 'l'
description: 'Language of the message.'
2019-11-21 13:03:12 +01:00
})
2020-08-20 23:14:53 +02:00
greet_cmd.add_flag(Flag{
flag: .int
name: 'times'
value: ['3']
description: 'Number of times the message gets printed.'
2019-11-21 13:03:12 +01:00
})
greet_cmd.add_flag(Flag{
flag: .string
name: 'fun'
multiple: true
description: 'Just a dumby flags to show multiple.'
})
2019-11-21 13:03:12 +01:00
cmd.add_command(greet_cmd)
cmd.setup()
2019-11-21 13:03:12 +01:00
cmd.parse(os.args)
}
fn greet_func(cmd Command) ? {
language := cmd.flags.get_string('language') or {
2020-08-20 23:14:53 +02:00
panic('Failed to get `language` flag: $err')
}
times := cmd.flags.get_int('times') or {
2020-08-20 23:14:53 +02:00
panic('Failed to get `times` flag: $err')
}
2020-08-20 23:14:53 +02:00
name := cmd.args[0]
for _ in 0 .. times {
2019-11-21 13:03:12 +01:00
match language {
'english', 'en' {
2020-08-20 23:14:53 +02:00
println('Welcome $name')
}
'german', 'de' {
2020-08-20 23:14:53 +02:00
println('Willkommen $name')
}
'dutch', 'nl' {
2020-08-20 23:14:53 +02:00
println('Welkom $name')
}
else {
println('Unsupported language')
println('Supported languages are `english`, `german` and `dutch`.')
break
}
2019-11-21 13:03:12 +01:00
}
}
fun := cmd.flags.get_strings('fun') or {
panic('Failed to get `fun` flag: $err')
}
for f in fun {
println('fun: ${f}')
}
2019-11-21 13:03:12 +01:00
}
2020-03-10 16:11:17 +01:00
fn greet_pre_func(cmd Command) ? {
println('This is a function running before the main function.\n')
2020-03-10 16:11:17 +01:00
}
fn greet_post_func(cmd Command) ? {
println('\nThis is a function running after the main function.')
}