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