github.com/terraform-linters/tflint@v0.51.2-0.20240520175844-3750771571b6/plugin/stub-generator/sources/testing/rules/terraform_autofix_comment.go (about) 1 package rules 2 3 import ( 4 "runtime" 5 "strings" 6 7 "github.com/hashicorp/hcl/v2" 8 "github.com/hashicorp/hcl/v2/hclsyntax" 9 "github.com/terraform-linters/tflint-plugin-sdk/tflint" 10 ) 11 12 // TerraformAutofixComment checks whether ... 13 type TerraformAutofixComment struct { 14 tflint.DefaultRule 15 } 16 17 // NewTerraformAutofixCommentRule returns a new rule 18 func NewTerraformAutofixCommentRule() *TerraformAutofixComment { 19 return &TerraformAutofixComment{} 20 } 21 22 // Name returns the rule name 23 func (r *TerraformAutofixComment) Name() string { 24 return "terraform_autofix_comment" 25 } 26 27 // Enabled returns whether the rule is enabled by default 28 func (r *TerraformAutofixComment) Enabled() bool { 29 return true 30 } 31 32 // Severity returns the rule severity 33 func (r *TerraformAutofixComment) Severity() tflint.Severity { 34 return tflint.ERROR 35 } 36 37 // Link returns the rule reference link 38 func (r *TerraformAutofixComment) Link() string { 39 return "" 40 } 41 42 // Check checks whether ... 43 func (r *TerraformAutofixComment) Check(runner tflint.Runner) error { 44 files, err := runner.GetFiles() 45 if err != nil { 46 return err 47 } 48 49 for name, file := range files { 50 if strings.HasSuffix(name, ".tf.json") { 51 continue 52 } 53 54 tokens, diags := hclsyntax.LexConfig(file.Bytes, name, hcl.InitialPos) 55 if diags.HasErrors() { 56 return diags 57 } 58 59 for _, token := range tokens { 60 if token.Type != hclsyntax.TokenComment { 61 continue 62 } 63 64 if string(token.Bytes) == "// autofixed"+newLine() { 65 if err := runner.EmitIssueWithFix( 66 r, 67 `Use "# autofixed" instead of "// autofixed"`, 68 token.Range, 69 func(f tflint.Fixer) error { 70 return f.ReplaceText( 71 f.RangeTo("// autofixed", name, token.Range.Start), 72 "# autofixed", 73 ) 74 }, 75 ); err != nil { 76 return err 77 } 78 } 79 } 80 } 81 82 return nil 83 } 84 85 func newLine() string { 86 if runtime.GOOS == "windows" { 87 return "\r\n" 88 } 89 return "\n" 90 }