Prism.psm1

# Copyright WebMD Health Services
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License

#Requires -Version 5.1
Set-StrictMode -Version 'Latest'

# Functions should use $moduleRoot as the relative root from which to find
# things. A published module has its function appended to this file, while a
# module in development has its functions in the Functions directory.
$moduleRoot = $PSScriptRoot

# Store each of your module's functions in its own file in the Functions
# directory. On the build server, your module's functions will be appended to
# this file, so only dot-source files that exist on the file system. This allows
# developers to work on a module without having to build it first. Grab all the
# functions that are in their own files.
$functionsPath = Join-Path -Path $moduleRoot -ChildPath 'Functions\*.ps1'
if( (Test-Path -Path $functionsPath) )
{
    foreach( $functionPath in (Get-Item $functionsPath) )
    {
        . $functionPath.FullName
    }
}



function Get-PackageManagementPreference
{
    [CmdletBinding()]
    param(
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

    $deepPrefs = @{}
    if( (Test-Path -Path 'env:PRISM_DISABLE_DEEP_DEBUG') -and `
        'Continue' -in @($Global:DebugPreference, $DebugPreference) )
    {
        $deepPrefs['Debug'] = $false
    }

    if( (Test-Path -Path 'env:PRISM_DISABLE_DEEP_VERBOSE') -and `
        'Continue' -in @($Global:VerbosePreference, $VerbosePreference))
    {
        $deepPrefs['Verbose'] = $false
    }

    return $deepPrefs
}



# Ugh. I hate this name, but it interferes with Install-Module in one of the package management modules.
function Install-PrivateModule
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [Object] $Configuration
    )

    begin
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

        $pkgMgmtPrefs = Get-PackageManagementPreference
    }

    process
    {
        if( -not (Test-Path -Path $Configuration.LockPath) )
        {
            $Configuration | Update-ModuleLock | Format-Table
        }

        $repoByLocation = @{}
        Get-PSRepository | ForEach-Object { $repoByLocation[$_.SourceLocation] = $_.Name }

        $locks = Get-Content -Path $Configuration.LockPath | ConvertFrom-Json
        $locks | Add-Member -Name 'PSModules' -MemberType NoteProperty -Value @() -ErrorAction Ignore
        foreach( $module in $locks.PSModules )
        {
            $installedModules =
                Get-Module -Name $module.name -ListAvailable -ErrorAction Ignore |
                Add-Member -Name 'SemVer' -MemberType ScriptProperty -Value {
                    $prerelease = $this.PrivateData['PSData']['PreRelease']
                    if( $prerelease )
                    {
                        $prerelease = "-$($prerelease)"
                    }
                    return "$($this.Version)$($prerelease)"
                }

            $installedModule = $installedModules | Where-Object SemVer -EQ $module.version 
            if( -not $installedModule )
            {
                $repoName = $repoByLocation[$module.repositorySourceLocation]
                if( -not $repoName )
                {
                    $msg = "PowerShell repository at ""$($module.repositorySourceLocation)"" does not exist. Use " +
                            '"Get-PSRepository" to see the current list of repositories, "Register-PSRepository" ' +
                            'to add a new repository, or "Set-PSRepository" to update an existing repository.'
                    Write-Error $msg
                    continue
                }

                $savePath =
                    Join-Path -Path $Configuration.File.DirectoryName -ChildPath $Configuration.PSModulesDirectoryName

                if( -not (Test-Path -Path $savePath) )
                {
                    New-Item -Path $savePath -ItemType 'Directory' -Force | Out-Null
                }

                Save-Module -Name $module.name `
                            -Path $savePath `
                            -RequiredVersion $module.version `
                            -AllowPrerelease `
                            -Repository $repoName `
                            @pkgMgmtPrefs
            }

            $modulePath = Join-Path -Path $savePath -ChildPath $module.name | Resolve-Path -Relative
            $installedModule = [pscustomobject]@{
                Name = $module.name;
                Version = $module.version;
                Path = $modulePath;
                RepositorySourceLocation = $module.repositorySourceLocation;
            }
            $installedModule.pstypenames.Add('Prism.InstalledModule')
            $installedModule | Write-Output
        }
    }
}

function Invoke-Prism
{
    <#
    .SYNOPSIS
    Invokes Prism.
 
    .DESCRIPTION
    A tool similar to nuget but for PowerShell modules. A config file in the root of a repository that specifies
    what modules should be installed into the PSModules directory of the repository. If a path is provided for the
    module it will be installed at the specified path instead of the PSModules directory.
 
    .EXAMPLE
    Invoke-Prism 'install'
 
    Demonstrates how to call this function to install required PSModules.
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [ValidateSet('install', 'update')]
        [String] $Command,

        # The name of the Prism configuration file to use. Defaults to `prism.json`.
        [String] $FileName = 'prism.json',

        [switch] $Recurse
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

    $origModulePath = $env:PSModulePath

    $pkgMgmtPrefs = Get-PackageManagementPreference
    try
    {
        # prism should ship with its own private copies of PackageManagement and PowerShellGet. Setting PSModulePath
        # to prism module's Modules directory ensures no other package modules get loaded.
        $pkgManagementModulePath = Join-Path -Path $moduleRoot -ChildPath 'PSModules'
        $env:PSModulePath = $pkgManagementModulePath
        Write-Debug 'AVAILABLE MODULES'
        Get-Module -ListAvailable | Format-Table -AutoSize | Out-String | Write-Debug
        Import-Module -Name 'PackageManagement' @pkgMgmtPrefs
        Import-Module -Name 'PowerShellGet' @pkgMgmtPrefs
        Write-Debug 'IMPORTED MODULES'
        Get-Module | Format-Table -AutoSize | Out-String | Write-Debug

        Write-Debug 'AVAILABLE MODULES'
        Write-Debug "PSModulePath $($env:PSModulePath)"
        Get-Module -ListAvailable | Format-Table -AutoSize | Out-String | Write-Debug

        $Force = $FileName.StartsWith('.')
        $prismJsonFiles = Get-ChildItem -Path '.' -Filter $FileName -Recurse:$Recurse -Force:$Force -ErrorAction Ignore
        if( -not $prismJsonFiles )
        {
            $msg = ''
            $suffix = ''
            if( $Recurse )
            {
                $suffix = 's'
                $msg = ' or any of its sub-directories'
            }

            $msg = "No $($FileName) file$($suffix) found in the current directory$($msg)."
            Write-Error -Message $msg -ErrorAction Stop
            return
        }

        foreach( $prismJsonFile in $prismJsonFiles )
        {
            $path = $prismJsonFile.FullName
            $config = Get-Content -Path $path | ConvertFrom-Json
            if( -not $config )
            {
                Write-Warning "File ""$($path | Resolve-Path -Relative) is empty."
                continue
            }

            $lockBaseName = [IO.Path]::GetFileNameWithoutExtension($path)
            $lockExtension = [IO.Path]::GetExtension($path)
            # Hidden file with no extension, e.g. `.prism`
            if( -not $lockBaseName -and $lockExtension )
            {
                $lockBaseName = $lockExtension
                $lockExtension = ''
            }

            $lockPath = Join-Path -Path ($path | Split-Path -Parent) -ChildPath "$($lockBaseName).lock$($lockExtension)"
            # private members that users aren't allowed to customize.
            $config |
                Add-Member -Name 'Path' -MemberType NoteProperty -Value $path -PassThru -Force |
                Add-Member -Name 'File' -MemberType NoteProperty -Value $prismJsonFile -PassThru -Force |
                Add-Member -Name 'LockPath' -MemberType NoteProperty -Value $lockPath -PassThru -Force |
                Out-Null

            $ignore = @{ 'ErrorAction' = 'Ignore' }
            # public configuration that users can customize.
            # Add-Member doesn't return an object if the member already exists, so these can't be part of the pipeline.
            $config | Add-Member -Name 'PSModules' -MemberType NoteProperty -Value @() @ignore
            $config | Add-Member -Name 'PSModulesDirectoryName' -MemberType NoteProperty -Value 'PSModules' @ignore

            # This makes it so we can use PowerShell's module cmdlets as much as possible.
            $privateModulePath =  Join-Path -Path $prismJsonFile.DirectoryName -ChildPath $config.PSModulesDirectoryName
            $env:PSModulePath = "$($privateModulePath)$([IO.Path]::PathSeparator)$($pkgManagementModulePath)"

            switch( $Command )
            {
                'install' 
                {
                    $config | Install-PrivateModule
                }
                'update'
                {
                    $config | Update-ModuleLock
                }
            }
        }
    }
    finally
    {
        $env:PSModulePath = $origModulePath
    }
}

Set-Alias -Name 'prism' -Value 'Invoke-Prism'


function Select-Module
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [Object] $Module,

        [Parameter(Mandatory)]
        [String] $Name,

        [String] $Version,

        [switch] $AllowPrerelease
    )

    process
    {
        if( $Module.Name -ne $Name )
        {
            return
        }

        if( $Version -and $Module.Version -notlike $Version )
        {
            return
        }

        if( $AllowPrerelease )
        {
            return $Module
        }

        [Version]$moduleVersion = $null
        if( [Version]::TryParse($Module.Version, [ref]$moduleVersion) )
        {
            return $Module
        }
    }
}


function Update-ModuleLock
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [Object] $Configuration
    )

    begin
    {
        Set-StrictMode -Version 'Latest'
        Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

        $pkgMgmtPrefs = Get-PackageManagementPreference
    }

    process
    {
        $modulesNotFound = [Collections.ArrayList]::New()
        $moduleNames = $Configuration.PSModules | Select-Object -ExpandProperty 'Name'
        if( -not $moduleNames )
        {
            Write-Warning "There are no modules listed in ""$($Path | Resolve-Path -Relative)""."
            return
        }

        $numFinds = $moduleNames | Measure-Object | Select-Object -ExpandProperty 'Count'
        $numFinds = $numFinds + 2
        Write-Debug " numSteps $($numFinds)"
        $curStep = 0
        $uniqueModuleNames = $moduleNames | Select-Object -Unique
        $status = "Find-Module -Name '$($uniqueModuleNames -join "', '")'"
        $percentComplete = ($curStep++/$numFinds * 100)
        $activity = @{ Activity = 'Resolving Module Versions' }
        Write-Progress @activity -Status $status -PercentComplete $percentComplete

        try
        {
            $modules = Find-Module -Name $uniqueModuleNames -ErrorAction Ignore @pkgMgmtPrefs
            if( -not $modules )
            {
                $msg = "$($Path | Resolve-Path -Relative): Modules ""$($uniqueModuleNames -join '", "')"" not " +
                       'found.'
                Write-Error $msg
                return
            }

            # Find-Module is expensive. Limit calls as much as possible.
            $findModuleCache = @{}

            $locks = [Collections.ArrayList]::New()

            $env:PSModulePath =
                Join-Path -Path $Configuration.File.DirectoryName -ChildPath $Configuration.PSModulesDirectoryName
            foreach( $pxModule in $Configuration.PSModules )
            {
                $optionalParams = @{}

                # Make sure these members are present and have default values.
                $pxModule | Add-Member -Name 'Version' -MemberType NoteProperty -Value '' -ErrorAction Ignore
                $pxModule |
                    Add-Member -Name 'AllowPrerelease' -MemberType NoteProperty -Value $false -ErrorAction Ignore

                $versionDesc = 'latest'
                if( $pxModule.Version )
                {
                    $versionDesc = $optionalParams['Version'] = $pxModule.Version
                }

                $allowPrerelease = $false
                if( $pxModule.AllowPrerelease -or $pxModule.Version -match '-' )
                {
                    $allowPrerelease = $optionalParams['AllowPrerelease'] = $true
                }

                $curStep += 1

                Write-Debug " curStep $($curStep)"
                $moduleToInstall =
                    $modules | Select-Module -Name $pxModule.Name @optionalParams | Select-Object -First 1
                if( -not $moduleToInstall )
                {
                    $status = "Find-Module -Name '$($pxModule.Name)' -AllVersions"
                    if( $allowPrerelease )
                    {
                        $status = "$($status) -AllowPrerelease"
                    }

                    if( -not $findModuleCache.ContainsKey($status) )
                    {
                        Write-Progress @activity -Status $status -PercentComplete ($curStep/$numFinds * 100)
                        $findModuleCache[$status] = Find-Module -Name $pxModule.Name `
                                                                -AllVersions `
                                                                -AllowPrerelease:$allowPrerelease `
                                                                -ErrorAction Ignore `
                                                                @pkgMgmtPrefs
                    }
                    $moduleToInstall =
                        $findModuleCache[$status] |
                        Select-Module -Name $pxModule.Name @optionalParams |
                        Select-Object -First 1
                }

                if( -not $moduleToInstall )
                {
                    [void]$modulesNotFound.Add($pxModule.Name)
                    continue
                }

                $pin = [pscustomobject]@{
                    name = $moduleToInstall.Name;
                    version = $moduleToInstall.Version;
                    repositorySourceLocation = $moduleToInstall.RepositorySourceLocation;
                }
                [void]$locks.Add( $pin )

                if( -not (Test-Path -Path $Configuration.LockPath) )
                {
                    New-Item -Path $Configuration.LockPath `
                             -ItemType 'File' `
                             -Value (([pscustomobject]@{}) | ConvertTo-Json) |
                        Out-Null
                }

                $moduleLock = [pscustomobject]@{
                    ModuleName = $pxModule.Name;
                    Version = $versionDesc;
                    LockedVersion = $pin.version;
                    RepositorySourceLocation = $pin.repositorySourceLocation;
                    Path = ($Configuration.LockPath | Resolve-Path -Relative);
                }
                $moduleLock.pstypenames.Add('Prism.ModuleLock')
                $moduleLock | Write-Output
            }

            Write-Progress @activity -Status "Saving lock file ""$($Configuration.LockPath)""." -PercentComplete 100
            $prismLock = [pscustomobject]@{
                PSModules = $locks;
            }
            $prismLock | ConvertTo-Json -Depth 2 | Set-Content -Path $Configuration.LockPath -NoNewline

            if( $modulesNotFound.Count )
            {
                $suffix = ''
                if( $modulesNotFound.Count -gt 1 )
                {
                    $suffix = 's'
                }
                $msg = "$($Path | Resolve-Path -Relative): Module$($suffix) ""$($modulesNotFound -join '", "')"" not " +
                       'found.'
                Write-Error $msg
            }
        }
        finally
        {
            Write-Progress @activity -Completed
        }
    }
}


function Use-CallerPreference
{
    <#
    .SYNOPSIS
    Sets the PowerShell preference variables in a module's function based on the callers preferences.
 
    .DESCRIPTION
    Script module functions do not automatically inherit their caller's variables, including preferences set by common
    parameters. This means if you call a script with switches like `-Verbose` or `-WhatIf`, those that parameter don't
    get passed into any function that belongs to a module.
 
    When used in a module function, `Use-CallerPreference` will grab the value of these common parameters used by the
    function's caller:
 
     * ErrorAction
     * Debug
     * Confirm
     * InformationAction
     * Verbose
     * WarningAction
     * WhatIf
     
    This function should be used in a module's function to grab the caller's preference variables so the caller doesn't
    have to explicitly pass common parameters to the module function.
 
    This function is adapted from the [`Get-CallerPreference` function written by David Wyatt](https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d).
 
    There is currently a [bug in PowerShell](https://connect.microsoft.com/PowerShell/Feedback/Details/763621) that
    causes an error when `ErrorAction` is implicitly set to `Ignore`. If you use this function, you'll need to add
    explicit `-ErrorAction $ErrorActionPreference` to every `Write-Error` call. Please vote up this issue so it can get
    fixed.
 
    .LINK
    about_Preference_Variables
 
    .LINK
    about_CommonParameters
 
    .LINK
    https://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d
 
    .LINK
    http://powershell.org/wp/2014/01/13/getting-your-script-module-functions-to-inherit-preference-variables-from-the-caller/
 
    .EXAMPLE
    Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
 
    Demonstrates how to set the caller's common parameter preference variables in a module function.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        #[Management.Automation.PSScriptCmdlet]
        # The module function's `$PSCmdlet` object. Requires the function be decorated with the `[CmdletBinding()]`
        # attribute.
        $Cmdlet,

        [Parameter(Mandatory)]
        # The module function's `$ExecutionContext.SessionState` object. Requires the function be decorated with the
        # `[CmdletBinding()]` attribute.
        #
        # Used to set variables in its callers' scope, even if that caller is in a different script module.
        [Management.Automation.SessionState]$SessionState
    )

    Set-StrictMode -Version 'Latest'

    # List of preference variables taken from the about_Preference_Variables and their common parameter name (taken
    # from about_CommonParameters).
    $commonPreferences = @{
                              'ErrorActionPreference' = 'ErrorAction';
                              'DebugPreference' = 'Debug';
                              'ConfirmPreference' = 'Confirm';
                              'InformationPreference' = 'InformationAction';
                              'VerbosePreference' = 'Verbose';
                              'WarningPreference' = 'WarningAction';
                              'WhatIfPreference' = 'WhatIf';
                          }

    foreach( $prefName in $commonPreferences.Keys )
    {
        $parameterName = $commonPreferences[$prefName]

        # Don't do anything if the parameter was passed in.
        if( $Cmdlet.MyInvocation.BoundParameters.ContainsKey($parameterName) )
        {
            continue
        }

        $variable = $Cmdlet.SessionState.PSVariable.Get($prefName)
        # Don't do anything if caller didn't use a common parameter.
        if( -not $variable )
        {
            continue
        }

        if( $SessionState -eq $ExecutionContext.SessionState )
        {
            Set-Variable -Scope 1 -Name $variable.Name -Value $variable.Value -Force -Confirm:$false -WhatIf:$false
        }
        else
        {
            $SessionState.PSVariable.Set($variable.Name, $variable.Value)
        }
    }
}