1
0
mirror of https://github.com/mgechev/revive.git synced 2025-07-03 00:26:51 +02:00

docs: improve comments for functions; enable godot (#1382)

This commit is contained in:
Oleksandr Redko
2025-05-27 08:44:24 +03:00
committed by GitHub
parent 398f7a83eb
commit f4976873e7
49 changed files with 135 additions and 132 deletions

View File

@ -8,6 +8,7 @@ linters:
enable:
- dupword
- gocritic
- godot
- govet
- ineffassign
- misspell

View File

@ -27,7 +27,7 @@ var (
commit = defaultCommit
date = defaultDate
builtBy = defaultBuilder
// AppFs is used to operations related with user config files
// AppFs is used for operations related to user config files.
AppFs = afero.NewOsFs()
)
@ -38,8 +38,8 @@ func fail(err string) {
// RunRevive runs the CLI for revive.
func RunRevive(extraRules ...revivelib.ExtraRule) {
// move parsing flags outside of init() otherwise tests don't works properly
// more info: https://github.com/golang/go/issues/46869#issuecomment-865695953
// Move parsing flags outside of init(); otherwise, tests don't work properly.
// More info: https://github.com/golang/go/issues/46869#issuecomment-865695953
initConfig()
if versionFlag {
@ -175,7 +175,7 @@ func initConfig() {
flag.Parse()
}
// getVersion returns build info (version, commit, date and builtBy)
// getVersion returns build info (version, commit, date, and builtBy).
func getVersion(builtBy, date, commit, version string) string {
var buildInfo string
if date != defaultDate && builtBy != defaultBuilder {

View File

@ -127,7 +127,7 @@ func getFormatters() map[string]lint.Formatter {
return result
}
// GetLintingRules yields the linting rules that must be applied by the linter
// GetLintingRules yields the linting rules that must be applied by the linter.
func GetLintingRules(config *lint.Config, extraRules []lint.Rule) ([]lint.Rule, error) {
rulesMap := map[string]lint.Rule{}
for _, r := range allRules {
@ -229,7 +229,7 @@ func normalizeConfig(config *lint.Config) {
const defaultConfidence = 0.8
// GetConfig yields the configuration
// GetConfig yields the configuration.
func GetConfig(configPath string) (*lint.Config, error) {
config := &lint.Config{}
switch {
@ -248,7 +248,7 @@ func GetConfig(configPath string) (*lint.Config, error) {
return config, nil
}
// GetFormatter yields the formatter for lint failures
// GetFormatter yields the formatter for lint failures.
func GetFormatter(formatterName string) (lint.Formatter, error) {
formatters := getFormatters()
if formatterName == "" {

View File

@ -14,7 +14,7 @@ type Checkstyle struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*Checkstyle) Name() string {
return "checkstyle"
}

View File

@ -13,7 +13,7 @@ type Default struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*Default) Name() string {
return "default"
}

View File

@ -19,7 +19,7 @@ type Friendly struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*Friendly) Name() string {
return "friendly"
}

View File

@ -12,12 +12,12 @@ type JSON struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*JSON) Name() string {
return "json"
}
// jsonObject defines a JSON object of an failure
// jsonObject defines a JSON object of an failure.
type jsonObject struct {
Severity lint.Severity
lint.Failure `json:",inline"`

View File

@ -13,7 +13,7 @@ type NDJSON struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*NDJSON) Name() string {
return "ndjson"
}

View File

@ -13,7 +13,7 @@ type Plain struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*Plain) Name() string {
return "plain"
}

View File

@ -15,7 +15,7 @@ type Sarif struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*Sarif) Name() string {
return "sarif"
}

View File

@ -13,7 +13,7 @@ type Stylish struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*Stylish) Name() string {
return "stylish"
}

View File

@ -15,7 +15,7 @@ type Unix struct {
Metadata lint.FormatterMetadata
}
// Name returns the name of the formatter
// Name returns the name of the formatter.
func (*Unix) Name() string {
return "unix"
}

View File

@ -15,7 +15,7 @@ import (
// by the given name, parameters types and return types; false otherwise.
//
// Example: to check if a function declaration has the signature Foo(int, string) (bool,error)
// call to FuncSignatureIs(funcDecl,"Foo",[]string{"int","string"},[]string{"bool","error"})
// call to FuncSignatureIs(funcDecl,"Foo",[]string{"int","string"},[]string{"bool","error"}).
func FuncSignatureIs(funcDecl *ast.FuncDecl, wantName string, wantParametersTypes, wantResultsTypes []string) bool {
if wantName != funcDecl.Name.String() {
return false // func name doesn't match expected one
@ -32,7 +32,7 @@ func FuncSignatureIs(funcDecl *ast.FuncDecl, wantName string, wantParametersType
}
// funcParametersSignatureIs returns true if the function has parameters of the given type and order,
// false otherwise
// false otherwise.
func funcParametersSignatureIs(funcDecl *ast.FuncDecl, wantParametersTypes []string) bool {
funcParametersTypes := GetTypeNames(funcDecl.Type.Params)
@ -117,7 +117,7 @@ func IsPkgDotName(expr ast.Expr, pkg, name string) bool {
}
// PickNodes yields a list of nodes by picking them from a sub-ast with root node n.
// Nodes are selected by applying the selector function
// Nodes are selected by applying the selector function.
func PickNodes(n ast.Node, selector func(n ast.Node) bool) []ast.Node {
var result []ast.Node

View File

@ -1,7 +1,7 @@
package ifelse
// Args contains arguments common to the early-return, indent-error-flow
// and superfluous-else rules
// Args contains arguments common to the early-return, indent-error-flow,
// and superfluous-else rules.
type Args struct {
PreserveScope bool
AllowJump bool

View File

@ -58,7 +58,7 @@ func StmtBranch(stmt ast.Stmt) Branch {
return Regular.Branch()
}
// String returns a brief string representation
// String returns a brief string representation.
func (b Branch) String() string {
switch b.BranchKind {
case Empty:
@ -71,7 +71,7 @@ func (b Branch) String() string {
return fmt.Sprintf("{ ... %v }", b.BranchKind)
}
// LongString returns a longer form string representation
// LongString returns a longer form string representation.
func (b Branch) LongString() string {
switch b.BranchKind {
case Panic, Exit:
@ -80,7 +80,7 @@ func (b Branch) LongString() string {
return b.BranchKind.LongString()
}
// HasDecls returns whether the branch has any top-level declarations
// HasDecls returns whether the branch has any top-level declarations.
func (b Branch) HasDecls() bool {
for _, stmt := range b.block {
switch stmt := stmt.(type) {
@ -95,7 +95,7 @@ func (b Branch) HasDecls() bool {
return false
}
// IsShort returns whether the branch is empty or consists of a single statement
// IsShort returns whether the branch is empty or consists of a single statement.
func (b Branch) IsShort() bool {
switch len(b.block) {
case 0:

View File

@ -5,35 +5,35 @@ package ifelse
type BranchKind int
const (
// Empty branches do nothing
// Empty branches do nothing.
Empty BranchKind = iota
// Return branches return from the current function
// Return branches return from the current function.
Return
// Continue branches continue a surrounding "for" loop
// Continue branches continue a surrounding "for" loop.
Continue
// Break branches break a surrounding "for" loop
// Break branches break a surrounding "for" loop.
Break
// Goto branches conclude with a "goto" statement
// Goto branches conclude with a "goto" statement.
Goto
// Panic branches panic the current function
// Panic branches panic the current function.
Panic
// Exit branches end the program
// Exit branches end the program.
Exit
// Regular branches do not fit any category above
// Regular branches do not fit any category above.
Regular
)
// IsEmpty tests if the branch is empty
// IsEmpty tests if the branch is empty.
func (k BranchKind) IsEmpty() bool { return k == Empty }
// Returns tests if the branch returns from the current function
// Returns tests if the branch returns from the current function.
func (k BranchKind) Returns() bool { return k == Return }
// Deviates tests if the control does not flow to the first
@ -48,10 +48,10 @@ func (k BranchKind) Deviates() bool {
panic("invalid kind")
}
// Branch returns a Branch with the given kind
// Branch returns a Branch with the given kind.
func (k BranchKind) Branch() Branch { return Branch{BranchKind: k} }
// String returns a brief string representation
// String returns a brief string representation.
func (k BranchKind) String() string {
switch k {
case Empty:
@ -74,7 +74,7 @@ func (k BranchKind) String() string {
panic("invalid kind")
}
// LongString returns a longer form string representation
// LongString returns a longer form string representation.
func (k BranchKind) LongString() string {
switch k {
case Empty:

View File

@ -40,7 +40,7 @@ func ExprCall(expr *ast.ExprStmt) (Call, bool) {
return Call{}, false
}
// String returns the function name with package qualifier (if any)
// String returns the function name with package qualifier (if any).
func (f Call) String() string {
if f.Pkg != "" {
return fmt.Sprintf("%s.%s", f.Pkg, f.Name)

View File

@ -6,10 +6,10 @@ import "go/ast"
type Target int
const (
// TargetIf means the text refers to the "if"
// TargetIf means the text refers to the "if".
TargetIf Target = iota
// TargetElse means the text refers to the "else"
// TargetElse means the text refers to the "else".
TargetElse
)

View File

@ -21,7 +21,7 @@ type RuleConfig struct {
excludeFilters []*FileFilter
}
// Initialize - should be called after reading from TOML file
// Initialize should be called after reading from TOML file.
func (rc *RuleConfig) Initialize() error {
for _, f := range rc.Exclude {
ff, err := ParseFileFilter(f)
@ -36,7 +36,7 @@ func (rc *RuleConfig) Initialize() error {
// RulesConfig defines the config for all rules.
type RulesConfig = map[string]RuleConfig
// MustExclude - checks if given filename `name` must be excluded
// MustExclude checks if given filename `name` must be excluded.
func (rc *RuleConfig) MustExclude(name string) bool {
for _, exclude := range rc.excludeFilters {
if exclude.MatchFileName(name) {

View File

@ -53,7 +53,7 @@ const (
type FailureCategory string
const (
// SeverityWarning declares failures of type warning
// SeverityWarning declares failures of type warning.
SeverityWarning = "warning"
// SeverityError declares failures of type error.
SeverityError = "error"
@ -62,7 +62,7 @@ const (
// Severity is the type for the failure types.
type Severity string
// FailurePosition returns the failure position
// FailurePosition returns the failure position.
type FailurePosition struct {
Start token.Position
End token.Position

View File

@ -29,7 +29,7 @@ func (f *File) Content() []byte {
return f.content
}
// NewFile creates a new file
// NewFile creates a new file.
func NewFile(name string, content []byte, pkg *Package) (*File, error) {
f, err := parser.ParseFile(pkg.fset, name, content, parser.ParseComments)
if err != nil {
@ -73,7 +73,7 @@ var basicTypeKinds = map[types.BasicKind]string{
// IsUntypedConst reports whether expr is an untyped constant,
// and indicates what its default type is.
// scope may be nil.
// Scope may be nil.
func (f *File) IsUntypedConst(expr ast.Expr) (defType string, ok bool) {
// Re-evaluate expr outside its context to see if it's untyped.
// (An expr evaluated within, for example, an assignment context will get the type of the LHS.)

View File

@ -6,12 +6,12 @@ import (
"strings"
)
// FileFilter - file filter to exclude some files for rule
// supports whole
// 1. file/dir names : pkg/mypkg/my.go,
// 2. globs: **/*.pb.go,
// 3. regexes (~ prefix) ~-tmp\.\d+\.go
// 4. special test marker `TEST` - treats as `~_test\.go`
// FileFilter filters file to exclude some files for a rule.
// Supports the following:
// - File or directory names: pkg/mypkg/my.go
// - Globs: **/*.pb.go,
// - Regexes (with ~ prefix): ~-tmp\.\d+\.go
// - Special test marker `TEST` (treated as `~_test\.go`).
type FileFilter struct {
// raw definition of filter inside config
raw string
@ -23,10 +23,10 @@ type FileFilter struct {
matchesNothing bool
}
// ParseFileFilter - creates [FileFilter] for given raw filter
// if empty string, it matches nothing
// if `*`, or `~`, it matches everything
// while regexp could be invalid, it could return it's compilation error
// ParseFileFilter creates a [FileFilter] for the given raw filter.
// If the string is empty, it matches nothing.
// If the string is `*` or `~`, it matches everything.
// If the regular expression is invalid, it returns a compilation error.
func ParseFileFilter(rawFilter string) (*FileFilter, error) {
rawFilter = strings.TrimSpace(rawFilter)
result := new(FileFilter)
@ -43,7 +43,7 @@ func ParseFileFilter(rawFilter string) (*FileFilter, error) {
func (ff *FileFilter) String() string { return ff.raw }
// MatchFileName - checks if file name matches filter
// MatchFileName checks if the file name matches the filter.
func (ff *FileFilter) MatchFileName(name string) bool {
if ff.matchesAll {
return true

View File

@ -1,13 +1,13 @@
package lint
// FormatterMetadata configuration of a formatter
// FormatterMetadata configuration of a formatter.
type FormatterMetadata struct {
Name string
Description string
Sample string
}
// Formatter defines an interface for failure formatters
// Formatter defines an interface for failure formatters.
type Formatter interface {
Format(<-chan Failure, Config) (string, error)
Name() string

View File

@ -25,7 +25,7 @@ type Linter struct {
fileReadTokens chan struct{}
}
// New creates a new Linter
// New creates a new Linter.
func New(reader ReadFile, maxOpenFiles int) Linter {
var fileReadTokens chan struct{}
if maxOpenFiles > 0 {
@ -215,7 +215,7 @@ func isGenerated(src []byte) bool {
return false
}
// addInvalidFileFailure adds a failure for an invalid formatted file
// addInvalidFileFailure adds a failure for an invalid formatted file.
func addInvalidFileFailure(filename, errStr string, failures chan Failure) {
position := getPositionInvalidFile(filename, errStr)
failures <- Failure{
@ -226,12 +226,14 @@ func addInvalidFileFailure(filename, errStr string, failures chan Failure) {
}
}
// errPosRegexp matches with an NewFile error message
// i.e. : corrupted.go:10:4: expected '}', found 'EOF
// first group matches the line and the second group, the column
// errPosRegexp matches with a NewFile error message:
//
// corrupted.go:10:4: expected '}', found 'EOF
//
// The first group matches the line, and the second group matches the column.
var errPosRegexp = regexp.MustCompile(`.*:(\d*):(\d*):.*$`)
// getPositionInvalidFile gets the position of the error in an invalid file
// getPositionInvalidFile gets the position of the error in an invalid file.
func getPositionInvalidFile(filename, s string) FailurePosition {
pos := errPosRegexp.FindStringSubmatch(s)
if len(pos) < 3 {

View File

@ -2,7 +2,7 @@ package lint
import "testing"
// TestName tests Name function
// TestName tests Name function.
func TestName(t *testing.T) {
tests := []struct {
name, want string

View File

@ -34,13 +34,13 @@ var (
trueValue = 1
falseValue = 2
// Go115 is a constant representing the Go version 1.15
// Go115 is a constant representing the Go version 1.15.
Go115 = goversion.Must(goversion.NewVersion("1.15"))
// Go121 is a constant representing the Go version 1.21
// Go121 is a constant representing the Go version 1.21.
Go121 = goversion.Must(goversion.NewVersion("1.21"))
// Go122 is a constant representing the Go version 1.22
// Go122 is a constant representing the Go version 1.22.
Go122 = goversion.Must(goversion.NewVersion("1.22"))
// Go124 is a constant representing the Go version 1.24
// Go124 is a constant representing the Go version 1.24.
Go124 = goversion.Must(goversion.NewVersion("1.24"))
)
@ -73,7 +73,7 @@ func (p *Package) IsMain() bool {
return false
}
// TypesPkg yields information on this package
// TypesPkg yields information on this package.
func (p *Package) TypesPkg() *types.Package {
p.mu.RLock()
defer p.mu.RUnlock()
@ -81,7 +81,7 @@ func (p *Package) TypesPkg() *types.Package {
return p.typesPkg
}
// TypesInfo yields type information of this package identifiers
// TypesInfo yields type information of this package identifiers.
func (p *Package) TypesInfo() *types.Info {
p.mu.RLock()
defer p.mu.RUnlock()
@ -89,7 +89,7 @@ func (p *Package) TypesInfo() *types.Info {
return p.typesInfo
}
// Sortable yields a map of sortable types in this package
// Sortable yields a map of sortable types in this package.
func (p *Package) Sortable() map[string]bool {
p.mu.RLock()
defer p.mu.RUnlock()
@ -141,7 +141,7 @@ func (p *Package) TypeCheck() error {
}
// check function encapsulates the call to go/types.Config.Check method and
// recovers if the called method panics (see issue #59)
// recovers if the called method panics (see issue #59).
func check(config *types.Config, n string, fset *token.FileSet, astFiles []*ast.File, info *types.Info) (p *types.Package, err error) {
defer func() {
if r := recover(); r != nil {
@ -213,7 +213,7 @@ func (p *Package) lint(rules []Rule, config Config, failures chan Failure) error
return eg.Wait()
}
// IsAtLeastGoVersion returns true if the Go version for this package is v or higher, false otherwise
// IsAtLeastGoVersion returns true if the Go version for this package is v or higher, false otherwise.
func (p *Package) IsAtLeastGoVersion(v *goversion.Version) bool {
p.mu.RLock()
defer p.mu.RUnlock()

View File

@ -11,7 +11,7 @@ type DisabledInterval struct {
RuleName string
}
// Rule defines an abstract rule interface
// Rule defines an abstract rule interface.
type Rule interface {
Name() string
Apply(*File, Arguments) []Failure

View File

@ -12,7 +12,7 @@ const logFile = "revive.log"
var logger *slog.Logger
// GetLogger retrieves an instance of an application logger which outputs
// to a file if the debug flag is enabled
// to a file if the debug flag is enabled.
func GetLogger() (*slog.Logger, error) {
if logger != nil {
return logger, nil

View File

@ -68,7 +68,7 @@ func New(
}, nil
}
// Lint the included patterns, skipping excluded ones
// Lint the included patterns, skipping excluded ones.
func (r *Revive) Lint(patterns ...*LintPattern) (<-chan lint.Failure, error) {
includePatterns := []string{}
excludePatterns := []string{}

View File

@ -1,29 +1,29 @@
package revivelib
// LintPattern indicates a pattern to be included/excluded when linting
// LintPattern indicates a pattern to be included/excluded when linting.
type LintPattern struct {
isExclude bool
pattern string
}
// IsExclude - should this pattern be included or excluded when linting
// IsExclude determines should this pattern be included or excluded when linting.
func (p *LintPattern) IsExclude() bool {
return p.isExclude
}
// GetPattern - returns the actual pattern
// GetPattern returns the actual pattern
//
// Deprecated: Use [Pattern].
func (p *LintPattern) GetPattern() string {
return p.Pattern()
}
// Pattern - returns the actual pattern
// Pattern returns the actual pattern.
func (p *LintPattern) Pattern() string {
return p.pattern
}
// Include this pattern when linting
// Include this pattern when linting.
func Include(pattern string) *LintPattern {
return &LintPattern{
isExclude: false,
@ -31,7 +31,7 @@ func Include(pattern string) *LintPattern {
}
}
// Exclude this pattern when linting
// Exclude this pattern when linting.
func Exclude(pattern string) *LintPattern {
return &LintPattern{
isExclude: true,

View File

@ -50,12 +50,12 @@ func (r *BannedCharsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failur
return failures
}
// Name returns the rule name
// Name returns the rule name.
func (*BannedCharsRule) Name() string {
return bannedCharsRuleName
}
// getBannedCharsList converts arguments into the banned characters list
// getBannedCharsList converts arguments into the banned characters list.
func (r *BannedCharsRule) getBannedCharsList(args lint.Arguments) ([]string, error) {
var bannedChars []string
for _, char := range args {
@ -74,7 +74,7 @@ type lintBannedCharsRule struct {
onFailure func(lint.Failure)
}
// Visit checks for each node if an identifier contains banned characters
// Visit checks for each node if an identifier contains banned characters.
func (w lintBannedCharsRule) Visit(node ast.Node) ast.Visitor {
n, ok := node.(*ast.Ident)
if !ok {

View File

@ -42,7 +42,7 @@ func (w lintBareReturnRule) Visit(node ast.Node) ast.Visitor {
return w
}
// checkFunc will verify if the given function has named result and bare returns
// checkFunc will verify if the given function has named result and bare returns.
func (w lintBareReturnRule) checkFunc(results *ast.FieldList, body *ast.BlockStmt) {
hasNamedResults := results != nil && len(results.List) > 0 && results.List[0].Names != nil
if !hasNamedResults || body == nil {

View File

@ -8,7 +8,7 @@ import (
)
// CommentSpacingsRule check whether there is a space between
// the comment symbol( // ) and the start of the comment text
// the comment symbol( // ) and the start of the comment text.
type CommentSpacingsRule struct {
allowList []string
}

View File

@ -44,7 +44,7 @@ func (ps *packages) methodNames(lp *lint.Package) pkgMethods {
var allPkgs = packages{pkgs: make([]pkgMethods, 1)}
// ConfusingNamingRule lints method names that differ only by capitalization
// ConfusingNamingRule lints method names that differ only by capitalization.
type ConfusingNamingRule struct{}
// Apply applies the rule to given file.
@ -127,7 +127,7 @@ type lintConfusingNames struct {
const defaultStructName = "_" // used to map functions
// getStructName of a function receiver. Defaults to defaultStructName
// getStructName of a function receiver. Defaults to defaultStructName.
func getStructName(r *ast.FieldList) string {
result := defaultStructName

View File

@ -7,7 +7,7 @@ import (
"github.com/mgechev/revive/lint"
)
// ConfusingResultsRule lints given function declarations
// ConfusingResultsRule lints given function declarations.
type ConfusingResultsRule struct{}
// Apply applies the rule to given file.

View File

@ -88,7 +88,7 @@ type lintErrorStrings struct {
onFailure func(lint.Failure)
}
// Visit browses the AST
// Visit browses the AST.
func (w lintErrorStrings) Visit(n ast.Node) ast.Visitor {
ce, ok := n.(*ast.CallExpr)
if !ok {
@ -126,8 +126,8 @@ func (w lintErrorStrings) Visit(n ast.Node) ast.Visitor {
return w
}
// match returns true if the expression corresponds to the known pkg.function
// i.e.: errors.Wrap
// match returns true if the expression corresponds to the known pkg.function,
// i.e.: errors.Wrap.
func (w lintErrorStrings) match(expr *ast.CallExpr) bool {
sel, ok := expr.Fun.(*ast.SelectorExpr)
if !ok {
@ -147,8 +147,8 @@ func (w lintErrorStrings) match(expr *ast.CallExpr) bool {
return ok
}
// getMessage returns the message depending on its position
// returns false if the cast is unsuccessful
// getMessage returns the message depending on its position.
// Returns false if the cast is unsuccessful.
func (w lintErrorStrings) getMessage(expr *ast.CallExpr) (s *ast.BasicLit, success bool) {
str, ok := w.checkArg(expr, 0)
if ok {

View File

@ -12,7 +12,7 @@ import (
"github.com/mgechev/revive/lint"
)
// disabledChecks store ignored warnings types
// disabledChecks store ignored warnings types.
type disabledChecks struct {
Const bool
Function bool
@ -30,7 +30,7 @@ const (
checkNameStuttering = "stuttering"
)
// isDisabled returns true if the given check is disabled, false otherwise
// isDisabled returns true if the given check is disabled, false otherwise.
func (dc *disabledChecks) isDisabled(checkName string) bool {
switch checkName {
case "var":
@ -254,7 +254,7 @@ func (w *lintExported) lintTypeDoc(t *ast.TypeSpec, doc *ast.CommentGroup, first
)
}
// checkValueNames returns true if names check, false otherwise
// checkValueNames returns true if names check, false otherwise.
func (w *lintExported) checkValueNames(names []*ast.Ident, nodeToBlame ast.Node, kind string) bool {
// Check that none are exported except for the first.
if len(names) < 2 {
@ -438,7 +438,7 @@ func (w *lintExported) lintInterfaceMethod(typeName string, m *ast.Field) {
}
}
// mustCheckMethod returns true if the method must be checked by this rule, false otherwise
// mustCheckMethod returns true if the method must be checked by this rule, false otherwise.
func (w *lintExported) mustCheckMethod(fn *ast.FuncDecl) bool {
recv := typeparams.ReceiverType(fn)

View File

@ -9,7 +9,7 @@ import (
"github.com/mgechev/revive/lint"
)
// FilenameFormatRule lints source filenames according to a set of regular expressions given as arguments
// FilenameFormatRule lints source filenames according to a set of regular expressions given as arguments.
type FilenameFormatRule struct {
format *regexp.Regexp
}

View File

@ -66,7 +66,7 @@ type importShadowing struct {
skipIdents map[*ast.Ident]struct{}
}
// Visit visits AST nodes and checks if id nodes (ast.Ident) shadow an import name
// Visit visits AST nodes and checks if id nodes (ast.Ident) shadow an import name.
func (w importShadowing) Visit(n ast.Node) ast.Visitor {
switch n := n.(type) {
case *ast.AssignStmt:

View File

@ -9,7 +9,7 @@ import (
"github.com/mgechev/revive/lint"
)
// RangeValAddress lints
// RangeValAddress warns if address of range value is used dangerously.
type RangeValAddress struct{}
// Apply applies the rule to given file.

View File

@ -11,7 +11,7 @@ import (
"github.com/mgechev/revive/lint"
)
// StringFormatRule lints strings and/or comments according to a set of regular expressions given as Arguments
// StringFormatRule lints strings and/or comments according to a set of regular expressions given as Arguments.
type StringFormatRule struct {
rules []stringFormatSubrule
}
@ -81,7 +81,7 @@ type stringFormatSubruleScope struct {
field string // (optional) If the argument to be checked is a struct, which member of the struct is checked against the rule (top level members only)
}
// Regex inserted to match valid function/struct field identifiers
// Regex inserted to match valid function/struct field identifiers.
const identRegex = "[_A-Za-z][_A-Za-z0-9]*"
var parseStringFormatScope = regexp.MustCompile(
@ -165,17 +165,17 @@ func (r *StringFormatRule) parseArgument(argument any, ruleNum int) (scopes stri
return scopes, regex, negated, errorMessage, nil
}
// Report an invalid config, this is specifically the user's fault
// Report an invalid config, this is specifically the user's fault.
func (*StringFormatRule) configError(msg string, ruleNum, option int) error {
return fmt.Errorf("invalid configuration for string-format: %s [argument %d, option %d]", msg, ruleNum, option)
}
// Report a general config parsing failure, this may be the user's fault, but it isn't known for certain
// Report a general config parsing failure, this may be the user's fault, but it isn't known for certain.
func (*StringFormatRule) parseError(msg string, ruleNum, option int) error {
return fmt.Errorf("failed to parse configuration for string-format: %s [argument %d, option %d]", msg, ruleNum, option)
}
// Report a general scope config parsing failure, this may be the user's fault, but it isn't known for certain
// Report a general scope config parsing failure, this may be the user's fault, but it isn't known for certain.
func (*StringFormatRule) parseScopeError(msg string, ruleNum, option, scopeNum int) error {
return fmt.Errorf("failed to parse configuration for string-format: %s [argument %d, option %d, scope index %d]", msg, ruleNum, option, scopeNum)
}
@ -204,7 +204,7 @@ func (w *lintStringFormatRule) Visit(node ast.Node) ast.Visitor {
return w
}
// Return the name of a call expression in the form of package.Func or Func
// Return the name of a call expression in the form of package.Func or Func.
func (*lintStringFormatRule) getCallName(call *ast.CallExpr) (callName string, ok bool) {
if ident, ok := call.Fun.(*ast.Ident); ok {
// Local function call
@ -227,7 +227,7 @@ func (*lintStringFormatRule) getCallName(call *ast.CallExpr) (callName string, o
return "", false
}
// apply a single format rule to a call expression (should be done after verifying the that the call expression matches the rule's scope)
// apply a single format rule to a call expression (should be done after verifying the that the call expression matches the rule's scope).
func (r *stringFormatSubrule) apply(call *ast.CallExpr, scope *stringFormatSubruleScope) {
if len(call.Args) <= scope.argument {
return

View File

@ -38,7 +38,6 @@ const (
type tagChecker func(checkCtx *checkContext, tag *structtag.Tag, fieldType ast.Expr) (message string, succeeded bool)
// populate tag checkers map
var tagCheckers = map[tagKey]tagChecker{
keyASN1: checkASN1Tag,
keyBSON: checkBSONTag,
@ -757,7 +756,8 @@ var validateSingleOptions = map[string]struct{}{
"uuid5_rfc4122": {},
}
// These are options that are used in expressions of the form
// These are options that are used in expressions of the form:
//
// <option> = <RHS>
var validateLHS = map[string]struct{}{
"contains": {},

View File

@ -41,7 +41,7 @@ type lintTimeDate struct {
}
var (
// timeDateArgumentNames are the names of the arguments of time.Date
// timeDateArgumentNames are the names of the arguments of time.Date.
timeDateArgumentNames = []string{
"year",
"month",
@ -53,7 +53,7 @@ var (
"timezone",
}
// timeDateArity is the number of arguments of time.Date
// timeDateArity is the number of arguments of time.Date.
timeDateArity = len(timeDateArgumentNames)
)

View File

@ -9,7 +9,7 @@ import (
"github.com/mgechev/revive/lint"
)
// TimeEqualRule shows where "==" and "!=" used for equality check time.Time
// TimeEqualRule shows where "==" and "!=" used for equality check time.Time.
type TimeEqualRule struct{}
// Apply applies the rule to given file.

View File

@ -136,7 +136,7 @@ func (w *lintUncheckedTypeAssertion) handleAssignment(n *ast.AssignStmt) {
}
}
// handles "return foo(.*bar)" - one of them is enough to fail as golang does not forward the type cast tuples in return statements
// handles "return foo(.*bar)" - one of them is enough to fail as golang does not forward the type cast tuples in return statements.
func (w *lintUncheckedTypeAssertion) handleReturn(n *ast.ReturnStmt) {
for _, r := range n.Results {
w.requireNoTypeAssert(r)

View File

@ -79,10 +79,10 @@ type lintUnconditionalRecursionRule struct {
}
// Visit will traverse function's body we search for calls to the function itself.
// We do not search inside conditional control structures (if, for, switch, ...) because any recursive call inside them is conditioned
// We do search inside conditional control structures are statements that will take the control out of the function (return, exit, panic)
// If we find conditional control exits, it means the function is NOT unconditionally-recursive
// If we find a recursive call before finding any conditional exit, a failure is generated
// We do not search inside conditional control structures (if, for, switch, ...) because any recursive call inside them is conditioned.
// We do search inside conditional control structures are statements that will take the control out of the function (return, exit, panic).
// If we find conditional control exits, it means the function is NOT unconditionally-recursive.
// If we find a recursive call before finding any conditional exit, a failure is generated.
// In resume: if we found a recursive call control-dependent from the entry point of the function then we raise a failure.
func (w *lintUnconditionalRecursionRule) Visit(node ast.Node) ast.Visitor {
switch n := node.(type) {

View File

@ -35,7 +35,7 @@ func srcLine(src []byte, p token.Position) string {
return string(src[lo:hi])
}
// checkNumberOfArguments fails if the given number of arguments is not, at least, the expected one
// checkNumberOfArguments fails if the given number of arguments is not, at least, the expected one.
func checkNumberOfArguments(expected int, args lint.Arguments, ruleName string) error {
if len(args) < expected {
return fmt.Errorf("not enough arguments for %s rule, expected %d, got %d. Please check the rule's documentation", ruleName, expected, len(args))
@ -50,7 +50,7 @@ func isRuleOption(arg, name string) bool {
// normalizeRuleOption returns an option name from the argument. It is lowercased and without hyphens.
//
// Example: normalizeRuleOption("allowTypesBefore"), normalizeRuleOption("allow-types-before") -> "allowtypesbefore"
// Example: normalizeRuleOption("allowTypesBefore"), normalizeRuleOption("allow-types-before") -> "allowtypesbefore".
func normalizeRuleOption(arg string) string {
return strings.ToLower(strings.ReplaceAll(arg, "-", ""))
}
@ -66,7 +66,7 @@ func isCallToExitFunction(pkgName, functionName string) bool {
return exitFunctions[pkgName] != nil && exitFunctions[pkgName][functionName]
}
// newInternalFailureError returns a slice of Failure with a single internal failure in it
// newInternalFailureError returns a slice of Failure with a single internal failure in it.
func newInternalFailureError(e error) []lint.Failure {
return []lint.Failure{lint.NewInternalFailure(e.Error())}
}

View File

@ -7,7 +7,7 @@ import (
"github.com/mgechev/revive/rule"
)
// Test that left and right side of Binary operators (only AND, OR) are swapable
// Test that left and right side of Binary operators (only AND, OR) are swapable.
func TestOptimizeOperandsOrder(t *testing.T) {
testRule(t, "optimize_operands_order", &rule.OptimizeOperandsOrderRule{}, &lint.RuleConfig{})
}

View File

@ -17,7 +17,7 @@ import (
)
// configureRule configures the given rule with the given configuration
// if the rule implements the ConfigurableRule interface
// if the rule implements the ConfigurableRule interface.
func configureRule(t *testing.T, rule lint.Rule, arguments lint.Arguments) {
t.Helper()
@ -151,7 +151,7 @@ type instruction struct {
Confidence float64 // confidence level
}
// JSONInstruction structure used when we parse json object instead of classic MATCH string
// JSONInstruction structure used when we parse json object instead of classic MATCH string.
type JSONInstruction struct {
Match string `json:"MATCH"`
Category string `json:"Category"`
@ -277,7 +277,7 @@ func srcLine(src []byte, p token.Position) string {
return string(src[lo:hi])
}
// TestLine tests srcLine function
// TestLine tests srcLine function.
func TestLine(t *testing.T) {
tests := []struct {
src string
@ -319,7 +319,7 @@ func exportedType(typ types.Type) bool {
return true
}
// TestExportedType tests exportedType function
// TestExportedType tests exportedType function.
func TestExportedType(t *testing.T) {
tests := []struct {
typString string