public/Install-Package.ps1

# Installs packages based on the provided Fast Package Reference generated by Find-Package
function Install-Package {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidOverwritingBuiltInCmdlets', '', Justification='Required by PackageManagement')]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [string]
        $FastPackageReference
    )

    Write-Debug -Message ($LocalizedData.ProviderDebugMessage -f ('Install-Package'))
    Write-Debug -Message ($LocalizedData.FastPackageReference -f $FastPackageReference)

    # If the fast package reference doesnt match the pattern we expect, throw an exception
    if ((-Not ($FastPackageReference -Match $script:FastReferenceRegex)) -Or (-Not ($Matches.name -And $Matches.version))) {
        ThrowError -ExceptionName "System.ArgumentException" `
            -ExceptionMessage ($LocalizedData.FailToInstall -f $FastPackageReference) `
            -ErrorId 'FailToInstall' `
            -ErrorCategory InvalidArgument
    }

    $shouldContinueQueryMessage = ($LocalizedData.InstallPackageQuery -f "Installing", $Matches.name)
    $shouldContinueCaption = $LocalizedData.InstallPackageCaption

    # If the user opts not to install the package, exit from the script
    if (-Not ((Get-PromptBypass) -Or $request.ShouldContinue($shouldContinueQueryMessage, $shouldContinueCaption))) {
        Write-Warning ($LocalizedData.NotInstalled -f $FastPackageReference)
        return
    }

    $installArgs = @{
        Name = $Matches.source+'/'+$Matches.name
    }

    switch ($Matches.type) {
        'Cask' {$installArgs.Cask = $true}
        'Formula' {$installArgs.Formula = $true}
    }

    # Validate what Homebrew installed matched what we requested, then convert the PSCustomObject output from Croze into PackageManagement SWIDs
    $swid = Croze\Install-HomebrewPackage @installArgs | ConvertTo-SoftwareIdentity

    if (-Not $swid) {
        # Croze returned something, but not in the format we expected. Something is amiss.
        Write-Warning ($LocalizedData.UnexpectedHomebrewResponse -f $FastPackageReference)
    }

    $swid
}