-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathinstall.go
317 lines (251 loc) · 9.87 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
package lib
import (
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"github.com/hashicorp/go-version"
)
const (
installFile = "terraform"
versionPrefix = "terraform_"
installPath = ".terraform.versions"
recentFile = "RECENT"
defaultBin = "/usr/local/bin/terraform" //default bin installation dir
tfDarwinArm64StartVersion = "1.0.2"
)
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
/* 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)
// }
/* 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(binPath)
initialize() //initialize path
installLocation = GetInstallLocation() //get installation location - this is where we will put our terraform binary file
goarch := runtime.GOARCH
goos := runtime.GOOS
// Terraform darwin arm64 comes with 1.0.2 and next version
tfver, _ := version.NewVersion(tfversion)
tf102, _ := version.NewVersion(tfDarwinArm64StartVersion)
if goos == "darwin" && goarch == "arm64" && tfver.LessThan(tf102) {
goarch = "amd64"
}
/* check if selected version already downloaded */
installFileVersionPath := ConvertExecutableExt(filepath.Join(installLocation, versionPrefix+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 + "/" + versionPrefix + 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 and return $HOME/bin as install location
func InstallableBinLocation(userBinPath string) string {
usr, errCurr := user.Current()
if errCurr != nil {
log.Fatal(errCurr)
}
binDir := Path(userBinPath) //get path directory from binary path
binPathExist := CheckDirExist(binDir) //the default is /usr/local/bin but users can provide custom bin locations
if binPathExist == true { //if bin path exist - check if we can write to to it
binPathWritable := false //assume bin path is not writable
if runtime.GOOS != "windows" {
binPathWritable = CheckDirWritable(binDir) //check if is writable on ( only works on LINUX)
}
// IF: "/usr/local/bin" or `custom bin path` provided by user is non-writable, (binPathWritable == false), we will attempt to install terraform at the ~/bin location. See ELSE
if binPathWritable == false {
homeBinExist := CheckDirExist(filepath.Join(usr.HomeDir, "bin")) //check to see if ~/bin exist
if homeBinExist { //if ~/bin exist, install at ~/bin/terraform
fmt.Printf("Installing terraform at %s\n", filepath.Join(usr.HomeDir, "bin"))
return filepath.Join(usr.HomeDir, "bin", "terraform")
} else { //if ~/bin directory does not exist, create ~/bin for terraform installation
fmt.Printf("Unable to write to: %s\n", userBinPath)
fmt.Printf("Creating bin directory at: %s\n", filepath.Join(usr.HomeDir, "bin"))
CreateDirIfNotExist(filepath.Join(usr.HomeDir, "bin")) //create ~/bin
fmt.Printf("RUN `export PATH=$PATH:%s` to append bin to $PATH\n", filepath.Join(usr.HomeDir, "bin"))
return filepath.Join(usr.HomeDir, "bin", "terraform")
}
} else { // ELSE: the "/usr/local/bin" or custom path provided by user is writable, we will return installable location
return filepath.Join(userBinPath)
}
}
fmt.Printf("[Error] : Binary path does not exist: %s\n", userBinPath)
fmt.Printf("[Error] : Manually create bin directory at: %s and try again.\n", binDir)
os.Exit(1)
return ""
}