Created
May 12, 2023 04:03
-
-
Save teru01/ea921928a550afba620353e1e6d2f08a to your computer and use it in GitHub Desktop.
tflintの結果を使ってunused data resourceを削除するスクリプト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// tflint --recursive --config $(pwd)/.tflint.hcl -f json で出力した結果を使う | |
package main | |
import ( | |
"bufio" | |
"encoding/json" | |
"log" | |
"os" | |
"path/filepath" | |
"strings" | |
) | |
type Result struct { | |
Issues []Issue | |
Errors []interface{} | |
} | |
type Issue struct { | |
Rule Rule | |
Message string | |
Range Range | |
} | |
type Range struct { | |
Filename string | |
Start Location | |
End Location | |
} | |
type Location struct { | |
Line int | |
Column int | |
} | |
type Rule struct { | |
Name string | |
} | |
func main() { | |
basedir := "../" | |
b, err := os.ReadFile(os.Args[1]) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
var result Result | |
if err := json.Unmarshal(b, &result); err != nil { | |
log.Fatalln(err) | |
} | |
for i := 0; i < len(result.Issues)/2; i++ { | |
result.Issues[i], result.Issues[len(result.Issues)-i-1] = result.Issues[len(result.Issues)-i-1], result.Issues[i] | |
} | |
for _, iss := range result.Issues { | |
if strings.Contains(iss.Message, "is declared but not used") && strings.Contains(iss.Message, "data") { | |
fname := iss.Range.Filename | |
start := iss.Range.Start.Line | |
f, err := os.Open(filepath.Join(basedir, fname)) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
lineNum := 0 | |
scanner := bufio.NewScanner(f) | |
indent := 0 | |
unused := false | |
var fbuf []string | |
for scanner.Scan() { | |
if err := scanner.Err(); err != nil { | |
log.Fatal(err) | |
} | |
lineNum++ | |
line := scanner.Text() | |
if unused && strings.Contains(line, "{") { | |
indent++ | |
} | |
if lineNum == start { | |
unused = true | |
} | |
if !unused { | |
fbuf = append(fbuf, line) | |
} | |
if unused && strings.Contains(line, "}") { | |
if indent == 0 { | |
unused = false | |
} else { | |
indent-- | |
} | |
} | |
} | |
if err := f.Close(); err != nil { | |
log.Fatal(err) | |
} | |
data := []byte(strings.Join(fbuf, "\n") + "\n") | |
if err := os.WriteFile(filepath.Join(basedir, fname), data, 0644); err != nil { | |
log.Fatal(err) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment