github.com/songshiyun/revive@v1.1.5-0.20220323112655-f8433a19b3c5/rule/file-header.go (about)

     1  package rule
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  
     7  	"github.com/songshiyun/revive/lint"
     8  )
     9  
    10  // FileHeaderRule lints given else constructs.
    11  type FileHeaderRule struct {
    12  	header string
    13  }
    14  
    15  var (
    16  	multiRegexp  = regexp.MustCompile("^/\\*")
    17  	singleRegexp = regexp.MustCompile("^//")
    18  )
    19  
    20  // Apply applies the rule to given file.
    21  func (r *FileHeaderRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
    22  	if r.header == "" {
    23  		checkNumberOfArguments(1, arguments, r.Name())
    24  		var ok bool
    25  		r.header, ok = arguments[0].(string)
    26  		if !ok {
    27  			panic(fmt.Sprintf("invalid argument for \"file-header\" rule: first argument should be a string, got %T", arguments[0]))
    28  		}
    29  	}
    30  
    31  	failure := []lint.Failure{
    32  		{
    33  			Node:       file.AST,
    34  			Confidence: 1,
    35  			Failure:    "the file doesn't have an appropriate header",
    36  		},
    37  	}
    38  
    39  	if len(file.AST.Comments) == 0 {
    40  		return failure
    41  	}
    42  
    43  	g := file.AST.Comments[0]
    44  	if g == nil {
    45  		return failure
    46  	}
    47  	comment := ""
    48  	for _, c := range g.List {
    49  		text := c.Text
    50  		if multiRegexp.MatchString(text) {
    51  			text = text[2 : len(text)-2]
    52  		} else if singleRegexp.MatchString(text) {
    53  			text = text[2:]
    54  		}
    55  		comment += text
    56  	}
    57  
    58  	regex, err := regexp.Compile(r.header)
    59  	if err != nil {
    60  		panic(err.Error())
    61  	}
    62  
    63  	if !regex.MatchString(comment) {
    64  		return failure
    65  	}
    66  	return nil
    67  }
    68  
    69  // Name returns the rule name.
    70  func (r *FileHeaderRule) Name() string {
    71  	return "file-header"
    72  }