github.com/coveo/gotemplate@v2.7.7+incompatible/utils/terraform.go (about)

     1  package utils
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"path/filepath"
     7  	"strings"
     8  
     9  	"github.com/coveo/gotemplate/errors"
    10  )
    11  
    12  // IsTerraformFile check if the file extension matches on of the terraform file extension
    13  func IsTerraformFile(file string) bool {
    14  	switch filepath.Ext(file) {
    15  	case ".tf", ".tf.json", ".tfvars":
    16  		return true
    17  	default:
    18  		return false
    19  	}
    20  }
    21  
    22  // TerraformFormat applies terraform fmt on
    23  func TerraformFormat(files ...string) error {
    24  	if _, err := exec.LookPath("terraform"); err != nil {
    25  		return nil
    26  	}
    27  
    28  	tfFolders := make(map[string]bool)
    29  	for _, file := range files {
    30  		if IsTerraformFile(file) {
    31  			tfFolders[filepath.Dir(file)] = true
    32  		}
    33  	}
    34  
    35  	var errs errors.Array
    36  	for folder := range tfFolders {
    37  		cmd := exec.Command("terraform", "fmt")
    38  		cmd.Dir = folder
    39  		if output, err := cmd.CombinedOutput(); err != nil {
    40  			errs = append(errs, fmt.Errorf("%v: %s", err, strings.TrimSpace(string(output))))
    41  			continue
    42  		}
    43  
    44  		// Sometimes, terraform fmt needs to be executed twice to format its content properly...
    45  		cmd = exec.Command("terraform", "fmt")
    46  		cmd.Dir = folder
    47  		errors.Must(cmd.Run())
    48  	}
    49  	if len(errs) == 0 {
    50  		return nil
    51  	}
    52  	return errs
    53  }