PythonSelect.psm1

<#
.SYNOPSIS
Makes the specified Python distribution the active one for the current session.
 
.DESCRIPTION
A Python distribution is considered "active" when its installation and script locations are both in the current PATH
environment variable and are not shadowed by another distribution. When a Python distribution is enabled, the PATH is
scrubbed of any references to any other Python distribution. Then the selected distribution's installation and script
locations are appended to the PATH.
 
The environment changes remain active only for the current session. Once a distribution has been enabled, references in
the PATH to Python locations should NOT be added, removed, or modified. This may interfere with future attempts to
enable different Python environments within the same session.
 
Parameters can be given to select the distribution that should be enabled. These parameters behave exactly like those
passed to Get-PythonDistribution. See the help for Get-PythonDistribution for more information. If no parameters are
given, then this will attempt to enable the latest version of the official Python distribution found on the system.
 
If no distributions are found matching the given parameters or multiple distributions are found, then this will fail.
 
.PARAMETER Company
Selects and activates a distribution whose company matches the given value.
 
.PARAMETER Tag
Selects and activates a distribution whose tag matches the given value.
 
.PARAMETER Version
Selects and activates a distribution whose version matches the given value. This can also be set to "latest", which
causes only the most recent version of those distributions matching the other filter criteria to be activated.
 
.PARAMETER Bitness
Selects and activates a distribution whose bitness matches the given value.
 
.PARAMETER Scope
Selects and activates a distribution whose scope matches the given value.
 
#>

function Enable-Python {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string] $Company,

        [Parameter()]
        [string] $Tag,

        [Parameter()]
        [string] $Version,

        [Parameter()]
        [ValidateSet( "32", "64" )]
        [string] $Bitness,

        [Parameter()]
        [ValidateSet( "System" , "CurrentUser" )]
        [string] $Scope
    )

    $ErrorActionPreference = "Stop"

    # If no selection criteria is given, we'll try to select the latest version of the standard Python distribution.
    if( -not $Company -and -not $Tag -and -not $Version ) {
        Write-Host "No distribution information given. Searching for latest version of the standard Python distribution."
        $Company = "PythonCore"
        $Version = "latest"

        # If no bitness was selected, then we'll try to select the one whose bitness matches the current environment.
        if( -not $Bitness ) {
            $Bitness = if( [System.Environment]::Is64BitProcess ) { "64" } else { "32" }
        }

        # Unless the user is requesting a specific scope, then make sure we search the system scope.
        if( -not $Scope ) {
            $Scope = "System"
        }
    }

    $getArgs = @{}
    if( $Company ) { $getArgs.Company = $Company }
    if( $Tag ) { $getArgs.Tag = $Tag }
    if( $Version ) { $getArgs.Version = $Version }
    if( $Bitness ) { $getArgs.Bitness = $Bitness }
    if( $Scope ) { $getArgs.Scope = $Scope }

    $distributions = Get-PythonDistribution @getArgs
    if( $distributions.Count -eq 0 ) {
        Write-Host "No Python distributions found matching given distribution information."
        throw "Failed to enable Python distribution. No distributions found."
    }

    if( $distributions.Count -gt 1 ) {
        Write-Host "Multiple Python distributions found matching given distribution information:"
        $distributions | Format-Table -Property Company,Tag,Version,Bitness,Scope | Out-Host
        throw "Failed to enable Python distribution. Ambiguous selection."
    }

    # If this is the first invocation of this cmdlet, wipe any Python paths the user may have previously had set.
    if( -not $global:EnablePythonAlreadySet ) {
        Get-PythonDistribution | Clear-PythonInstallPath
        $global:EnablePythonAlreadySet = $true
    }

    $distribution = $distributions[0]
    Write-Host "Python distribution found in $($distribution.InstallPath). Updating PATH."

    if( $global:EnablePythonInstallPath ) {
        Clear-PythonInstallPath -InstallPath $global:EnablePythonInstallPath
    }

    $environmentPaths = $env:Path.Split( [System.IO.Path]::PathSeparator, [System.StringSplitOptions]::None )
    $environmentPaths += @( $distribution.InstallPath, (Join-Path $distribution.InstallPath "Scripts") )
    $env:Path = [string]::Join( [System.IO.Path]::PathSeparator, $environmentPaths )
    $global:EnablePythonInstallPath = $distribution.InstallPath
}
<#
.SYNOPSIS
Gets information on all registered Python distributions installed on the current system.
 
.DESCRIPTION
According to PEP 514 (https://www.python.org/dev/peps/pep-0514/), Python distributions are to register themselves on
Windows using well-defined registry locations. Distributions can either be installed in a system-wide location or in a
user-specific location.
 
Within a given scope, distributions are differentiated by a pair of values denoting what PEP 514 refers to as the
distribution's company and the tag. Each distribution can also be 32- or 64-bit.
 
These identifying pieces of information can be used to discover which Python distributions are available to the user on
the current system. They can also be used to filter the list of available distributions, which is useful for eventually
enabling a particular distribution within the current session.
 
When no arguments are given, information on all registered Python distributions with a valid installation are returned.
The values returned can then be passed to Enable-Python to enable a specific distribution. Passing additional arguments
will filter the list of returned distributions based on the filtered properties.
 
A filter on a distribution property will match a distribution if any of the following conditions are met:
 
  1. The distribution's property matches exactly the filtered value.
  2. The distribution's property is prefixed by the filtered value.
  3. The distribution's property is "like" the filtered value (according to the rules of the -like operator). This means
     the filtered value can contain wildcard characters.
 
All comparisons and checks are done in a case-insensitive manner.
 
.PARAMETER Company
Returns distributions whose company matches the given value.
 
.PARAMETER Tag
Returns distributions whose tag matches the given value.
 
.PARAMETER Version
Returns distributions whose version matches the given value. This can also be set to "latest", which causes only the
most recent version of those distributions matching the other filter criteria to be returned.
 
.PARAMETER Bitness
Returns distributions whose bitness matches the given value.
 
.PARAMETER Scope
Returns distributions whose scope matches the given value.
 
#>

function Get-PythonDistribution {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string] $Company,

        [Parameter()]
        [string] $Tag,

        [Parameter()]
        [string] $Version,

        [Parameter()]
        [ValidateSet( "32", "64" )]
        [string] $Bitness,

        [Parameter()]
        [ValidateSet( "System", "CurrentUser" )]
        [string] $Scope
    )

    $ErrorActionPreference = "Stop"

    $distributions = @()
    $distributionSets = @(
        @{
            RegKeyPrefix = "HKLM:\SOFTWARE\Python"
            Scope = "System"
        },

        @{
            RegKeyPrefix = "HKLM:\SOFTWARE\WOW6432Node\Python"
            Scope = "System"
        }

        @{
            RegKeyPrefix = "HKCU:\Software\Python"
            Scope = "CurrentUser"
        }
    )

    foreach( $distributionSet in $distributionSets ) {
        if( -not $Scope -or $distributionSet.Scope -eq $Scope ) {
            foreach( $companyKey in (Get-ChildItem -Path $distributionSet.RegKeyPrefix -ErrorAction Ignore) ) {
                if( -not $Company -or (Compare-DistributionSelector $companyKey.PSChildName $Company) ) {
                    foreach( $tagKey in (Get-ChildItem -Path $companyKey.PSPath) ) {
                        if( -not $Tag -or (Compare-DistributionSelector $tagKey.PSChildName $Tag) ) {
                            $installPathKey = Get-Item -Path "$($tagKey.PSPath)\InstallPath" -ErrorAction Ignore
                            if( $installPathKey ) {
                                $installPath = Get-ItemPropertyValue -Path $installPathKey.PSPath -Name "(Default)"

                                # If we can't get the distribution version or bitness, this is usually because there is
                                # no Python interpreter installed at the given install path. This would typically happen
                                # if a distribution doesn't properly clean out its registry keys whenever it is removed.
                                $distributionVersion = Get-DistributionVersion -InstallPath $installPath
                                if( -not $distributionVersion ) {
                                    Write-Warning ("Cannot determine distribution version. Skipping distribution " +
                                        "located at install path $installPath (Company=$($companyKey.PSChildName), " +
                                        "Tag=$($tagKey.PSChildName), Scope=$($distributionSet.Scope)).")
                                    continue
                                }

                                if( $Version -and $Version -ne "latest" -and
                                    -not (Compare-DistributionSelector $distributionVersion $Version) ) {
                                    continue
                                }

                                $distributionBitness = Get-DistributionBitness -InstallPath $installPath
                                if( -not $distributionBitness ) {
                                    Write-Warning ("Cannot determine distribution bitness. Skipping distribution " +
                                        "located at install path $installPath (Company=$($companyKey.PSChildName), " +
                                        "Tag=$($tagKey.PSChildName), Scope=$($distributionSet.Scope)).")
                                    continue
                                }

                                if( $Bitness -and -not (Compare-DistributionSelector $distributionBitness $Bitness) ) {
                                    continue
                                }

                                $distributions += [PSCustomObject]@{
                                    Company = $companyKey.PSChildName
                                    Tag = $tagKey.PSChildName
                                    Version = $distributionVersion
                                    Bitness = $distributionBitness
                                    Scope = $distributionSet.Scope
                                    InstallPath = $installPath
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    if( $Version -eq "latest" ) {
        $latestVersion = $distributions | `
            % { [System.Version]$_.Version } | `
            Measure-Object -Maximum | `
            Select-Object -ExpandProperty Maximum

        $distributions = $distributions | ? { $_.Version -eq $latestVersion }
    }

    $distributions
}
<#
.SYNOPSIS
Removes traces of the given installation location to a particular Python distribution from the user's PATH.
 
.DESCRIPTION
This searches for the given installation location as well as $InstallPath\Scripts in the user's PATH environment
variable. If either are found, then they are removed. These changes do not persist beyond the current session in which
they are made.
 
.PARAMETER InstallPath
Root directory of the Python distribution to search for in the user's PATH.
 
#>

function Clear-PythonInstallPath {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory, ValueFromPipelineByPropertyName )]
        [string[]] $InstallPath
    )

    begin {
        $environmentPaths = $env:Path.Split( [System.IO.Path]::PathSeparator, [System.StringSplitOptions]::None )
        $normalizedEnvironmentPaths = $environmentPaths | % { if( $_ ) { Get-NormalizedPath -Path $_ } else { "" } }
        $pathsToRemove = @()
    }

    process {
        foreach( $path in $InstallPath ) {
            $pythonPath = Get-NormalizedPath -Path $path
            $scriptsPath = Get-NormalizedPath -Path (Join-Path $path "Scripts")

            for( $iEnvPath = 0; $iEnvPath -lt $environmentPaths.Count; $iEnvPath++ ) {
                if( $pythonPath -eq $normalizedEnvironmentPaths[$iEnvPath] -or
                    $scriptsPath -eq $normalizedEnvironmentPaths[$iEnvPath] ) {
                    $pathsToRemove += $environmentPaths[$iEnvPath]
                }
            }
        }
    }

    end {
        $environmentPaths = $environmentPaths | ? { $pathsToRemove -notcontains $_ }
        $env:Path = [string]::Join( [System.IO.Path]::PathSeparator, $environmentPaths )
    }
}
<#
.SYNOPSIS
Checks to see if the reference selector matches the given difference selector. Read the description to see what
constitutes a match.
 
.DESCRIPTION
All comparisons are done in a case-insensitive manner. The rules for matching are as follows:
 
  1. If the reference and difference selectors are equal, then the result is true. This is an exact match.
  2. If the difference selector is a prefix of the reference selector, then the result is true. This is a prefix match.
  3. If the reference selector is "like" the difference selector (as determined by the -like operator), then the result
     is true. This is a wildcard match.
  4. In all other cases, the result is false.
 
.PARAMETER Reference
The selector against which the difference selector is compared.
 
.PARAMETER Difference
The selector to compare against the reference selector. This may contain wildcard characters.
 
.EXAMPLE
Perform an exact match.
 
Compare-DistributionSelector -Reference PythonCore -Difference PythonCore
$true
 
.EXAMPLE
Perform a prefix match.
 
Compare-DistributionSelector -Reference 3.6.3 -Difference 3.6
$true
 
.EXAMPLE
Perform a wildcard match.
 
Compare-DistributionSelector -Reference Continuum -Difference "Cont*"
$true
 
#>

function Compare-DistributionSelector {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $Reference,

        [Parameter( Mandatory )]
        [string] $Difference
    )

    # First check for exact match. This always trumps everything.
    if( $Reference -eq $Difference ) {
        return $true
    }

    # Now do a prefix match. This is likely the most common type of fuzzy match we'll expect. For example, someone may
    # say they want to enable version 3.6, which will match version 3.6.3.
    if( $Reference.StartsWith( $Difference, [System.StringComparison]::OrdinalIgnoreCase ) ) {
        return $true
    }

    # Lastly we support wildcard matching.
    if( $Reference -like $Difference ) {
        return $true
    }

    $false
}
<#
.SYNOPSIS
Gets whether the Python interpreter installed at the given install location is 32- or 64-bit.
 
.PARAMETER InstallPath
Root directory of the Python distribution to check.
 
#>

function Get-DistributionBitness {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $InstallPath
    )

    $python = Get-Python -InstallPath $InstallPath
    if( $python ) {
        & $python -c "import struct; print( 8 * struct.calcsize( 'P' ) )"
    }
}
<#
.SYNOPSIS
Gets the version of the Python interpreter installed at the given install location in major.minor.micro format.
 
.PARAMETER InstallPath
Root directory of the Python distribution to check.
 
#>

function Get-DistributionVersion {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $InstallPath
    )

    $python = Get-Python -InstallPath $InstallPath
    if( $python ) {
        # Older versions of Python don't have support for the tuple field names major, minor, and micro. Instead, we
        # access the version info fields by their respective indexes.
        & $python -c "import sys; print( '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2]) )"
    }
}
<#
.SYNOPSIS
"Normalizes" a path by ensuring it has exactly one trailing slash.
 
.DESCRIPTION
This is used to make directory path comparisons easier in, e.g,. Clear-PythonInstallPath.
 
.PARAMETER Path
The path to normalize.
 
#>

function Get-NormalizedPath {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $Path
    )

    # This is kind of hacky, but it's a way to ensure all the PATH items we care about have a trailing slash for easier
    # install path comparison.
    Join-Path $Path ""
}
<#
.SYNOPSIS
Gets the Python executable installed at the given installation location.
 
.PARAMETER InstallPath
Root directory of the Python distribution to get the executable from.
 
#>

function Get-Python {
    [CmdletBinding()]
    param(
        [Parameter( Mandatory )]
        [string] $InstallPath
    )

    Get-Command (Join-Path $InstallPath "python.exe") -ErrorAction Ignore
}