This repository has been archived by the owner on May 15, 2023. It is now read-only.
forked from warrensbox/terraform-switcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.go
332 lines (265 loc) · 9.96 KB
/
install.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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
package lib
import (
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
)
const (
installFile = "terraform"
installVersion = "terraform_"
installPath = ".terraform.versions"
recentFile = "RECENT"
defaultBin = "/usr/local/bin/terraform" //default bin installation dir
)
var (
installLocation = "/tmp"
)
// initialize : removes existing symlink to terraform binary// I Don't think this is needed
func initialize() {
/* Step 1 */
/* initilize default binary path for terraform */
/* assumes that terraform is installed here */
/* we will find the terraform path instalation later and replace this variable with the correct installed bin path */
installedBinPath := "/usr/local/bin/terraform"
/* find terraform binary location if terraform is already installed*/
cmd := NewCommand("terraform")
next := cmd.Find()
/* overrride installation default binary path if terraform is already installed */
/* find the last bin path */
for path := next(); len(path) > 0; path = next() {
installedBinPath = path
}
/* check if current symlink to terraform binary exist */
symlinkExist := CheckSymlink(installedBinPath)
/* remove current symlink if exist*/
if symlinkExist {
RemoveSymlink(installedBinPath)
}
}
// getInstallLocation : get location where the terraform binary will be installed,
// will create a directory in the home location if it does not exist
func getInstallLocation() string {
/* get current user */
usr, errCurr := user.Current()
if errCurr != nil {
log.Fatal(errCurr)
}
userCommon := usr.HomeDir
/* For snapcraft users, SNAP_USER_COMMON environment variable is set by default.
* tfswitch does not have permission to save to $HOME/.terraform.versions for snapcraft users
* tfswitch will save binaries into $SNAP_USER_COMMON/.terraform.versions */
if os.Getenv("SNAP_USER_COMMON") != "" {
userCommon = os.Getenv("SNAP_USER_COMMON")
}
/* set installation location */
installLocation = filepath.Join(userCommon, installPath)
/* Create local installation directory if it does not exist */
CreateDirIfNotExist(installLocation)
return installLocation
}
//Install : Install the provided version in the argument
func Install(tfversion string, binPath string, mirrorURL string) {
if !ValidVersionFormat(tfversion) {
fmt.Printf("The provided terraform version format does not exist - %s. Try `tfswitch -l` to see all available versions.\n", tfversion)
os.Exit(1)
}
pathDir := Path(binPath) //get path directory from binary path
//binDirExist := CheckDirExist(pathDir) //check bin path exist
/* Check to see if user has permission to the default bin location which is "/usr/local/bin/terraform"
* If user does not have permission to default bin location, proceed to create $HOME/bin and install the tfswitch there
* Inform user that they dont have permission to default location, therefore tfswitch was installed in $HOME/bin
* Tell users to add $HOME/bin to their path
*/
binPath = InstallableBinLocation(pathDir)
initialize() //initialize path
installLocation = getInstallLocation() //get installation location - this is where we will put our terraform binary file
goarch := runtime.GOARCH
goos := runtime.GOOS
// TODO: Workaround for macos arm64 since terraform doesn't have a binary for it yet
if goos == "darwin" && goarch == "arm64" {
goarch = "amd64"
}
/* check if selected version already downloaded */
installFileVersionPath := ConvertExecutableExt(filepath.Join(installLocation, installVersion+tfversion))
fileExist := CheckFileExist(installFileVersionPath)
/* if selected version already exist, */
if fileExist {
/* remove current symlink if exist*/
symlinkExist := CheckSymlink(binPath)
if symlinkExist {
RemoveSymlink(binPath)
}
/* set symlink to desired version */
CreateSymlink(installFileVersionPath, binPath)
fmt.Printf("Switched terraform to version %q \n", tfversion)
AddRecent(tfversion) //add to recent file for faster lookup
os.Exit(0)
}
//if does not have slash - append slash
hasSlash := strings.HasSuffix(mirrorURL, "/")
if !hasSlash {
mirrorURL = fmt.Sprintf("%s/", mirrorURL)
}
/* if selected version already exist, */
/* proceed to download it from the hashicorp release page */
url := mirrorURL + tfversion + "/" + installVersion + tfversion + "_" + goos + "_" + goarch + ".zip"
zipFile, errDownload := DownloadFromURL(installLocation, url)
/* If unable to download file from url, exit(1) immediately */
if errDownload != nil {
fmt.Println(errDownload)
os.Exit(1)
}
/* unzip the downloaded zipfile */
_, errUnzip := Unzip(zipFile, installLocation)
if errUnzip != nil {
fmt.Println("[Error] : Unable to unzip downloaded zip file")
log.Fatal(errUnzip)
os.Exit(1)
}
/* rename unzipped file to terraform version name - terraform_x.x.x */
installFilePath := ConvertExecutableExt(filepath.Join(installLocation, installFile))
RenameFile(installFilePath, installFileVersionPath)
/* remove zipped file to clear clutter */
RemoveFiles(zipFile)
/* remove current symlink if exist*/
symlinkExist := CheckSymlink(binPath)
if symlinkExist {
RemoveSymlink(binPath)
}
/* set symlink to desired version */
CreateSymlink(installFileVersionPath, binPath)
fmt.Printf("Switched terraform to version %q \n", tfversion)
AddRecent(tfversion) //add to recent file for faster lookup
os.Exit(0)
}
// AddRecent : add to recent file
func AddRecent(requestedVersion string) {
installLocation = getInstallLocation() //get installation location - this is where we will put our terraform binary file
versionFile := filepath.Join(installLocation, recentFile)
fileExist := CheckFileExist(versionFile)
if fileExist {
lines, errRead := ReadLines(versionFile)
if errRead != nil {
fmt.Printf("[Error] : %s\n", errRead)
return
}
for _, line := range lines {
if !ValidVersionFormat(line) {
fmt.Println("File dirty. Recreating cache file.")
RemoveFiles(versionFile)
CreateRecentFile(requestedVersion)
return
}
}
versionExist := VersionExist(requestedVersion, lines)
if !versionExist {
if len(lines) >= 3 {
_, lines = lines[len(lines)-1], lines[:len(lines)-1]
lines = append([]string{requestedVersion}, lines...)
WriteLines(lines, versionFile)
} else {
lines = append([]string{requestedVersion}, lines...)
WriteLines(lines, versionFile)
}
}
} else {
CreateRecentFile(requestedVersion)
}
}
// GetRecentVersions : get recent version from file
func GetRecentVersions() ([]string, error) {
installLocation = getInstallLocation() //get installation location - this is where we will put our terraform binary file
versionFile := filepath.Join(installLocation, recentFile)
fileExist := CheckFileExist(versionFile)
if fileExist {
lines, errRead := ReadLines(versionFile)
outputRecent := []string{}
if errRead != nil {
fmt.Printf("Error: %s\n", errRead)
return nil, errRead
}
for _, line := range lines {
/* checks if versions in the recent file are valid.
If any version is invalid, it will be consider dirty
and the recent file will be removed
*/
if !ValidVersionFormat(line) {
RemoveFiles(versionFile)
return nil, errRead
}
/* output can be confusing since it displays the 3 most recent used terraform version
append the string *recent to the output to make it more user friendly
*/
outputRecent = append(outputRecent, fmt.Sprintf("%s *recent", line))
}
return outputRecent, nil
}
return nil, nil
}
//CreateRecentFile : create a recent file
func CreateRecentFile(requestedVersion string) {
installLocation = getInstallLocation() //get installation location - this is where we will put our terraform binary file
WriteLines([]string{requestedVersion}, filepath.Join(installLocation, recentFile))
}
//ConvertExecutableExt : convert excutable with local OS extension
func ConvertExecutableExt(fpath string) string {
switch runtime.GOOS {
case "windows":
if filepath.Ext(fpath) == ".exe" {
return fpath
}
return fpath + ".exe"
default:
return fpath
}
}
//InstallableBinLocation : Checks if terraform is installable in the location provided by the user.
//If not, create $HOME/bin. Ask users to add $HOME/bin to $PATH
//Return $HOME/bin as install location
func InstallableBinLocation(userBin string) string {
usr, errCurr := user.Current()
if errCurr != nil {
log.Fatal(errCurr)
}
/* Setup for SNAPCRAFT Users */
SNAP := os.Getenv("SNAP_REAL_HOME")
if SNAP != "" { //if SNAP_USER_COMMON env is set, install
snapHomePath := filepath.Join(SNAP, "bin")
fmt.Println(snapHomePath)
CreateDirIfNotExist(snapHomePath)
fmt.Printf("Installing terraform at %s\n", snapHomePath)
fmt.Printf("RUN `export PATH=$PATH:%s` to append bin to $PATH\n", snapHomePath)
return filepath.Join(snapHomePath, "terraform")
}
existDefaultBin := CheckDirExist(userBin) //the default is /usr/local/bin but users can provide custom bin locations
if existDefaultBin { //if exist - now see if we can write to to it
writableToDefault := false
if runtime.GOOS != "windows" {
writableToDefault = CheckDirWritable(userBin) //check if is writable on ( only works on LINUX)
}
if !writableToDefault {
exisHomeBin := CheckDirExist(filepath.Join(usr.HomeDir, "bin"))
if exisHomeBin {
fmt.Printf("Installing terraform at %s\n", filepath.Join(usr.HomeDir, "bin"))
return filepath.Join(usr.HomeDir, "bin", "terraform")
}
PrintCreateDirStmt(userBin, filepath.Join(usr.HomeDir, "bin"))
CreateDirIfNotExist(filepath.Join(usr.HomeDir, "bin"))
return filepath.Join(usr.HomeDir, "bin", "terraform")
}
return filepath.Join(userBin, "terraform")
}
fmt.Printf("[Error] : Binary path does not exist: %s\n", userBin)
fmt.Printf("[Error] : Manually create bin directory at: %s and try again.\n", userBin)
os.Exit(1)
return ""
}
func PrintCreateDirStmt(unableDir string, writable string) {
fmt.Printf("Unable to write to: %s\n", unableDir)
fmt.Printf("Creating bin directory at: %s\n", writable)
fmt.Printf("RUN `export PATH=$PATH:%s` to append bin to $PATH\n", writable)
}