github.com/jpreese/tflint@v0.19.2-0.20200908152133-b01686250fb6/rules/terraformrules/terraform_comment_syntax.go (about)

     1  package terraformrules
     2  
     3  import (
     4  	"log"
     5  	"strings"
     6  
     7  	"github.com/hashicorp/hcl/v2"
     8  	"github.com/hashicorp/hcl/v2/hclsyntax"
     9  
    10  	"github.com/terraform-linters/tflint/tflint"
    11  )
    12  
    13  // TerraformCommentSyntaxRule checks whether comments use the preferred syntax
    14  type TerraformCommentSyntaxRule struct{}
    15  
    16  // NewTerraformCommentSyntaxRule returns a new rule
    17  func NewTerraformCommentSyntaxRule() *TerraformCommentSyntaxRule {
    18  	return &TerraformCommentSyntaxRule{}
    19  }
    20  
    21  // Name returns the rule name
    22  func (r *TerraformCommentSyntaxRule) Name() string {
    23  	return "terraform_comment_syntax"
    24  }
    25  
    26  // Enabled returns whether the rule is enabled by default
    27  func (r *TerraformCommentSyntaxRule) Enabled() bool {
    28  	return false
    29  }
    30  
    31  // Severity returns the rule severity
    32  func (r *TerraformCommentSyntaxRule) Severity() string {
    33  	return tflint.WARNING
    34  }
    35  
    36  // Link returns the rule reference link
    37  func (r *TerraformCommentSyntaxRule) Link() string {
    38  	return tflint.ReferenceLink(r.Name())
    39  }
    40  
    41  // Check checks whether single line comments is used
    42  func (r *TerraformCommentSyntaxRule) Check(runner *tflint.Runner) error {
    43  	if !runner.TFConfig.Path.IsRoot() {
    44  		// This rule does not evaluate child modules.
    45  		return nil
    46  	}
    47  
    48  	log.Printf("[TRACE] Check `%s` rule for `%s` runner", r.Name(), runner.TFConfigPath())
    49  
    50  	for name, file := range runner.Files() {
    51  		if err := r.checkComments(runner, name, file); err != nil {
    52  			return err
    53  		}
    54  	}
    55  
    56  	return nil
    57  }
    58  
    59  func (r *TerraformCommentSyntaxRule) checkComments(runner *tflint.Runner, filename string, file *hcl.File) error {
    60  	if strings.HasSuffix(filename, ".json") {
    61  		return nil
    62  	}
    63  
    64  	tokens, diags := hclsyntax.LexConfig(file.Bytes, filename, hcl.InitialPos)
    65  	if diags.HasErrors() {
    66  		return diags
    67  	}
    68  
    69  	for _, token := range tokens {
    70  		if token.Type != hclsyntax.TokenComment {
    71  			continue
    72  		}
    73  
    74  		if strings.HasPrefix(string(token.Bytes), "//") {
    75  			runner.EmitIssue(
    76  				r,
    77  				"Single line comments should begin with #",
    78  				token.Range,
    79  			)
    80  		}
    81  	}
    82  
    83  	return nil
    84  }