Private/Resolve-Version.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Function Resolve-Version {
    [cmdletbinding()]
    Param(
        $Config
    )

    # order of precedence for desired version:
    # .terraformversion > $env:terraformversion > user profile > default to latest

    $ErrorActionPreference = "stop"

    $Version = [pscustomobject]@{
        DesiredVersion = $null
        Source         = $null
    }

    # check user profile
    if ($Config.DesiredVersion) {
        if ($Config.AvailableVersions -contains $Config.DesiredVersion) {
            $Version.DesiredVersion = $Config.DesiredVersion
            $Version.Source = "profile"
        }
        else {
            throw ("unable to find specified terraform version: source={0}, version={1}" -f "profile", $Config.DesiredVersion)
        }
    }
    
    # check .terraformversion file
    if (Test-Path -Path ".terraformversion") {
        $VersionFile = (Get-Content -Path ".terraformversion" -Raw).Trim()
        if ($Config.AvailableVersions -contains $VersionFile) {
            $Version.DesiredVersion = $VersionFile
            $Version.Source = "file"
        }
        else {
            throw ("unable to find specified terraform version: source={0}, version={1}" -f "file", $VersionFile)
        }
        
    }

    # check env variable
    if ($env:terraformversion) {
        if ($Config.AvailableVersions -contains $env:terraformversion) {
            $Version.DesiredVersion = $env:terraformversion
            $Version.Source = 'environment'
        }
        else {
            throw ("unable to find specified terraform version: source={0}, version={1}" -f "environment", $env:terraformversion)
        }
    }
    
    # default to latest
    if ($null -eq $Version.DesiredVersion) {
        $Version.DesiredVersion = [version[]]$Config.AvailableVersions | Sort-Object -Descending | Select-Object -First 1
        $Version.Source = "latest"
    }

    Return $Version

}