getopt: return remaining args, use getopt for scoop install

This commit is contained in:
Luke Sampson
2013-09-03 10:45:47 +10:00
parent fd7514fee3
commit b7cfd6fdb0
3 changed files with 20 additions and 31 deletions
+2 -26
View File
@@ -1,29 +1,3 @@
function parse_args($a) {
$apps = @(); $arch = $null; $global = $false
for($i = 0; $i -lt $a.length; $i++) {
$arg = $a[$i]
if($arg.startswith('-')) {
switch($arg) {
'-arch' {
if($a.length -gt $i + 1) { $arch = $a[$i++] }
else { write-host '-arch parameter requires a value'; exit 1 }
}
'-global' {
$global = $true
}
default {
write-host "unrecognised parameter: $arg"; exit 1
}
}
} else {
$apps += $arg
}
}
$apps, $arch, $global
}
# adapted from http://hg.python.org/cpython/file/2.7/Lib/getopt.py
# returns @(opts hash, rem_args array, error string)
function getopt($argv, $shortopts, $longopts) {
@@ -75,6 +49,8 @@ function getopt($argv, $shortopts, $longopts) {
return err "option -$letter not recognized"
}
}
} else {
$rem += $arg
}
}
+7 -3
View File
@@ -12,8 +12,8 @@
# When installing from your computer, you can leave the .json extension off if you like.
#
# Options:
# -arch 32bit|64bit use the specified architecture, if the app supports it
# -global install the app globally
# -a, --arch <32bit|64bit> use the specified architecture, if the app supports it
# -g, --global install the app globally
. "$psscriptroot\..\lib\core.ps1"
. "$psscriptroot\..\lib\manifest.ps1"
@@ -76,7 +76,11 @@ function install($app, $architecture, $global) {
show_notes $manifest
}
$apps, $architecture, $global = parse_args $args
$opt, $apps, $err = getopt $args 'ga:' 'global', 'arch='
if($err) { "scoop install: $err"; exit 1 }
$global = $opt.g -or $opt.global
$architecture = $opt.a + $opt.arch
switch($architecture) {
'' { $architecture = architecture }
+11 -2
View File
@@ -26,13 +26,22 @@ test 'handle unrecognized long option' {
assert $err -ne $null
assert $err -eq 'option --non-exist not recognized'
$null, $null, $err = getopt '--global', '--another' 'abc:de:' 'global', 'one'
$null, $null, $err = getopt '--global','--another' 'abc:de:' 'global','one'
assert $err -eq 'option --another not recognized'
}
test 'remaining args returned' {
$opt, $rem, $err = getopt '-g','rem' 'g' ''
assert $err -eq $null
assert $opt.g -eq $true
assert $rem -ne $null
assert $rem.length -eq 1
assert $rem[0] -eq 'rem'
}
test 'get a long flag and a short option with argument' {
$a = "--global -a 32bit test" -split ' '
$opt, $rem, $err = getopt $a 'ga:' 'global', 'arch='
$opt, $rem, $err = getopt $a 'ga:' 'global','arch='
assert $err -eq $null
assert $opt.global -eq $true
assert $opt.a -eq '32bit'