flag: add custom errors (#9515)

pull/9536/head
Atakan Yenel 2021-03-30 14:31:02 +02:00 committed by GitHub
parent e9c7cd0c9f
commit d1fadaf30c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 32 additions and 4 deletions

View File

@ -10,6 +10,26 @@ pub:
// and also the default value, when the flag is not given
}
struct UnkownFlagError {
msg string
code int
}
struct MinimumArgsCountError {
msg string
code int
}
struct MaximumArgsCountError {
msg string
code int
}
struct NoArgsExpectedError {
msg string
code int
}
[unsafe]
fn (mut f Flag) free() {
unsafe {
@ -477,17 +497,25 @@ pub fn (fs FlagParser) usage() string {
pub fn (fs FlagParser) finalize() ?[]string {
for a in fs.args {
if (a.len >= 2 && a[..2] == '--') || (a.len == 2 && a[0] == `-`) {
return error('Unknown flag `$a`')
return IError(&UnkownFlagError{
msg: 'Unknown flag `$a`'
})
}
}
if fs.args.len < fs.min_free_args && fs.min_free_args > 0 {
return error('Expected at least $fs.min_free_args arguments, but given $fs.args.len')
return IError(&MinimumArgsCountError{
msg: 'Expected at least $fs.min_free_args arguments, but given $fs.args.len'
})
}
if fs.args.len > fs.max_free_args && fs.max_free_args > 0 {
return error('Expected at most $fs.max_free_args arguments, but given $fs.args.len')
return IError(&MaximumArgsCountError{
msg: 'Expected at most $fs.max_free_args arguments, but given $fs.args.len'
})
}
if fs.args.len > 0 && fs.max_free_args == 0 && fs.min_free_args == 0 {
return error('Expected no arguments, but given $fs.args.len')
return IError(&NoArgsExpectedError{
msg: 'Expected no arguments, but given $fs.args.len'
})
}
return fs.args
}