flag: return error on .finalize() on CLI arguments with unknown short options too

pull/9415/head
Delyan Angelov 2021-03-22 08:21:13 +02:00
parent 0258482caf
commit 1eb3ed9818
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
2 changed files with 19 additions and 11 deletions

View File

@ -404,17 +404,15 @@ pub fn (fs FlagParser) usage() string {
return use.replace('- ,', ' ')
}
// finalize argument parsing -> call after all arguments are defined
//
// all remaining arguments are returned in the same order they are defined on
// command line
//
// if additional flag are found (things starting with '--') an error is returned
// error handling is up to the application developer
// finalize - return all remaining arguments (non options).
// Call .finalize() after all arguments are defined.
// The remaining arguments are returned in the same order they are
// defined on the command line. If additional flags are found, i.e.
// (things starting with '--' or '-'), it returns an error.
pub fn (fs FlagParser) finalize() ?[]string {
for a in fs.args {
if a.len >= 2 && a[..2] == '--' {
return error("Unknown argument \'${a[2..]}\'")
if (a.len >= 2 && a[..2] == '--') || (a.len == 2 && a[0] == `-`) {
return error('Unknown flag `$a`')
}
}
if fs.args.len < fs.min_free_args && fs.min_free_args > 0 {

View File

@ -133,11 +133,21 @@ fn test_finalize_returns_none_flag_arguments_ordered() {
}
}
fn test_finalize_returns_error_for_unknown_flags() {
fn test_finalize_returns_error_for_unknown_flags_long() {
mut fp := flag.new_flag_parser(['--known', '--unknown'])
fp.bool('known', 0, false, '')
finalized := fp.finalize() or {
assert err.msg == "Unknown argument 'unknown'"
assert err.msg == 'Unknown flag `--unknown`'
return
}
assert finalized.len < 0 // expect error to be returned
}
fn test_finalize_returns_error_for_unknown_flags_short() {
mut fp := flag.new_flag_parser(['--known', '-x'])
fp.bool('known', 0, false, '')
finalized := fp.finalize() or {
assert err.msg == 'Unknown flag `-x`'
return
}
assert finalized.len < 0 // expect error to be returned