-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathparameters.go
183 lines (162 loc) · 7.13 KB
/
parameters.go
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package param_parsing
import (
"fmt"
"path/filepath"
"runtime"
"strings"
"github.com/gookit/slog"
"github.com/pborman/getopt"
"github.com/warrensbox/terraform-switcher/lib"
)
type Params struct {
ChDirPath string
CustomBinaryPath string
DefaultVersion string
DryRun bool
HelpFlag bool
InstallPath string
LatestFlag bool
LatestPre string
LatestStable string
ListAllFlag bool
LogLevel string
MirrorURL string
ShowLatestFlag bool
ShowLatestPre string
ShowLatestStable string
Product string
ProductEntity lib.Product
TomlDir string
Version string
VersionFlag bool
}
var logger *slog.Logger
func GetParameters() Params {
var params Params
params = initParams(params)
params = populateParams(params)
return params
}
func populateParams(params Params) Params {
var productIds []string
var defaultMirrors []string
for _, product := range lib.GetAllProducts() {
productIds = append(productIds, product.GetId())
defaultMirrors = append(defaultMirrors, fmt.Sprintf("%s: %s", product.GetName(), product.GetDefaultMirrorUrl()))
}
getopt.StringVarLong(¶ms.ChDirPath, "chdir", 'c', "Switch to a different working directory before executing the given command. Ex: tfswitch --chdir terraform_project will run tfswitch in the terraform_project directory")
getopt.StringVarLong(¶ms.CustomBinaryPath, "bin", 'b', "Custom binary path. Ex: tfswitch -b "+lib.ConvertExecutableExt("/Users/username/bin/terraform"))
getopt.StringVarLong(¶ms.DefaultVersion, "default", 'd', "Default to this version in case no other versions could be detected. Ex: tfswitch --default 1.2.4")
getopt.BoolVarLong(¶ms.DryRun, "dry-run", 'r', "Only show what tfswitch would do. Don't download anything.")
getopt.BoolVarLong(¶ms.HelpFlag, "help", 'h', "Displays help message")
getopt.StringVarLong(¶ms.InstallPath, "install", 'i', "Custom install path. Ex: tfswitch -i /Users/username. The binaries will be in the sub installDir directory e.g. /Users/username/"+lib.InstallDir)
getopt.BoolVarLong(¶ms.LatestFlag, "latest", 'u', "Get latest stable version")
getopt.StringVarLong(¶ms.LatestPre, "latest-pre", 'p', "Latest pre-release implicit version. Ex: tfswitch --latest-pre 0.13 downloads 0.13.0-rc1 (latest)")
getopt.StringVarLong(¶ms.LatestStable, "latest-stable", 's', "Latest implicit version based on a constraint. Ex: tfswitch --latest-stable 0.13.0 downloads 0.13.7 and 0.13 downloads 0.15.5 (latest)")
getopt.BoolVarLong(¶ms.ListAllFlag, "list-all", 'l', "List all versions of terraform - including beta and rc")
getopt.StringVarLong(¶ms.LogLevel, "log-level", 'g', "Set loglevel for tfswitch. One of (ERROR, INFO, NOTICE, DEBUG, TRACE)")
getopt.StringVarLong(¶ms.MirrorURL, "mirror", 'm', "install from a remote API other than the default. Default (based on product):\n"+strings.Join(defaultMirrors, "\n"))
getopt.BoolVarLong(¶ms.ShowLatestFlag, "show-latest", 'U', "Show latest stable version")
getopt.StringVarLong(¶ms.ShowLatestPre, "show-latest-pre", 'P', "Show latest pre-release implicit version. Ex: tfswitch --show-latest-pre 0.13 prints 0.13.0-rc1 (latest)")
getopt.StringVarLong(¶ms.ShowLatestStable, "show-latest-stable", 'S', "Show latest implicit version. Ex: tfswitch --show-latest-stable 0.13 prints 0.13.7 (latest)")
getopt.StringVarLong(¶ms.Product, "product", 't', fmt.Sprintf("Specifies which product to use. Ex: `tfswitch --product opentofu` will install OpenTofu. Options: (%s). Default: %s", strings.Join(productIds, ", "), lib.DefaultProductId))
getopt.BoolVarLong(¶ms.VersionFlag, "version", 'v', "Displays the version of tfswitch")
// Parse the command line parameters to fetch stuff like chdir
getopt.Parse()
if !params.VersionFlag {
oldLogLevel := params.LogLevel
logger = lib.InitLogger(params.LogLevel)
var err error
// Read configuration files
// TOML from Homedir
if tomlFileExists(params) {
params, err = getParamsTOML(params)
if err != nil {
logger.Fatalf("Failed to obtain settings from TOML config in home directory: %v", err)
}
}
// First pass to obtain environment variables to override product
params = GetParamsFromEnvironment(params)
// Set defaults based on product
// This must be performed after TOML file, to obtain product.
// But the mirror URL, if set to default product URL,
// is used by some of the version getter methods, to
// obtain list of versions.
product := lib.GetProductById(params.Product)
if product == nil {
logger.Fatalf("Invalid \"product\" configuration value: %q", params.Product)
} else { // Use else as there is a warning that params maybe nil, as it does not see Fatalf as a break condition
if params.MirrorURL == "" {
params.MirrorURL = product.GetDefaultMirrorUrl()
}
// Set default bin directory, if not configured
if params.CustomBinaryPath == "" {
if runtime.GOOS == "windows" {
params.CustomBinaryPath = filepath.Join(lib.GetHomeDirectory(), "bin", lib.ConvertExecutableExt(product.GetExecutableName()))
} else {
params.CustomBinaryPath = filepath.Join("/usr/local/bin", product.GetExecutableName())
}
}
params.ProductEntity = product
}
if tfSwitchFileExists(params) {
params, err = GetParamsFromTfSwitch(params)
if err != nil {
logger.Fatalf("Failed to obtain settings from \".tfswitch\" file: %v", err)
}
}
if terraformVersionFileExists(params) {
params, err = GetParamsFromTerraformVersion(params)
if err != nil {
logger.Fatalf("Failed to obtain settings from \".terraform-version\" file: %v", err)
}
}
if isTerraformModule(params) {
params, err = GetVersionFromVersionsTF(params)
if err != nil {
logger.Fatalf("Failed to obtain settings from Terraform module: %v", err)
}
}
if terraGruntFileExists(params) {
params, err = GetVersionFromTerragrunt(params)
if err != nil {
logger.Fatalf("Failed to obtain settings from Terragrunt configuration: %v", err)
}
}
params = GetParamsFromEnvironment(params)
// Logger config was changed by the config files. Reinitialise.
if params.LogLevel != oldLogLevel {
logger = lib.InitLogger(params.LogLevel)
}
}
// Parse again to overwrite anything that might by defined on the cli AND in any config file (CLI always wins)
getopt.Parse()
args := getopt.Args()
if len(args) == 1 {
/* version provided on command line as arg */
params.Version = args[0]
}
return params
}
func initParams(params Params) Params {
params.ChDirPath = lib.GetCurrentDirectory()
params.CustomBinaryPath = ""
params.DefaultVersion = lib.DefaultLatest
params.DryRun = false
params.HelpFlag = false
params.InstallPath = lib.GetHomeDirectory()
params.LatestFlag = false
params.LatestPre = lib.DefaultLatest
params.LatestStable = lib.DefaultLatest
params.ListAllFlag = false
params.LogLevel = "INFO"
params.MirrorURL = ""
params.ShowLatestFlag = false
params.ShowLatestPre = lib.DefaultLatest
params.ShowLatestStable = lib.DefaultLatest
params.TomlDir = lib.GetHomeDirectory()
params.Version = lib.DefaultLatest
params.Product = lib.DefaultProductId
params.VersionFlag = false
return params
}