-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
58 lines (47 loc) · 1.28 KB
/
main.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
package main
import (
"log"
"os"
"path/filepath"
"slices"
"strings"
"github.com/cockroachdb/errors"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclwrite"
)
func getRefactoringBlocks() []string {
return []string{"moved", "import", "removed"}
}
func main() {
const terraformDir = "./" //TODO: あとで引数で弄れるようにしたい
err := filepath.Walk(terraformDir, func(filePath string, info os.FileInfo, err error) error {
if err != nil {
return errors.Wrap(err, "Error on filepath.Walk")
}
// '.tf' 拡張子でなければスキップ
if !strings.HasSuffix(info.Name(), ".tf") {
return nil
}
src, err := os.ReadFile(filePath)
if err != nil {
return errors.Wrap(err, "Error on os.ReadFile")
}
file, diags := hclwrite.ParseConfig(src, filePath, hcl.InitialPos)
if diags.HasErrors() {
return errors.Wrap(diags, "Error on hclwrite.ParseConfig")
}
body := file.Body()
for _, v := range body.Blocks() {
if slices.Contains(getRefactoringBlocks(), v.Type()) {
body.RemoveBlock(v)
}
}
if err = os.WriteFile(filePath, file.Bytes(), info.Mode()); err != nil {
return errors.Wrap(err, "Error on os.WriteFile")
}
return nil
})
if err != nil {
log.Fatalf("Error walking through Terraform directory: %+v\n", err)
}
}