From c00dd42cae224cba339f40a5abda4ad6c7ca9020 Mon Sep 17 00:00:00 2001 From: Valinor Date: Sun, 26 Feb 2023 07:32:16 +0100 Subject: [PATCH] fix(getopt): Stop split arguments in `getopt()` and ensure array by explicit arguments type (#5326) Co-authored-by: Hsiao-nan Cheung --- CHANGELOG.md | 1 + lib/getopt.ps1 | 7 +------ test/Scoop-GetOpts.Tests.ps1 | 6 ++++++ 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 89cb0b71f6..ec4d91723b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ - **decompress:** Exclude '*.nsis' that may cause error ([#5294](https://github.com/ScoopInstaller/Scoop/issues/5294)) - **autoupdate:** Fix file hash extraction ([#5295](https://github.com/ScoopInstaller/Scoop/issues/5295)) +- **getopt:** Stop split arguments in `getopt()` and ensure array by explicit arguments type ([#5326](https://github.com/ScoopInstaller/Scoop/issues/5326)) - **shortcuts:** Output correctly formatted path ([#5333](https://github.com/ScoopInstaller/Scoop/issues/5333)) - **core:** Fix scripts' calling parameters ([#5365](https://github.com/ScoopInstaller/Scoop/issues/5365)) - **core:** Fix `is_in_dir` under Unix ([#5391](https://github.com/ScoopInstaller/Scoop/issues/5391)) diff --git a/lib/getopt.ps1 b/lib/getopt.ps1 index 74ffae7c52..2de3ac6c0a 100644 --- a/lib/getopt.ps1 +++ b/lib/getopt.ps1 @@ -13,7 +13,7 @@ # following arguments are treated as non-option arguments, even if # they begin with a hyphen. The "--" itself will not be included in # the returned $opts. (POSIX-compatible) -function getopt($argv, $shortopts, $longopts) { +function getopt([String[]]$argv, [String]$shortopts, [String[]]$longopts) { $opts = @{}; $rem = @() function err($msg) { @@ -24,10 +24,6 @@ function getopt($argv, $shortopts, $longopts) { return [Regex]::Escape($str) } - # ensure these are arrays - $argv = @($argv -split ' ') - $longopts = @($longopts) - for ($i = 0; $i -lt $argv.Length; $i++) { $arg = $argv[$i] if ($null -eq $arg) { continue } @@ -81,6 +77,5 @@ function getopt($argv, $shortopts, $longopts) { $rem += $arg } } - $opts, $rem } diff --git a/test/Scoop-GetOpts.Tests.ps1 b/test/Scoop-GetOpts.Tests.ps1 index ef4d56a950..c55781ecbf 100644 --- a/test/Scoop-GetOpts.Tests.ps1 +++ b/test/Scoop-GetOpts.Tests.ps1 @@ -17,6 +17,12 @@ Describe 'getopt' -Tag 'Scoop' { $err | Should -Be 'Option --arb requires an argument.' } + It 'handle space in quote' { + $opt, $rem, $err = getopt '-x', 'space arg' 'x:' '' + $err | Should -BeNullOrEmpty + $opt.x | Should -Be 'space arg' + } + It 'handle unrecognized short option' { $null, $null, $err = getopt '-az' 'a' '' $err | Should -Be 'Option -z not recognized.'