OneGet / oneget

PackageManagement (aka OneGet) is a package manager for Windows
MIT License
2.38k stars 190 forks source link

MSFT_PackageManagement: Fix passing switch values in AdditionalParameters #500

Open jberezanski opened 3 years ago

jberezanski commented 3 years ago

When a DSC configuration, which uses the PackageManagement resource and attempts to pass provider-specific parameters via AdditionalParameters, is compiled, the parameters dictionary is serialized to MSFT_KeyValuePair objects, which hold a pair of strings. As a consequence, all type information about AdditionalParameters values is lost.

This poses a problem when a provider defines parameters whose types are not implictly convertible from string. Two such common types are [switch] and [bool]. For example, the PowerShellGet provider defines several switch parameters, such as InstallUpdate, AllowClobber or AllowPrereleaseVersions - all of those are quite important. Unfortunately, attempting to pass values to those parameters in a DSC configuration leads to failures, caused by attempts to directly assign a string value to a SwitchParameter.

This pull request solves this problem. Although the PackageManagement resource has no direct access to provider metadata, it can examine the parameters of the cmdlets it intends to call and determine their types. For [switch] and [bool] parameters, the resource parses the string value from AdditionalParameters to a [bool], which is implicitly convertible to [switch].

Example configuration, which fails on 1.4.7 and works after this PR:

configuration TestSwitches
{
    Import-DscResource -Module @{ModuleName="PackageManagement"; ModuleVersion="1.4.8"} # assuming the changes are released in this version

    node localhost
    {
        PackageManagementSource PSGallery
        {
            Ensure = 'Present'
            Name = 'PSGallery'
            ProviderName = 'PowerShellGet'
            SourceLocation = 'https://www.powershellgallery.com/api/v2'
            InstallationPolicy = 'Trusted'
        }

        PackageManagement SF_PS_Http
        {
            Ensure = 'Present'
            Name = 'Microsoft.ServiceFabric.PowerShell.Http'
            MinimumVersion = '1.4.2-preview1'
            ProviderName = 'PowerShellGet'
            Source = 'PSGallery'
            AdditionalParameters = @{ AllowPrereleaseVersions = $true; InstallUpdate = $true; Scope = 'AllUsers'; AllowClobber = $true; SkipPublisherCheck = $true; Type = 'Module' }
            DependsOn = @('[PackageManagementSource]PSGallery')
        }
    }
}
jberezanski commented 3 years ago

It seems the AppVeyor jobs are trying to pull NuGet packages from a nonexistent feed (https://powershell.myget.org/F/powershell-core/api/v3/index.json).