From b28eca4efda058ca2135274abda884072a8108dd Mon Sep 17 00:00:00 2001 From: Luke Sampson Date: Mon, 2 Sep 2013 23:45:54 +1000 Subject: [PATCH] add more tests for getopts --- lib/opts.ps1 | 19 ++++++++++++++++++- test/opts.ps1 | 7 +++++++ test/tests.ps1 | 11 ++++++++--- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/lib/opts.ps1 b/lib/opts.ps1 index 45fa99bd..8e3e115c 100644 --- a/lib/opts.ps1 +++ b/lib/opts.ps1 @@ -33,7 +33,10 @@ function getopt($argv, $shortopts, $longopts) { $opts, $rem, $msg } + # ensure these are arrays + $argv = @($argv) $longopts = @($longopts) + for($i = 0; $i -lt $argv.length; $i++) { $arg = $argv[$i] @@ -56,7 +59,21 @@ function getopt($argv, $shortopts, $longopts) { } } elseif($arg.startswith('-') -and $arg -ne '-') { for($j = 1; $j -lt $arg.length; $j++) { - $letter = $arg[$j] + $letter = $arg[$j].tostring() + + if($shortopts -match "$letter`:?") { + $shortopt = $matches[0] + if($shortopt[1] -eq ':') { + if($j -ne $arg.length -1 -or $i -eq $argv.length) { + return err "option -$letter requires an argument" + } + $opts.$letter = $argv[++$i] + } else { + $opts.$letter = $true + } + } else { + return err "option -$letter not recognized" + } } } } diff --git a/test/opts.ps1 b/test/opts.ps1 index 09803a50..5b4bf155 100644 --- a/test/opts.ps1 +++ b/test/opts.ps1 @@ -5,6 +5,7 @@ $a = "--global -a 32bit test" -split ' ' $opt, $rem, $err = getopt $a "ga:" "global", "arch=" + assert $err -eq $null assert $opt.global -eq $true assert $opt.a -eq "32bit" @@ -13,4 +14,10 @@ $null, $null, $err = getopt "--non-exist", "", "" assert $err -ne $null assert $err -eq "option --non-exist not recognized" +$null, $null, $err = getopt "--arb" "" "arb=" +assert $err -eq "option --arb requires an argument" + +$null, $null, $err = getopt "-az" "a" "" +assert $err -eq "option -z not recognized" + test_results diff --git a/test/tests.ps1 b/test/tests.ps1 index cc54ce79..8ffdd95a 100644 --- a/test/tests.ps1 +++ b/test/tests.ps1 @@ -7,10 +7,15 @@ function fail($msg) { $script = split-path $invoked.scriptname -leaf $line = $invoked.scriptlinenumber - write-host "FAIL: $msg ($script line $line)" -f red + write-host "FAIL: $msg" -f red write-host $invoked.positionmessage } +function fmt($var) { + if($var -is [string]) { return "'$var'" } + return $var +} + function assert( $x,$eq='__undefined',$ne='__undefined') { $script:run++ @@ -20,11 +25,11 @@ function assert( } if($eq -ne "__undefined") { - if($x -ne $eq) { fail "$x != $eq" } + if($x -ne $eq) { fail "$(fmt($x)) != $(fmt($eq))" } } if($ne -ne "__undefined") { - if($x -eq $ne) { fail "$x == $ne" } + if($x -eq $ne) { fail "$(fmt($x)) == $(fmt($ne))" } } }