-
Notifications
You must be signed in to change notification settings - Fork 2
/
local.go
288 lines (227 loc) · 6.75 KB
/
local.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
package terraform
import (
"bufio"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"os/user"
"path/filepath"
"runtime"
"strings"
"syscall"
"github.com/hazelops/ize/internal/config"
"github.com/sirupsen/logrus"
"time"
"github.com/hashicorp/go-version"
"github.com/hazelops/ize/pkg/term"
"github.com/hazelops/ize/pkg/terminal"
tfswitcher "github.com/psihachina/terraform-switcher/lib"
)
const (
versionPrefix = "terraform_"
defaultMirror = "https://releases.hashicorp.com/terraform"
)
type local struct {
version string
command []string
env []string
output io.Writer
tfpath string
project *config.Project
state string
}
func NewLocalTerraform(state string, command []string, env []string, out io.Writer, project *config.Project) *local {
if len(project.Terraform[state].Version) == 0 {
project.Terraform[state].Version = project.TerraformVersion
}
return &local{
state: state,
version: project.Terraform[state].Version,
command: command,
env: env,
output: out,
project: project,
}
}
func (l *local) Run() error {
if len(l.project.EnvDir) == 0 {
l.project.EnvDir = "."
}
stateDir := filepath.Join(l.project.EnvDir, l.state)
if l.state == "infra" {
stateDir = l.project.EnvDir
}
cmd := exec.Command(l.tfpath, l.command...)
cmd.Dir = stateDir
err := term.New(term.WithDir(l.project.EnvDir), term.WithStdin(os.Stdin)).InteractiveRun(cmd)
if err != nil {
return err
}
return nil
}
func (l *local) Prepare() error {
var (
mirror = defaultMirror
path = ""
)
path, err := installVersion(l.version, &mirror)
if err != nil {
return err
}
l.tfpath = path
return nil
}
func (l *local) NewCmd(cmd []string) {
l.command = cmd
}
func (l *local) SetOut(out io.Writer) {
l.output = out
}
func printOutput(r io.Reader, w io.Writer) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
w.Write([]byte(scanner.Text() + "\n"))
}
}
func runCommand(cmd *exec.Cmd, out io.Writer) (stdout, stderr string, err error) {
signal.Ignore(os.Interrupt)
defer signal.Reset(os.Interrupt)
outReader, err := cmd.StdoutPipe()
if err != nil {
return
}
errReader, err := cmd.StderrPipe()
if err != nil {
return
}
if err = cmd.Start(); err != nil {
return
}
go printOutput(outReader, out)
go printOutput(errReader, out)
err = cmd.Wait()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
if s, ok := exitErr.Sys().(syscall.WaitStatus); ok {
err = fmt.Errorf("exit status: %d", s.ExitStatus())
}
}
}
return
}
func (l *local) RunUI(ui terminal.UI) error {
sg := ui.StepGroup()
defer sg.Wait()
s := sg.Add("[%s][%s] Running terraform v%s...", l.project.Env, l.state, l.version)
defer func() { s.Abort(); time.Sleep(time.Millisecond * 100) }()
stdout := s.TermOutput()
if l.output != nil {
stdout = l.output
}
if len(l.project.EnvDir) == 0 {
l.project.EnvDir = "."
}
stateDir := filepath.Join(l.project.EnvDir, l.state)
if l.state == "infra" {
stateDir = l.project.EnvDir
}
cmd := exec.Command(l.tfpath, l.command...)
cmd.Dir = stateDir
_, _, err := runCommand(cmd, stdout)
if err != nil {
return err
}
s.Done()
return nil
}
func getInstallLocation(installPath string) 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 */
tfswitcher.CreateDirIfNotExist(installLocation)
return installLocation
}
func installVersion(version string, mirrorURL *string) (string, error) {
var (
installFileVersionPath string
)
if tfswitcher.ValidVersionFormat(version) {
requestedVersion := version
//check to see if the requested version has been downloaded before
installLocation := getInstallLocation(".ize/versions/terraform/")
installFileVersionPath = tfswitcher.ConvertExecutableExt(filepath.Join(installLocation, versionPrefix+requestedVersion))
recentDownloadFile := tfswitcher.CheckFileExist(installFileVersionPath)
if recentDownloadFile {
return installFileVersionPath, nil
}
//if the requested version had not been downloaded before
listAll := true //set list all true - all versions including beta and rc will be displayed
tflist, _ := tfswitcher.GetTFList(*mirrorURL, listAll) //get list of versions
exist := tfswitcher.VersionExist(requestedVersion, tflist) //check if version exist before downloading it
if exist {
err := Install(requestedVersion, *mirrorURL)
if err != nil {
return "", err
}
} else {
return "", fmt.Errorf("provided terraform version does not exist")
}
} else {
tfswitcher.PrintInvalidTFVersion()
return "", fmt.Errorf("argument must be a valid terraform version")
}
return installFileVersionPath, nil
}
func Install(tfversion string, mirrorURL string) error {
installLocation := getInstallLocation(".ize/versions/terraform/") //get installation location - this is where we will put our terraform binary file
goarch := runtime.GOARCH
goos := runtime.GOOS
// Terraform darwin arm64 comes with version 1.0.2 and above
tfver, _ := version.NewVersion(tfversion)
tf102, _ := version.NewVersion("1.0.2")
if goos == "darwin" && goarch == "arm64" && tfver.LessThan(tf102) {
goarch = "amd64"
}
/* check if selected version has already been downloaded */
installFileVersionPath := tfswitcher.ConvertExecutableExt(filepath.Join(installLocation, versionPrefix+tfversion))
fileExist := tfswitcher.CheckFileExist(installFileVersionPath)
/* if selected version already exists */
if fileExist {
return nil
}
// if it does not have a slash - append it
hasSlash := strings.HasSuffix(mirrorURL, "/")
if !hasSlash {
mirrorURL = fmt.Sprintf("%s/", mirrorURL)
}
logrus.Debugf("downloading terraform version %s to: %s", tfversion, installLocation)
/* if selected version already exist, */
/* proceed to download it from the hashicorp release page */
url := mirrorURL + tfversion + "/" + versionPrefix + tfversion + "_" + goos + "_" + goarch + ".zip"
zipFile, errDownload := tfswitcher.DownloadFromURL(installLocation, url)
/* If unable to download file from url, exit(1) immediately */
if errDownload != nil {
return errDownload
}
/* unzip the downloaded zipfile */
_, errUnzip := tfswitcher.Unzip(zipFile, installLocation)
if errUnzip != nil {
fmt.Println("[Error] : Unable to unzip downloaded zip file")
return errUnzip
}
/* rename unzipped file to terraform version name - terraform_x.x.x */
installFilePath := tfswitcher.ConvertExecutableExt(filepath.Join(installLocation, "terraform"))
tfswitcher.RenameFile(installFilePath, installFileVersionPath)
/* remove zipped file to clear clutter */
tfswitcher.RemoveFiles(zipFile)
return nil
}