diff --git a/lib/getopt.ps1 b/lib/getopt.ps1 index 0e30a97ef..15c78fcd9 100644 --- a/lib/getopt.ps1 +++ b/lib/getopt.ps1 @@ -15,6 +15,10 @@ function getopt($argv, $shortopts, $longopts) { $opts, $rem, $msg } + function regex_escape($str) { + return [regex]::escape($str) + } + # ensure these are arrays $argv = @($argv) $longopts = @($longopts) @@ -46,7 +50,7 @@ function getopt($argv, $shortopts, $longopts) { for($j = 1; $j -lt $arg.length; $j++) { $letter = $arg[$j].tostring() - if($shortopts -match "$letter`:?") { + if($shortopts -match "$(regex_escape $letter)`:?") { $shortopt = $matches[0] if($shortopt[1] -eq ':') { if($j -ne $arg.length -1 -or $i -eq $argv.length - 1) { @@ -66,4 +70,4 @@ function getopt($argv, $shortopts, $longopts) { } $opts, $rem -} \ No newline at end of file +} diff --git a/test/Scoop-GetOpts.Tests.ps1 b/test/Scoop-GetOpts.Tests.ps1 index 80c3d25c2..cd5584350 100644 --- a/test/Scoop-GetOpts.Tests.ps1 +++ b/test/Scoop-GetOpts.Tests.ps1 @@ -45,4 +45,27 @@ describe "getopt" { $opt.global | should be $true $opt.a | should be '32bit' } -} \ No newline at end of file + + it 'handles regex characters' { + $a = "-?" + { $opt, $rem, $err = getopt $a 'ga:' 'global' 'arch=' } | should not throw + { $null, $null, $null = getopt $a '?:' 'help' | should not throw } + } + + it 'handles short option without required argument' { + $null, $null, $err = getopt '-x' 'x' '' + $err | should be $null + } + + it 'handles long option without required argument' { + $opt, $null, $err = getopt '--long-arg' '' 'long-arg' + $err | should be $null + $opt."long-arg" | should be $true + } + + it 'handles long option with required argument' { + $opt, $null, $err = getopt '--long-arg', 'test' '' 'long-arg=' + $err | should be $null + $opt."long-arg" | should be "test" + } +}