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:
@ -8,6 +8,7 @@ linters:
|
|||||||
enable:
|
enable:
|
||||||
- dupword
|
- dupword
|
||||||
- gocritic
|
- gocritic
|
||||||
|
- godot
|
||||||
- govet
|
- govet
|
||||||
- ineffassign
|
- ineffassign
|
||||||
- misspell
|
- misspell
|
||||||
|
@ -27,7 +27,7 @@ var (
|
|||||||
commit = defaultCommit
|
commit = defaultCommit
|
||||||
date = defaultDate
|
date = defaultDate
|
||||||
builtBy = defaultBuilder
|
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()
|
AppFs = afero.NewOsFs()
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -38,8 +38,8 @@ func fail(err string) {
|
|||||||
|
|
||||||
// RunRevive runs the CLI for revive.
|
// RunRevive runs the CLI for revive.
|
||||||
func RunRevive(extraRules ...revivelib.ExtraRule) {
|
func RunRevive(extraRules ...revivelib.ExtraRule) {
|
||||||
// move parsing flags outside of init() otherwise tests don't works properly
|
// Move parsing flags outside of init(); otherwise, tests don't work properly.
|
||||||
// more info: https://github.com/golang/go/issues/46869#issuecomment-865695953
|
// More info: https://github.com/golang/go/issues/46869#issuecomment-865695953
|
||||||
initConfig()
|
initConfig()
|
||||||
|
|
||||||
if versionFlag {
|
if versionFlag {
|
||||||
@ -175,7 +175,7 @@ func initConfig() {
|
|||||||
flag.Parse()
|
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 {
|
func getVersion(builtBy, date, commit, version string) string {
|
||||||
var buildInfo string
|
var buildInfo string
|
||||||
if date != defaultDate && builtBy != defaultBuilder {
|
if date != defaultDate && builtBy != defaultBuilder {
|
||||||
|
@ -127,7 +127,7 @@ func getFormatters() map[string]lint.Formatter {
|
|||||||
return result
|
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) {
|
func GetLintingRules(config *lint.Config, extraRules []lint.Rule) ([]lint.Rule, error) {
|
||||||
rulesMap := map[string]lint.Rule{}
|
rulesMap := map[string]lint.Rule{}
|
||||||
for _, r := range allRules {
|
for _, r := range allRules {
|
||||||
@ -229,7 +229,7 @@ func normalizeConfig(config *lint.Config) {
|
|||||||
|
|
||||||
const defaultConfidence = 0.8
|
const defaultConfidence = 0.8
|
||||||
|
|
||||||
// GetConfig yields the configuration
|
// GetConfig yields the configuration.
|
||||||
func GetConfig(configPath string) (*lint.Config, error) {
|
func GetConfig(configPath string) (*lint.Config, error) {
|
||||||
config := &lint.Config{}
|
config := &lint.Config{}
|
||||||
switch {
|
switch {
|
||||||
@ -248,7 +248,7 @@ func GetConfig(configPath string) (*lint.Config, error) {
|
|||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetFormatter yields the formatter for lint failures
|
// GetFormatter yields the formatter for lint failures.
|
||||||
func GetFormatter(formatterName string) (lint.Formatter, error) {
|
func GetFormatter(formatterName string) (lint.Formatter, error) {
|
||||||
formatters := getFormatters()
|
formatters := getFormatters()
|
||||||
if formatterName == "" {
|
if formatterName == "" {
|
||||||
|
@ -14,7 +14,7 @@ type Checkstyle struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*Checkstyle) Name() string {
|
func (*Checkstyle) Name() string {
|
||||||
return "checkstyle"
|
return "checkstyle"
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ type Default struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*Default) Name() string {
|
func (*Default) Name() string {
|
||||||
return "default"
|
return "default"
|
||||||
}
|
}
|
||||||
|
@ -19,7 +19,7 @@ type Friendly struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*Friendly) Name() string {
|
func (*Friendly) Name() string {
|
||||||
return "friendly"
|
return "friendly"
|
||||||
}
|
}
|
||||||
|
@ -12,12 +12,12 @@ type JSON struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*JSON) Name() string {
|
func (*JSON) Name() string {
|
||||||
return "json"
|
return "json"
|
||||||
}
|
}
|
||||||
|
|
||||||
// jsonObject defines a JSON object of an failure
|
// jsonObject defines a JSON object of an failure.
|
||||||
type jsonObject struct {
|
type jsonObject struct {
|
||||||
Severity lint.Severity
|
Severity lint.Severity
|
||||||
lint.Failure `json:",inline"`
|
lint.Failure `json:",inline"`
|
||||||
|
@ -13,7 +13,7 @@ type NDJSON struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*NDJSON) Name() string {
|
func (*NDJSON) Name() string {
|
||||||
return "ndjson"
|
return "ndjson"
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ type Plain struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*Plain) Name() string {
|
func (*Plain) Name() string {
|
||||||
return "plain"
|
return "plain"
|
||||||
}
|
}
|
||||||
|
@ -15,7 +15,7 @@ type Sarif struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*Sarif) Name() string {
|
func (*Sarif) Name() string {
|
||||||
return "sarif"
|
return "sarif"
|
||||||
}
|
}
|
||||||
|
@ -13,7 +13,7 @@ type Stylish struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*Stylish) Name() string {
|
func (*Stylish) Name() string {
|
||||||
return "stylish"
|
return "stylish"
|
||||||
}
|
}
|
||||||
|
@ -15,7 +15,7 @@ type Unix struct {
|
|||||||
Metadata lint.FormatterMetadata
|
Metadata lint.FormatterMetadata
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the name of the formatter
|
// Name returns the name of the formatter.
|
||||||
func (*Unix) Name() string {
|
func (*Unix) Name() string {
|
||||||
return "unix"
|
return "unix"
|
||||||
}
|
}
|
||||||
|
@ -15,7 +15,7 @@ import (
|
|||||||
// by the given name, parameters types and return types; false otherwise.
|
// 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)
|
// 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 {
|
func FuncSignatureIs(funcDecl *ast.FuncDecl, wantName string, wantParametersTypes, wantResultsTypes []string) bool {
|
||||||
if wantName != funcDecl.Name.String() {
|
if wantName != funcDecl.Name.String() {
|
||||||
return false // func name doesn't match expected one
|
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,
|
// 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 {
|
func funcParametersSignatureIs(funcDecl *ast.FuncDecl, wantParametersTypes []string) bool {
|
||||||
funcParametersTypes := GetTypeNames(funcDecl.Type.Params)
|
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.
|
// 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 {
|
func PickNodes(n ast.Node, selector func(n ast.Node) bool) []ast.Node {
|
||||||
var result []ast.Node
|
var result []ast.Node
|
||||||
|
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
package ifelse
|
package ifelse
|
||||||
|
|
||||||
// Args contains arguments common to the early-return, indent-error-flow
|
// Args contains arguments common to the early-return, indent-error-flow,
|
||||||
// and superfluous-else rules
|
// and superfluous-else rules.
|
||||||
type Args struct {
|
type Args struct {
|
||||||
PreserveScope bool
|
PreserveScope bool
|
||||||
AllowJump bool
|
AllowJump bool
|
||||||
|
@ -58,7 +58,7 @@ func StmtBranch(stmt ast.Stmt) Branch {
|
|||||||
return Regular.Branch()
|
return Regular.Branch()
|
||||||
}
|
}
|
||||||
|
|
||||||
// String returns a brief string representation
|
// String returns a brief string representation.
|
||||||
func (b Branch) String() string {
|
func (b Branch) String() string {
|
||||||
switch b.BranchKind {
|
switch b.BranchKind {
|
||||||
case Empty:
|
case Empty:
|
||||||
@ -71,7 +71,7 @@ func (b Branch) String() string {
|
|||||||
return fmt.Sprintf("{ ... %v }", b.BranchKind)
|
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 {
|
func (b Branch) LongString() string {
|
||||||
switch b.BranchKind {
|
switch b.BranchKind {
|
||||||
case Panic, Exit:
|
case Panic, Exit:
|
||||||
@ -80,7 +80,7 @@ func (b Branch) LongString() string {
|
|||||||
return b.BranchKind.LongString()
|
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 {
|
func (b Branch) HasDecls() bool {
|
||||||
for _, stmt := range b.block {
|
for _, stmt := range b.block {
|
||||||
switch stmt := stmt.(type) {
|
switch stmt := stmt.(type) {
|
||||||
@ -95,7 +95,7 @@ func (b Branch) HasDecls() bool {
|
|||||||
return false
|
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 {
|
func (b Branch) IsShort() bool {
|
||||||
switch len(b.block) {
|
switch len(b.block) {
|
||||||
case 0:
|
case 0:
|
||||||
|
@ -5,35 +5,35 @@ package ifelse
|
|||||||
type BranchKind int
|
type BranchKind int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// Empty branches do nothing
|
// Empty branches do nothing.
|
||||||
Empty BranchKind = iota
|
Empty BranchKind = iota
|
||||||
|
|
||||||
// Return branches return from the current function
|
// Return branches return from the current function.
|
||||||
Return
|
Return
|
||||||
|
|
||||||
// Continue branches continue a surrounding "for" loop
|
// Continue branches continue a surrounding "for" loop.
|
||||||
Continue
|
Continue
|
||||||
|
|
||||||
// Break branches break a surrounding "for" loop
|
// Break branches break a surrounding "for" loop.
|
||||||
Break
|
Break
|
||||||
|
|
||||||
// Goto branches conclude with a "goto" statement
|
// Goto branches conclude with a "goto" statement.
|
||||||
Goto
|
Goto
|
||||||
|
|
||||||
// Panic branches panic the current function
|
// Panic branches panic the current function.
|
||||||
Panic
|
Panic
|
||||||
|
|
||||||
// Exit branches end the program
|
// Exit branches end the program.
|
||||||
Exit
|
Exit
|
||||||
|
|
||||||
// Regular branches do not fit any category above
|
// Regular branches do not fit any category above.
|
||||||
Regular
|
Regular
|
||||||
)
|
)
|
||||||
|
|
||||||
// IsEmpty tests if the branch is empty
|
// IsEmpty tests if the branch is empty.
|
||||||
func (k BranchKind) IsEmpty() bool { return k == 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 }
|
func (k BranchKind) Returns() bool { return k == Return }
|
||||||
|
|
||||||
// Deviates tests if the control does not flow to the first
|
// Deviates tests if the control does not flow to the first
|
||||||
@ -48,10 +48,10 @@ func (k BranchKind) Deviates() bool {
|
|||||||
panic("invalid kind")
|
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} }
|
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 {
|
func (k BranchKind) String() string {
|
||||||
switch k {
|
switch k {
|
||||||
case Empty:
|
case Empty:
|
||||||
@ -74,7 +74,7 @@ func (k BranchKind) String() string {
|
|||||||
panic("invalid kind")
|
panic("invalid kind")
|
||||||
}
|
}
|
||||||
|
|
||||||
// LongString returns a longer form string representation
|
// LongString returns a longer form string representation.
|
||||||
func (k BranchKind) LongString() string {
|
func (k BranchKind) LongString() string {
|
||||||
switch k {
|
switch k {
|
||||||
case Empty:
|
case Empty:
|
||||||
|
@ -40,7 +40,7 @@ func ExprCall(expr *ast.ExprStmt) (Call, bool) {
|
|||||||
return Call{}, false
|
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 {
|
func (f Call) String() string {
|
||||||
if f.Pkg != "" {
|
if f.Pkg != "" {
|
||||||
return fmt.Sprintf("%s.%s", f.Pkg, f.Name)
|
return fmt.Sprintf("%s.%s", f.Pkg, f.Name)
|
||||||
|
@ -6,10 +6,10 @@ import "go/ast"
|
|||||||
type Target int
|
type Target int
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// TargetIf means the text refers to the "if"
|
// TargetIf means the text refers to the "if".
|
||||||
TargetIf Target = iota
|
TargetIf Target = iota
|
||||||
|
|
||||||
// TargetElse means the text refers to the "else"
|
// TargetElse means the text refers to the "else".
|
||||||
TargetElse
|
TargetElse
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -21,7 +21,7 @@ type RuleConfig struct {
|
|||||||
excludeFilters []*FileFilter
|
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 {
|
func (rc *RuleConfig) Initialize() error {
|
||||||
for _, f := range rc.Exclude {
|
for _, f := range rc.Exclude {
|
||||||
ff, err := ParseFileFilter(f)
|
ff, err := ParseFileFilter(f)
|
||||||
@ -36,7 +36,7 @@ func (rc *RuleConfig) Initialize() error {
|
|||||||
// RulesConfig defines the config for all rules.
|
// RulesConfig defines the config for all rules.
|
||||||
type RulesConfig = map[string]RuleConfig
|
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 {
|
func (rc *RuleConfig) MustExclude(name string) bool {
|
||||||
for _, exclude := range rc.excludeFilters {
|
for _, exclude := range rc.excludeFilters {
|
||||||
if exclude.MatchFileName(name) {
|
if exclude.MatchFileName(name) {
|
||||||
|
@ -53,7 +53,7 @@ const (
|
|||||||
type FailureCategory string
|
type FailureCategory string
|
||||||
|
|
||||||
const (
|
const (
|
||||||
// SeverityWarning declares failures of type warning
|
// SeverityWarning declares failures of type warning.
|
||||||
SeverityWarning = "warning"
|
SeverityWarning = "warning"
|
||||||
// SeverityError declares failures of type error.
|
// SeverityError declares failures of type error.
|
||||||
SeverityError = "error"
|
SeverityError = "error"
|
||||||
@ -62,7 +62,7 @@ const (
|
|||||||
// Severity is the type for the failure types.
|
// Severity is the type for the failure types.
|
||||||
type Severity string
|
type Severity string
|
||||||
|
|
||||||
// FailurePosition returns the failure position
|
// FailurePosition returns the failure position.
|
||||||
type FailurePosition struct {
|
type FailurePosition struct {
|
||||||
Start token.Position
|
Start token.Position
|
||||||
End token.Position
|
End token.Position
|
||||||
|
@ -29,7 +29,7 @@ func (f *File) Content() []byte {
|
|||||||
return f.content
|
return f.content
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFile creates a new file
|
// NewFile creates a new file.
|
||||||
func NewFile(name string, content []byte, pkg *Package) (*File, error) {
|
func NewFile(name string, content []byte, pkg *Package) (*File, error) {
|
||||||
f, err := parser.ParseFile(pkg.fset, name, content, parser.ParseComments)
|
f, err := parser.ParseFile(pkg.fset, name, content, parser.ParseComments)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -73,7 +73,7 @@ var basicTypeKinds = map[types.BasicKind]string{
|
|||||||
|
|
||||||
// IsUntypedConst reports whether expr is an untyped constant,
|
// IsUntypedConst reports whether expr is an untyped constant,
|
||||||
// and indicates what its default type is.
|
// 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) {
|
func (f *File) IsUntypedConst(expr ast.Expr) (defType string, ok bool) {
|
||||||
// Re-evaluate expr outside its context to see if it's untyped.
|
// 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.)
|
// (An expr evaluated within, for example, an assignment context will get the type of the LHS.)
|
||||||
|
@ -6,12 +6,12 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
// FileFilter - file filter to exclude some files for rule
|
// FileFilter filters file to exclude some files for a rule.
|
||||||
// supports whole
|
// Supports the following:
|
||||||
// 1. file/dir names : pkg/mypkg/my.go,
|
// - File or directory names: pkg/mypkg/my.go
|
||||||
// 2. globs: **/*.pb.go,
|
// - Globs: **/*.pb.go,
|
||||||
// 3. regexes (~ prefix) ~-tmp\.\d+\.go
|
// - Regexes (with ~ prefix): ~-tmp\.\d+\.go
|
||||||
// 4. special test marker `TEST` - treats as `~_test\.go`
|
// - Special test marker `TEST` (treated as `~_test\.go`).
|
||||||
type FileFilter struct {
|
type FileFilter struct {
|
||||||
// raw definition of filter inside config
|
// raw definition of filter inside config
|
||||||
raw string
|
raw string
|
||||||
@ -23,10 +23,10 @@ type FileFilter struct {
|
|||||||
matchesNothing bool
|
matchesNothing bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// ParseFileFilter - creates [FileFilter] for given raw filter
|
// ParseFileFilter creates a [FileFilter] for the given raw filter.
|
||||||
// if empty string, it matches nothing
|
// If the string is empty, it matches nothing.
|
||||||
// if `*`, or `~`, it matches everything
|
// If the string is `*` or `~`, it matches everything.
|
||||||
// while regexp could be invalid, it could return it's compilation error
|
// If the regular expression is invalid, it returns a compilation error.
|
||||||
func ParseFileFilter(rawFilter string) (*FileFilter, error) {
|
func ParseFileFilter(rawFilter string) (*FileFilter, error) {
|
||||||
rawFilter = strings.TrimSpace(rawFilter)
|
rawFilter = strings.TrimSpace(rawFilter)
|
||||||
result := new(FileFilter)
|
result := new(FileFilter)
|
||||||
@ -43,7 +43,7 @@ func ParseFileFilter(rawFilter string) (*FileFilter, error) {
|
|||||||
|
|
||||||
func (ff *FileFilter) String() string { return ff.raw }
|
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 {
|
func (ff *FileFilter) MatchFileName(name string) bool {
|
||||||
if ff.matchesAll {
|
if ff.matchesAll {
|
||||||
return true
|
return true
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
package lint
|
package lint
|
||||||
|
|
||||||
// FormatterMetadata configuration of a formatter
|
// FormatterMetadata configuration of a formatter.
|
||||||
type FormatterMetadata struct {
|
type FormatterMetadata struct {
|
||||||
Name string
|
Name string
|
||||||
Description string
|
Description string
|
||||||
Sample string
|
Sample string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Formatter defines an interface for failure formatters
|
// Formatter defines an interface for failure formatters.
|
||||||
type Formatter interface {
|
type Formatter interface {
|
||||||
Format(<-chan Failure, Config) (string, error)
|
Format(<-chan Failure, Config) (string, error)
|
||||||
Name() string
|
Name() string
|
||||||
|
@ -25,7 +25,7 @@ type Linter struct {
|
|||||||
fileReadTokens chan struct{}
|
fileReadTokens chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// New creates a new Linter
|
// New creates a new Linter.
|
||||||
func New(reader ReadFile, maxOpenFiles int) Linter {
|
func New(reader ReadFile, maxOpenFiles int) Linter {
|
||||||
var fileReadTokens chan struct{}
|
var fileReadTokens chan struct{}
|
||||||
if maxOpenFiles > 0 {
|
if maxOpenFiles > 0 {
|
||||||
@ -215,7 +215,7 @@ func isGenerated(src []byte) bool {
|
|||||||
return false
|
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) {
|
func addInvalidFileFailure(filename, errStr string, failures chan Failure) {
|
||||||
position := getPositionInvalidFile(filename, errStr)
|
position := getPositionInvalidFile(filename, errStr)
|
||||||
failures <- Failure{
|
failures <- Failure{
|
||||||
@ -226,12 +226,14 @@ func addInvalidFileFailure(filename, errStr string, failures chan Failure) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// errPosRegexp matches with an NewFile error message
|
// errPosRegexp matches with a NewFile error message:
|
||||||
// i.e. : corrupted.go:10:4: expected '}', found 'EOF
|
//
|
||||||
// first group matches the line and the second group, the column
|
// 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*):.*$`)
|
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 {
|
func getPositionInvalidFile(filename, s string) FailurePosition {
|
||||||
pos := errPosRegexp.FindStringSubmatch(s)
|
pos := errPosRegexp.FindStringSubmatch(s)
|
||||||
if len(pos) < 3 {
|
if len(pos) < 3 {
|
||||||
|
@ -2,7 +2,7 @@ package lint
|
|||||||
|
|
||||||
import "testing"
|
import "testing"
|
||||||
|
|
||||||
// TestName tests Name function
|
// TestName tests Name function.
|
||||||
func TestName(t *testing.T) {
|
func TestName(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name, want string
|
name, want string
|
||||||
|
@ -34,13 +34,13 @@ var (
|
|||||||
trueValue = 1
|
trueValue = 1
|
||||||
falseValue = 2
|
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"))
|
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"))
|
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"))
|
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"))
|
Go124 = goversion.Must(goversion.NewVersion("1.24"))
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -73,7 +73,7 @@ func (p *Package) IsMain() bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// TypesPkg yields information on this package
|
// TypesPkg yields information on this package.
|
||||||
func (p *Package) TypesPkg() *types.Package {
|
func (p *Package) TypesPkg() *types.Package {
|
||||||
p.mu.RLock()
|
p.mu.RLock()
|
||||||
defer p.mu.RUnlock()
|
defer p.mu.RUnlock()
|
||||||
@ -81,7 +81,7 @@ func (p *Package) TypesPkg() *types.Package {
|
|||||||
return p.typesPkg
|
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 {
|
func (p *Package) TypesInfo() *types.Info {
|
||||||
p.mu.RLock()
|
p.mu.RLock()
|
||||||
defer p.mu.RUnlock()
|
defer p.mu.RUnlock()
|
||||||
@ -89,7 +89,7 @@ func (p *Package) TypesInfo() *types.Info {
|
|||||||
return p.typesInfo
|
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 {
|
func (p *Package) Sortable() map[string]bool {
|
||||||
p.mu.RLock()
|
p.mu.RLock()
|
||||||
defer p.mu.RUnlock()
|
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
|
// 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) {
|
func check(config *types.Config, n string, fset *token.FileSet, astFiles []*ast.File, info *types.Info) (p *types.Package, err error) {
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
@ -213,7 +213,7 @@ func (p *Package) lint(rules []Rule, config Config, failures chan Failure) error
|
|||||||
return eg.Wait()
|
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 {
|
func (p *Package) IsAtLeastGoVersion(v *goversion.Version) bool {
|
||||||
p.mu.RLock()
|
p.mu.RLock()
|
||||||
defer p.mu.RUnlock()
|
defer p.mu.RUnlock()
|
||||||
|
@ -11,7 +11,7 @@ type DisabledInterval struct {
|
|||||||
RuleName string
|
RuleName string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rule defines an abstract rule interface
|
// Rule defines an abstract rule interface.
|
||||||
type Rule interface {
|
type Rule interface {
|
||||||
Name() string
|
Name() string
|
||||||
Apply(*File, Arguments) []Failure
|
Apply(*File, Arguments) []Failure
|
||||||
|
@ -12,7 +12,7 @@ const logFile = "revive.log"
|
|||||||
var logger *slog.Logger
|
var logger *slog.Logger
|
||||||
|
|
||||||
// GetLogger retrieves an instance of an application logger which outputs
|
// 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) {
|
func GetLogger() (*slog.Logger, error) {
|
||||||
if logger != nil {
|
if logger != nil {
|
||||||
return logger, nil
|
return logger, nil
|
||||||
|
@ -68,7 +68,7 @@ func New(
|
|||||||
}, nil
|
}, 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) {
|
func (r *Revive) Lint(patterns ...*LintPattern) (<-chan lint.Failure, error) {
|
||||||
includePatterns := []string{}
|
includePatterns := []string{}
|
||||||
excludePatterns := []string{}
|
excludePatterns := []string{}
|
||||||
|
@ -1,29 +1,29 @@
|
|||||||
package revivelib
|
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 {
|
type LintPattern struct {
|
||||||
isExclude bool
|
isExclude bool
|
||||||
pattern string
|
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 {
|
func (p *LintPattern) IsExclude() bool {
|
||||||
return p.isExclude
|
return p.isExclude
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPattern - returns the actual pattern
|
// GetPattern returns the actual pattern
|
||||||
//
|
//
|
||||||
// Deprecated: Use [Pattern].
|
// Deprecated: Use [Pattern].
|
||||||
func (p *LintPattern) GetPattern() string {
|
func (p *LintPattern) GetPattern() string {
|
||||||
return p.Pattern()
|
return p.Pattern()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pattern - returns the actual pattern
|
// Pattern returns the actual pattern.
|
||||||
func (p *LintPattern) Pattern() string {
|
func (p *LintPattern) Pattern() string {
|
||||||
return p.pattern
|
return p.pattern
|
||||||
}
|
}
|
||||||
|
|
||||||
// Include this pattern when linting
|
// Include this pattern when linting.
|
||||||
func Include(pattern string) *LintPattern {
|
func Include(pattern string) *LintPattern {
|
||||||
return &LintPattern{
|
return &LintPattern{
|
||||||
isExclude: false,
|
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 {
|
func Exclude(pattern string) *LintPattern {
|
||||||
return &LintPattern{
|
return &LintPattern{
|
||||||
isExclude: true,
|
isExclude: true,
|
||||||
|
@ -50,12 +50,12 @@ func (r *BannedCharsRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failur
|
|||||||
return failures
|
return failures
|
||||||
}
|
}
|
||||||
|
|
||||||
// Name returns the rule name
|
// Name returns the rule name.
|
||||||
func (*BannedCharsRule) Name() string {
|
func (*BannedCharsRule) Name() string {
|
||||||
return bannedCharsRuleName
|
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) {
|
func (r *BannedCharsRule) getBannedCharsList(args lint.Arguments) ([]string, error) {
|
||||||
var bannedChars []string
|
var bannedChars []string
|
||||||
for _, char := range args {
|
for _, char := range args {
|
||||||
@ -74,7 +74,7 @@ type lintBannedCharsRule struct {
|
|||||||
onFailure func(lint.Failure)
|
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 {
|
func (w lintBannedCharsRule) Visit(node ast.Node) ast.Visitor {
|
||||||
n, ok := node.(*ast.Ident)
|
n, ok := node.(*ast.Ident)
|
||||||
if !ok {
|
if !ok {
|
||||||
|
@ -42,7 +42,7 @@ func (w lintBareReturnRule) Visit(node ast.Node) ast.Visitor {
|
|||||||
return w
|
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) {
|
func (w lintBareReturnRule) checkFunc(results *ast.FieldList, body *ast.BlockStmt) {
|
||||||
hasNamedResults := results != nil && len(results.List) > 0 && results.List[0].Names != nil
|
hasNamedResults := results != nil && len(results.List) > 0 && results.List[0].Names != nil
|
||||||
if !hasNamedResults || body == nil {
|
if !hasNamedResults || body == nil {
|
||||||
|
@ -8,7 +8,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// CommentSpacingsRule check whether there is a space between
|
// 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 {
|
type CommentSpacingsRule struct {
|
||||||
allowList []string
|
allowList []string
|
||||||
}
|
}
|
||||||
|
@ -44,7 +44,7 @@ func (ps *packages) methodNames(lp *lint.Package) pkgMethods {
|
|||||||
|
|
||||||
var allPkgs = packages{pkgs: make([]pkgMethods, 1)}
|
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{}
|
type ConfusingNamingRule struct{}
|
||||||
|
|
||||||
// Apply applies the rule to given file.
|
// Apply applies the rule to given file.
|
||||||
@ -127,7 +127,7 @@ type lintConfusingNames struct {
|
|||||||
|
|
||||||
const defaultStructName = "_" // used to map functions
|
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 {
|
func getStructName(r *ast.FieldList) string {
|
||||||
result := defaultStructName
|
result := defaultStructName
|
||||||
|
|
||||||
|
@ -7,7 +7,7 @@ import (
|
|||||||
"github.com/mgechev/revive/lint"
|
"github.com/mgechev/revive/lint"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConfusingResultsRule lints given function declarations
|
// ConfusingResultsRule lints given function declarations.
|
||||||
type ConfusingResultsRule struct{}
|
type ConfusingResultsRule struct{}
|
||||||
|
|
||||||
// Apply applies the rule to given file.
|
// Apply applies the rule to given file.
|
||||||
|
@ -88,7 +88,7 @@ type lintErrorStrings struct {
|
|||||||
onFailure func(lint.Failure)
|
onFailure func(lint.Failure)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Visit browses the AST
|
// Visit browses the AST.
|
||||||
func (w lintErrorStrings) Visit(n ast.Node) ast.Visitor {
|
func (w lintErrorStrings) Visit(n ast.Node) ast.Visitor {
|
||||||
ce, ok := n.(*ast.CallExpr)
|
ce, ok := n.(*ast.CallExpr)
|
||||||
if !ok {
|
if !ok {
|
||||||
@ -126,8 +126,8 @@ func (w lintErrorStrings) Visit(n ast.Node) ast.Visitor {
|
|||||||
return w
|
return w
|
||||||
}
|
}
|
||||||
|
|
||||||
// match returns true if the expression corresponds to the known pkg.function
|
// match returns true if the expression corresponds to the known pkg.function,
|
||||||
// i.e.: errors.Wrap
|
// i.e.: errors.Wrap.
|
||||||
func (w lintErrorStrings) match(expr *ast.CallExpr) bool {
|
func (w lintErrorStrings) match(expr *ast.CallExpr) bool {
|
||||||
sel, ok := expr.Fun.(*ast.SelectorExpr)
|
sel, ok := expr.Fun.(*ast.SelectorExpr)
|
||||||
if !ok {
|
if !ok {
|
||||||
@ -147,8 +147,8 @@ func (w lintErrorStrings) match(expr *ast.CallExpr) bool {
|
|||||||
return ok
|
return ok
|
||||||
}
|
}
|
||||||
|
|
||||||
// getMessage returns the message depending on its position
|
// getMessage returns the message depending on its position.
|
||||||
// returns false if the cast is unsuccessful
|
// Returns false if the cast is unsuccessful.
|
||||||
func (w lintErrorStrings) getMessage(expr *ast.CallExpr) (s *ast.BasicLit, success bool) {
|
func (w lintErrorStrings) getMessage(expr *ast.CallExpr) (s *ast.BasicLit, success bool) {
|
||||||
str, ok := w.checkArg(expr, 0)
|
str, ok := w.checkArg(expr, 0)
|
||||||
if ok {
|
if ok {
|
||||||
|
@ -12,7 +12,7 @@ import (
|
|||||||
"github.com/mgechev/revive/lint"
|
"github.com/mgechev/revive/lint"
|
||||||
)
|
)
|
||||||
|
|
||||||
// disabledChecks store ignored warnings types
|
// disabledChecks store ignored warnings types.
|
||||||
type disabledChecks struct {
|
type disabledChecks struct {
|
||||||
Const bool
|
Const bool
|
||||||
Function bool
|
Function bool
|
||||||
@ -30,7 +30,7 @@ const (
|
|||||||
checkNameStuttering = "stuttering"
|
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 {
|
func (dc *disabledChecks) isDisabled(checkName string) bool {
|
||||||
switch checkName {
|
switch checkName {
|
||||||
case "var":
|
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 {
|
func (w *lintExported) checkValueNames(names []*ast.Ident, nodeToBlame ast.Node, kind string) bool {
|
||||||
// Check that none are exported except for the first.
|
// Check that none are exported except for the first.
|
||||||
if len(names) < 2 {
|
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 {
|
func (w *lintExported) mustCheckMethod(fn *ast.FuncDecl) bool {
|
||||||
recv := typeparams.ReceiverType(fn)
|
recv := typeparams.ReceiverType(fn)
|
||||||
|
|
||||||
|
@ -9,7 +9,7 @@ import (
|
|||||||
"github.com/mgechev/revive/lint"
|
"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 {
|
type FilenameFormatRule struct {
|
||||||
format *regexp.Regexp
|
format *regexp.Regexp
|
||||||
}
|
}
|
||||||
|
@ -66,7 +66,7 @@ type importShadowing struct {
|
|||||||
skipIdents map[*ast.Ident]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 {
|
func (w importShadowing) Visit(n ast.Node) ast.Visitor {
|
||||||
switch n := n.(type) {
|
switch n := n.(type) {
|
||||||
case *ast.AssignStmt:
|
case *ast.AssignStmt:
|
||||||
|
@ -9,7 +9,7 @@ import (
|
|||||||
"github.com/mgechev/revive/lint"
|
"github.com/mgechev/revive/lint"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RangeValAddress lints
|
// RangeValAddress warns if address of range value is used dangerously.
|
||||||
type RangeValAddress struct{}
|
type RangeValAddress struct{}
|
||||||
|
|
||||||
// Apply applies the rule to given file.
|
// Apply applies the rule to given file.
|
||||||
|
@ -11,7 +11,7 @@ import (
|
|||||||
"github.com/mgechev/revive/lint"
|
"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 {
|
type StringFormatRule struct {
|
||||||
rules []stringFormatSubrule
|
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)
|
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]*"
|
const identRegex = "[_A-Za-z][_A-Za-z0-9]*"
|
||||||
|
|
||||||
var parseStringFormatScope = regexp.MustCompile(
|
var parseStringFormatScope = regexp.MustCompile(
|
||||||
@ -165,17 +165,17 @@ func (r *StringFormatRule) parseArgument(argument any, ruleNum int) (scopes stri
|
|||||||
return scopes, regex, negated, errorMessage, nil
|
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 {
|
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)
|
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 {
|
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)
|
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 {
|
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)
|
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 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) {
|
func (*lintStringFormatRule) getCallName(call *ast.CallExpr) (callName string, ok bool) {
|
||||||
if ident, ok := call.Fun.(*ast.Ident); ok {
|
if ident, ok := call.Fun.(*ast.Ident); ok {
|
||||||
// Local function call
|
// Local function call
|
||||||
@ -227,7 +227,7 @@ func (*lintStringFormatRule) getCallName(call *ast.CallExpr) (callName string, o
|
|||||||
return "", false
|
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) {
|
func (r *stringFormatSubrule) apply(call *ast.CallExpr, scope *stringFormatSubruleScope) {
|
||||||
if len(call.Args) <= scope.argument {
|
if len(call.Args) <= scope.argument {
|
||||||
return
|
return
|
||||||
|
@ -38,7 +38,6 @@ const (
|
|||||||
|
|
||||||
type tagChecker func(checkCtx *checkContext, tag *structtag.Tag, fieldType ast.Expr) (message string, succeeded bool)
|
type tagChecker func(checkCtx *checkContext, tag *structtag.Tag, fieldType ast.Expr) (message string, succeeded bool)
|
||||||
|
|
||||||
// populate tag checkers map
|
|
||||||
var tagCheckers = map[tagKey]tagChecker{
|
var tagCheckers = map[tagKey]tagChecker{
|
||||||
keyASN1: checkASN1Tag,
|
keyASN1: checkASN1Tag,
|
||||||
keyBSON: checkBSONTag,
|
keyBSON: checkBSONTag,
|
||||||
@ -757,7 +756,8 @@ var validateSingleOptions = map[string]struct{}{
|
|||||||
"uuid5_rfc4122": {},
|
"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>
|
// <option> = <RHS>
|
||||||
var validateLHS = map[string]struct{}{
|
var validateLHS = map[string]struct{}{
|
||||||
"contains": {},
|
"contains": {},
|
||||||
|
@ -41,7 +41,7 @@ type lintTimeDate struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
// timeDateArgumentNames are the names of the arguments of time.Date
|
// timeDateArgumentNames are the names of the arguments of time.Date.
|
||||||
timeDateArgumentNames = []string{
|
timeDateArgumentNames = []string{
|
||||||
"year",
|
"year",
|
||||||
"month",
|
"month",
|
||||||
@ -53,7 +53,7 @@ var (
|
|||||||
"timezone",
|
"timezone",
|
||||||
}
|
}
|
||||||
|
|
||||||
// timeDateArity is the number of arguments of time.Date
|
// timeDateArity is the number of arguments of time.Date.
|
||||||
timeDateArity = len(timeDateArgumentNames)
|
timeDateArity = len(timeDateArgumentNames)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -9,7 +9,7 @@ import (
|
|||||||
"github.com/mgechev/revive/lint"
|
"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{}
|
type TimeEqualRule struct{}
|
||||||
|
|
||||||
// Apply applies the rule to given file.
|
// Apply applies the rule to given 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) {
|
func (w *lintUncheckedTypeAssertion) handleReturn(n *ast.ReturnStmt) {
|
||||||
for _, r := range n.Results {
|
for _, r := range n.Results {
|
||||||
w.requireNoTypeAssert(r)
|
w.requireNoTypeAssert(r)
|
||||||
|
@ -79,10 +79,10 @@ type lintUnconditionalRecursionRule struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Visit will traverse function's body we search for calls to the function itself.
|
// 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 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)
|
// 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 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
|
// 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.
|
// 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 {
|
func (w *lintUnconditionalRecursionRule) Visit(node ast.Node) ast.Visitor {
|
||||||
switch n := node.(type) {
|
switch n := node.(type) {
|
||||||
|
@ -35,7 +35,7 @@ func srcLine(src []byte, p token.Position) string {
|
|||||||
return string(src[lo:hi])
|
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 {
|
func checkNumberOfArguments(expected int, args lint.Arguments, ruleName string) error {
|
||||||
if len(args) < expected {
|
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))
|
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.
|
// 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 {
|
func normalizeRuleOption(arg string) string {
|
||||||
return strings.ToLower(strings.ReplaceAll(arg, "-", ""))
|
return strings.ToLower(strings.ReplaceAll(arg, "-", ""))
|
||||||
}
|
}
|
||||||
@ -66,7 +66,7 @@ func isCallToExitFunction(pkgName, functionName string) bool {
|
|||||||
return exitFunctions[pkgName] != nil && exitFunctions[pkgName][functionName]
|
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 {
|
func newInternalFailureError(e error) []lint.Failure {
|
||||||
return []lint.Failure{lint.NewInternalFailure(e.Error())}
|
return []lint.Failure{lint.NewInternalFailure(e.Error())}
|
||||||
}
|
}
|
||||||
|
@ -7,7 +7,7 @@ import (
|
|||||||
"github.com/mgechev/revive/rule"
|
"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) {
|
func TestOptimizeOperandsOrder(t *testing.T) {
|
||||||
testRule(t, "optimize_operands_order", &rule.OptimizeOperandsOrderRule{}, &lint.RuleConfig{})
|
testRule(t, "optimize_operands_order", &rule.OptimizeOperandsOrderRule{}, &lint.RuleConfig{})
|
||||||
}
|
}
|
||||||
|
@ -17,7 +17,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
// configureRule configures the given rule with the given configuration
|
// 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) {
|
func configureRule(t *testing.T, rule lint.Rule, arguments lint.Arguments) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
|
|
||||||
@ -151,7 +151,7 @@ type instruction struct {
|
|||||||
Confidence float64 // confidence level
|
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 {
|
type JSONInstruction struct {
|
||||||
Match string `json:"MATCH"`
|
Match string `json:"MATCH"`
|
||||||
Category string `json:"Category"`
|
Category string `json:"Category"`
|
||||||
@ -277,7 +277,7 @@ func srcLine(src []byte, p token.Position) string {
|
|||||||
return string(src[lo:hi])
|
return string(src[lo:hi])
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestLine tests srcLine function
|
// TestLine tests srcLine function.
|
||||||
func TestLine(t *testing.T) {
|
func TestLine(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
src string
|
src string
|
||||||
@ -319,7 +319,7 @@ func exportedType(typ types.Type) bool {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// TestExportedType tests exportedType function
|
// TestExportedType tests exportedType function.
|
||||||
func TestExportedType(t *testing.T) {
|
func TestExportedType(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
typString string
|
typString string
|
||||||
|
Reference in New Issue
Block a user