/
terraform.go
53 lines (46 loc) · 1.14 KB
/
terraform.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
package utils
import (
"fmt"
"os/exec"
"path/filepath"
"strings"
"github.com/coveo/gotemplate/errors"
)
// IsTerraformFile check if the file extension matches on of the terraform file extension
func IsTerraformFile(file string) bool {
switch filepath.Ext(file) {
case ".tf", ".tf.json", ".tfvars":
return true
default:
return false
}
}
// TerraformFormat applies terraform fmt on
func TerraformFormat(files ...string) error {
if _, err := exec.LookPath("terraform"); err != nil {
return nil
}
tfFolders := make(map[string]bool)
for _, file := range files {
if IsTerraformFile(file) {
tfFolders[filepath.Dir(file)] = true
}
}
var errs errors.Array
for folder := range tfFolders {
cmd := exec.Command("terraform", "fmt")
cmd.Dir = folder
if output, err := cmd.CombinedOutput(); err != nil {
errs = append(errs, fmt.Errorf("%v: %s", err, strings.TrimSpace(string(output))))
continue
}
// Sometimes, terraform fmt needs to be executed twice to format its content properly...
cmd = exec.Command("terraform", "fmt")
cmd.Dir = folder
errors.Must(cmd.Run())
}
if len(errs) == 0 {
return nil
}
return errs
}