Skip to content

Commit e3d0303

Browse files
authored
Fix 1541 "-WhatIf results in extra, unwanted output and a spurious error" (#1711)
1 parent 913a92e commit e3d0303

File tree

4 files changed

+164
-145
lines changed

4 files changed

+164
-145
lines changed

src/code/InstallHelper.cs

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ internal class InstallHelper
6060

6161
public InstallHelper(PSCmdlet cmdletPassedIn, NetworkCredential networkCredential)
6262
{
63-
CancellationTokenSource source = new CancellationTokenSource();
63+
CancellationTokenSource source = new();
6464
_cancellationToken = source.Token;
6565
_cmdletPassedIn = cmdletPassedIn;
6666
_networkCredential = networkCredential;
@@ -183,7 +183,7 @@ private List<PSResourceInfo> ProcessRepositories(
183183
ScopeType scope)
184184
{
185185
_cmdletPassedIn.WriteDebug("In InstallHelper::ProcessRepositories()");
186-
List<PSResourceInfo> allPkgsInstalled = new List<PSResourceInfo>();
186+
List<PSResourceInfo> allPkgsInstalled = new();
187187
if (repository != null && repository.Length != 0)
188188
{
189189
// Write error and disregard repository entries containing wildcards.
@@ -262,7 +262,7 @@ private List<PSResourceInfo> ProcessRepositories(
262262
var noToAll = false;
263263

264264
var findHelper = new FindHelper(_cancellationToken, _cmdletPassedIn, _networkCredential);
265-
List<string> repositoryNamesToSearch = new List<string>();
265+
List<string> repositoryNamesToSearch = new();
266266
bool sourceTrusted = false;
267267

268268
// Loop through all the repositories provided (in priority order) until there no more packages to install.
@@ -330,7 +330,7 @@ private List<PSResourceInfo> ProcessRepositories(
330330
allPkgsInstalled.AddRange(installedPkgs);
331331
}
332332

333-
if (_pkgNamesToInstall.Count > 0)
333+
if (!_cmdletPassedIn.MyInvocation.BoundParameters.ContainsKey("WhatIf") && _pkgNamesToInstall.Count > 0)
334334
{
335335
string repositoryWording = repositoryNamesToSearch.Count > 1 ? "registered repositories" : "repository";
336336
_cmdletPassedIn.WriteError(new ErrorRecord(
@@ -547,7 +547,7 @@ private List<PSResourceInfo> InstallPackages(
547547
FindHelper findHelper)
548548
{
549549
_cmdletPassedIn.WriteDebug("In InstallHelper::InstallPackages()");
550-
List<PSResourceInfo> pkgsSuccessfullyInstalled = new List<PSResourceInfo>();
550+
List<PSResourceInfo> pkgsSuccessfullyInstalled = new();
551551

552552
// Install parent package to the temp directory,
553553
// Get the dependencies from the installed package,
@@ -658,7 +658,7 @@ private List<PSResourceInfo> InstallPackages(
658658
}
659659

660660
// If -WhatIf is passed in, early out.
661-
if (!_cmdletPassedIn.ShouldProcess("Exit ShouldProcess"))
661+
if (_cmdletPassedIn.MyInvocation.BoundParameters.ContainsKey("WhatIf"))
662662
{
663663
return pkgsSuccessfullyInstalled;
664664
}
@@ -1328,17 +1328,17 @@ private bool CallAcceptLicense(PSResourceInfo p, string moduleManifest, string t
13281328

13291329
if (File.Exists(moduleManifest))
13301330
{
1331-
using (StreamReader sr = new StreamReader(moduleManifest))
1331+
using (StreamReader sr = new(moduleManifest))
13321332
{
13331333
var text = sr.ReadToEnd();
13341334

13351335
var pattern = "RequireLicenseAcceptance\\s*=\\s*\\$true";
13361336
var patternToSkip1 = "#\\s*RequireLicenseAcceptance\\s*=\\s*\\$true";
13371337
var patternToSkip2 = "\\*\\s*RequireLicenseAcceptance\\s*=\\s*\\$true";
13381338

1339-
Regex rgx = new Regex(pattern);
1340-
Regex rgxComment1 = new Regex(patternToSkip1);
1341-
Regex rgxComment2 = new Regex(patternToSkip2);
1339+
Regex rgx = new(pattern);
1340+
Regex rgxComment1 = new(patternToSkip1);
1341+
Regex rgxComment2 = new(patternToSkip2);
13421342
if (rgx.IsMatch(text) && !rgxComment1.IsMatch(text) && !rgxComment2.IsMatch(text))
13431343
{
13441344
requireLicenseAcceptance = true;
@@ -1409,14 +1409,14 @@ private bool DetectClobber(string pkgName, Hashtable parsedMetadataHashtable, ou
14091409

14101410
// Get installed modules, then get all possible paths
14111411
// selectPrereleaseOnly is false because even if Prerelease is true we want to include both stable and prerelease, would never select prerelease only.
1412-
GetHelper getHelper = new GetHelper(_cmdletPassedIn);
1412+
GetHelper getHelper = new(_cmdletPassedIn);
14131413
IEnumerable<PSResourceInfo> pkgsAlreadyInstalled = getHelper.GetPackagesFromPath(
14141414
name: new string[] { "*" },
14151415
versionRange: VersionRange.All,
14161416
pathsToSearch: _pathsToSearch,
14171417
selectPrereleaseOnly: false);
14181418

1419-
List<string> listOfCmdlets = new List<string>();
1419+
List<string> listOfCmdlets = new();
14201420
if (parsedMetadataHashtable.ContainsKey("CmdletsToExport"))
14211421
{
14221422
if (parsedMetadataHashtable["CmdletsToExport"] is object[] cmdletsToExport)
@@ -1430,8 +1430,8 @@ private bool DetectClobber(string pkgName, Hashtable parsedMetadataHashtable, ou
14301430

14311431
foreach (var pkg in pkgsAlreadyInstalled)
14321432
{
1433-
List<string> duplicateCmdlets = new List<string>();
1434-
List<string> duplicateCmds = new List<string>();
1433+
List<string> duplicateCmdlets = new();
1434+
List<string> duplicateCmds = new();
14351435
// See if any of the cmdlets or commands in the pkg we're trying to install exist within a package that's already installed
14361436
if (pkg.Includes.Cmdlet != null && pkg.Includes.Cmdlet.Length != 0)
14371437
{

test/InstallPSResourceTests/InstallPSResourceLocal.Tests.ps1

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
11
# Copyright (c) Microsoft Corporation.
22
# Licensed under the MIT License.
33

4+
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '')]
5+
Param()
6+
47
$ProgressPreference = "SilentlyContinue"
58
$modPath = "$psscriptroot/../PSGetTestUtils.psm1"
69
Import-Module $modPath -Force -Verbose
710

811
$psmodulePaths = $env:PSModulePath -split ';'
9-
Write-Verbose -Verbose "Current module search paths: $psmodulePaths"
12+
Write-Verbose -Verbose -Message "Current module search paths: $psmodulePaths"
1013

1114
Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
1215

13-
1416
BeforeAll {
1517
$localRepo = "psgettestlocal"
1618
$localUNCRepo = "psgettestlocal3"
@@ -54,7 +56,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
5456
$res.Version | Should -Be "5.0.0"
5557
}
5658

57-
It "Install resource given Name parameter from UNC repository" {
59+
It "Install resource given Name parameter from UNC repository" {
5860
Install-PSResource -Name $testModuleName -Repository $localUNCRepo -TrustRepository
5961
$res = Get-InstalledPSResource -Name $testModuleName
6062
$res.Name | Should -Be $testModuleName
@@ -70,7 +72,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
7072

7173
It "Install multiple resources by name" {
7274
$pkgNames = @($testModuleName, $testModuleName2)
73-
Install-PSResource -Name $pkgNames -Repository $localRepo -TrustRepository
75+
Install-PSResource -Name $pkgNames -Repository $localRepo -TrustRepository
7476
$pkg = Get-InstalledPSResource $pkgNames
7577
$pkg.Name | Should -Be $pkgNames
7678
}
@@ -83,7 +85,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
8385
}
8486

8587
It "Should install resource given name and exact version with bracket syntax" {
86-
Install-PSResource -Name $testModuleName -Version "[1.0.0.0]" -Repository $localRepo -TrustRepository
88+
Install-PSResource -Name $testModuleName -Version "[1.0.0.0]" -Repository $localRepo -TrustRepository
8789
$res = Get-InstalledPSResource $testModuleName
8890
$res.Name | Should -Be $testModuleName
8991
$res.Version | Should -Be "1.0.0"
@@ -97,7 +99,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
9799
}
98100

99101
It "Should install resource given name and exact range exclusive (1.0.0.0, 5.0.0.0)" {
100-
Install-PSResource -Name $testModuleName -Version "(1.0.0.0, 5.0.0.0)" -Repository $localRepo -TrustRepository
102+
Install-PSResource -Name $testModuleName -Version "(1.0.0.0, 5.0.0.0)" -Repository $localRepo -TrustRepository
101103
$res = Get-InstalledPSResource $testModuleName
102104
$res.Name | Should -Be $testModuleName
103105
$res.Version | Should -Be "3.0.0"
@@ -110,7 +112,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
110112
}
111113
catch
112114
{}
113-
$Error[0].FullyQualifiedErrorId | Should -be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource"
115+
$Error[0].FullyQualifiedErrorId | Should -Be "IncorrectVersionFormat,Microsoft.PowerShell.PSResourceGet.Cmdlets.InstallPSResource"
114116

115117
$res = Get-InstalledPSResource $testModuleName -ErrorAction SilentlyContinue
116118
$res | Should -BeNullOrEmpty
@@ -131,7 +133,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
131133
}
132134

133135
It "Install resource with latest (including prerelease) version given Prerelease parameter" {
134-
Install-PSResource -Name $testModuleName -Prerelease -Repository $localRepo -TrustRepository
136+
Install-PSResource -Name $testModuleName -Prerelease -Repository $localRepo -TrustRepository
135137
$pkg = Get-InstalledPSResource $testModuleName
136138
$pkg.Name | Should -Be $testModuleName
137139
$pkg.Version | Should -Be "5.2.5"
@@ -171,14 +173,14 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
171173
}
172174

173175
It "Install resource via InputObject by piping from Find-PSresource" {
174-
Find-PSResource -Name $testModuleName -Repository $localRepo | Install-PSResource -TrustRepository
176+
Find-PSResource -Name $testModuleName -Repository $localRepo | Install-PSResource -TrustRepository
175177
$pkg = Get-InstalledPSResource $testModuleName
176178
$pkg.Name | Should -Be $testModuleName
177179
$pkg.Version | Should -Be "5.0.0"
178180
}
179181

180182
It "Install resource via InputObject by piping from Find-PSResource" {
181-
$modules = Find-PSResource -Name "*" -Repository $localRepo
183+
$modules = Find-PSResource -Name "*" -Repository $localRepo
182184
$modules.Count | Should -BeGreaterThan 1
183185

184186
Install-PSResource -TrustRepository -InputObject $modules
@@ -190,7 +192,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
190192
It "Install resource under location specified in PSModulePath" {
191193
Install-PSResource -Name $testModuleName -Repository $localRepo -TrustRepository
192194
$pkg = Get-InstalledPSResource $testModuleName
193-
$pkg.Name | Should -Be $testModuleName
195+
$pkg.Name | Should -Be $testModuleName
194196
($env:PSModulePath).Contains($pkg.InstalledLocation)
195197
}
196198

@@ -212,7 +214,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
212214

213215
# Windows only
214216
It "Install resource under no specified scope - Windows only" -Skip:(!(Get-IsWindows)) {
215-
Install-PSResource -Name $testModuleName -Repository $localRepo -TrustRepository
217+
Install-PSResource -Name $testModuleName -Repository $localRepo -TrustRepository
216218
$pkg = Get-InstalledPSResource $testModuleName
217219
$pkg.Name | Should -Be $testModuleName
218220
$pkg.InstalledLocation.ToString().Contains("Documents") | Should -Be $true
@@ -240,7 +242,7 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
240242
Install-PSResource -Name $testModuleName -Repository $localRepo -TrustRepository
241243
$pkg = Get-InstalledPSResource $testModuleName
242244
$pkg.Name | Should -Be $testModuleName
243-
Install-PSResource -Name $testModuleName -Repository $localRepo -TrustRepository -WarningVariable WarningVar -warningaction SilentlyContinue
245+
Install-PSResource -Name $testModuleName -Repository $localRepo -TrustRepository -WarningVariable WarningVar -WarningAction SilentlyContinue
244246
$WarningVar | Should -Not -BeNullOrEmpty
245247
}
246248

@@ -257,6 +259,8 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
257259

258260
It "Install module using -WhatIf, should not install the module" {
259261
Install-PSResource -Name $testModuleName -Version "1.0.0.0" -Repository $localRepo -TrustRepository -WhatIf
262+
$? | Should -BeTrue
263+
260264
$res = Get-InstalledPSResource -Name $testModuleName -ErrorAction SilentlyContinue
261265
$res | Should -BeNullOrEmpty
262266
}
@@ -270,11 +274,11 @@ Describe 'Test Install-PSResource for local repositories' -tags 'CI' {
270274
It "Get definition for alias 'isres'" {
271275
(Get-Alias isres).Definition | Should -BeExactly 'Install-PSResource'
272276
}
273-
277+
274278
It "Not install resource that lists dependency packages which cannot be found" {
275279
$localRepoUri = Join-Path -Path $TestDrive -ChildPath "testdir"
276280
Save-PSResource -Name "test_script" -Repository "PSGallery" -TrustRepository -Path $localRepoUri -AsNupkg -SkipDependencyCheck
277-
Write-Host $localRepoUri
281+
Write-Information -InformationAction Continue -MessageData $localRepoUri
278282
$res = Install-PSResource -Name "test_script" -Repository $localRepo -TrustRepository -PassThru -ErrorVariable err -ErrorAction SilentlyContinue
279283
$res | Should -BeNullOrEmpty
280284
$err.Count | Should -Not -Be 0

0 commit comments

Comments
 (0)