1
0
mirror of https://github.com/mgechev/revive.git synced 2024-12-12 10:44:59 +02:00
revive/rule/file-header.go

73 lines
1.4 KiB
Go
Raw Normal View History

2018-02-05 00:51:19 +02:00
package rule
import (
"fmt"
2018-02-05 00:51:19 +02:00
"regexp"
"github.com/mgechev/revive/lint"
)
// FileHeaderRule lints given else constructs.
2021-10-17 20:34:48 +02:00
type FileHeaderRule struct {
header string
}
2018-02-05 00:51:19 +02:00
2019-11-28 05:14:21 +02:00
var (
multiRegexp = regexp.MustCompile("^/\\*")
singleRegexp = regexp.MustCompile("^//")
)
2018-02-05 00:51:19 +02:00
// Apply applies the rule to given file.
func (r *FileHeaderRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
2021-10-17 20:34:48 +02:00
if r.header == "" {
checkNumberOfArguments(1, arguments, r.Name())
var ok bool
r.header, ok = arguments[0].(string)
if !ok {
panic(fmt.Sprintf("invalid argument for \"file-header\" rule: first argument should be a string, got %T", arguments[0]))
}
2018-02-05 00:51:19 +02:00
}
2019-11-28 05:14:21 +02:00
failure := []lint.Failure{
{
Node: file.AST,
Confidence: 1,
Failure: "the file doesn't have an appropriate header",
2018-02-05 00:51:19 +02:00
},
}
2019-11-28 05:14:21 +02:00
if len(file.AST.Comments) == 0 {
return failure
}
2019-11-28 05:14:21 +02:00
g := file.AST.Comments[0]
2018-02-05 00:51:19 +02:00
if g == nil {
2019-11-28 05:14:21 +02:00
return failure
2018-02-05 00:51:19 +02:00
}
comment := ""
for _, c := range g.List {
text := c.Text
if multiRegexp.MatchString(text) {
2018-02-05 00:51:19 +02:00
text = text[2 : len(text)-2]
} else if singleRegexp.MatchString(text) {
2018-02-05 00:51:19 +02:00
text = text[2:]
}
comment += text
}
2021-10-17 20:34:48 +02:00
regex, err := regexp.Compile(r.header)
2019-11-28 05:14:21 +02:00
if err != nil {
panic(err.Error())
}
if !regex.MatchString(comment) {
2019-11-28 05:14:21 +02:00
return failure
2018-02-05 00:51:19 +02:00
}
return nil
}
2019-11-28 05:14:21 +02:00
// Name returns the rule name.
func (r *FileHeaderRule) Name() string {
return "file-header"
}