1
0
mirror of https://github.com/mgechev/revive.git synced 2025-11-25 22:12:38 +02:00
Files
revive/rule/line_length_limit.go

107 lines
2.2 KiB
Go
Raw Normal View History

package rule
import (
"bufio"
"bytes"
"errors"
"fmt"
"go/token"
"strings"
2022-04-10 09:06:59 +02:00
"sync"
"unicode/utf8"
"github.com/mgechev/revive/lint"
)
2024-12-01 17:44:41 +02:00
// LineLengthLimitRule lints number of characters in a line.
2021-10-17 20:34:48 +02:00
type LineLengthLimitRule struct {
max int
configureOnce sync.Once
2021-10-17 20:34:48 +02:00
}
const defaultLineLengthLimit = 80
func (r *LineLengthLimitRule) configure(arguments lint.Arguments) error {
2024-10-01 12:14:02 +02:00
if len(arguments) < 1 {
r.max = defaultLineLengthLimit
return nil
2024-10-01 12:14:02 +02:00
}
maxLength, ok := arguments[0].(int64) // Alt. non panicking version
if !ok || maxLength < 0 {
return errors.New(`invalid value passed as argument number to the "line-length-limit" rule`)
2024-10-01 12:14:02 +02:00
}
r.max = int(maxLength)
return nil
2022-04-10 09:06:59 +02:00
}
// Apply applies the rule to given file.
func (r *LineLengthLimitRule) Apply(file *lint.File, arguments lint.Arguments) []lint.Failure {
var configureErr error
r.configureOnce.Do(func() { configureErr = r.configure(arguments) })
if configureErr != nil {
return newInternalFailureError(configureErr)
}
var failures []lint.Failure
2022-04-10 09:06:59 +02:00
checker := lintLineLengthNum{
2021-10-17 20:34:48 +02:00
max: r.max,
file: file,
onFailure: func(failure lint.Failure) {
failures = append(failures, failure)
},
}
checker.check()
return failures
}
// Name returns the rule name.
2022-04-10 11:55:13 +02:00
func (*LineLengthLimitRule) Name() string {
return "line-length-limit"
}
type lintLineLengthNum struct {
max int
file *lint.File
onFailure func(lint.Failure)
}
func (r lintLineLengthNum) check() {
f := bytes.NewReader(r.file.Content())
spaces := strings.Repeat(" ", 4) // tab width = 4
l := 1
s := bufio.NewScanner(f)
for s.Scan() {
t := s.Text()
2021-10-23 13:25:41 +02:00
t = strings.ReplaceAll(t, "\t", spaces)
c := utf8.RuneCountInString(t)
if c > r.max {
r.onFailure(lint.Failure{
Category: "code-style",
Position: lint.FailurePosition{
// Offset not set; it is non-trivial, and doesn't appear to be needed.
Start: token.Position{
Filename: r.file.Name,
Line: l,
Column: 0,
},
End: token.Position{
Filename: r.file.Name,
Line: l,
Column: c,
},
},
Confidence: 1,
Failure: fmt.Sprintf("line is %d characters, out of limit %d", c, r.max),
})
}
l++
}
}