github.com/wata727/tflint@v0.12.2-0.20191013070026-96dd0d36f385/tflint/annotation.go (about)

     1  package tflint
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  
     7  	"github.com/hashicorp/hcl/v2/hclsyntax"
     8  )
     9  
    10  var annotationPattern = regexp.MustCompile(`tflint-ignore: (\S+)`)
    11  
    12  // Annotation represents comments with special meaning in TFLint
    13  type Annotation struct {
    14  	Content string
    15  	Token   hclsyntax.Token
    16  }
    17  
    18  // Annotations is slice of Annotation
    19  type Annotations []Annotation
    20  
    21  // NewAnnotations find annotations from the passed tokens and return that list.
    22  func NewAnnotations(tokens hclsyntax.Tokens) Annotations {
    23  	ret := Annotations{}
    24  
    25  	for _, token := range tokens {
    26  		if token.Type != hclsyntax.TokenComment {
    27  			continue
    28  		}
    29  
    30  		match := annotationPattern.FindStringSubmatch(string(token.Bytes))
    31  		if len(match) != 2 {
    32  			continue
    33  		}
    34  		ret = append(ret, Annotation{
    35  			Content: match[1],
    36  			Token:   token,
    37  		})
    38  	}
    39  
    40  	return ret
    41  }
    42  
    43  // IsAffected checks if the passed issue is affected with the annotation
    44  func (a *Annotation) IsAffected(issue *Issue) bool {
    45  	if a.Token.Range.Filename != issue.Range.Filename {
    46  		return false
    47  	}
    48  	if a.Content == issue.Rule.Name() || a.Content == "all" {
    49  		if a.Token.Range.Start.Line == issue.Range.Start.Line {
    50  			return true
    51  		}
    52  		if a.Token.Range.Start.Line == issue.Range.Start.Line-1 {
    53  			return true
    54  		}
    55  	}
    56  	return false
    57  }
    58  
    59  // String returns the string representation of the annotation
    60  func (a *Annotation) String() string {
    61  	return fmt.Sprintf("annotation:%s (%s)", a.Content, a.Token.Range.String())
    62  }