Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 32 additions & 33 deletions cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"strings"

"github.com/fatih/color"
"github.com/spf13/afero"

"github.com/mgechev/revive/config"
"github.com/mgechev/revive/internal/timing"
Expand All @@ -32,15 +31,23 @@ var (
commit = defaultCommit
date = defaultDate
builtBy = defaultBuilder
// AppFs is used for operations related to user config files.
AppFs = afero.NewOsFs()
)

type options struct {
configPath string
excludePatterns revivelib.ArrayFlags
formatterName string
version bool
setExitStatus bool
maxOpenFiles int
}

// RunRevive runs the CLI for revive.
func RunRevive(extraRules ...revivelib.ExtraRule) {
// Move parsing flags outside of init(); otherwise, tests don't work properly.
// More info: https://github.com/golang/go/issues/46869#issuecomment-865695953
if err := initConfig(); err != nil {
opts, err := initConfig()
if err != nil {
// Same exit codes as flag.ExitOnError.
exitCode := 2
if errors.Is(err, flag.ErrHelp) {
Expand All @@ -49,7 +56,7 @@ func RunRevive(extraRules ...revivelib.ExtraRule) {
os.Exit(exitCode) //revive:disable-line:deep-exit
}

if versionFlag {
if opts.version {
fmt.Print(getVersion(builtBy, date, commit, version))
return
}
Expand All @@ -61,7 +68,7 @@ func RunRevive(extraRules ...revivelib.ExtraRule) {
}

doneTotal := timing.Track(logger, "total")
exitCode, err := runRevive(logger, extraRules...)
exitCode, err := runRevive(logger, opts, extraRules...)
doneTotal("error", err)
if err != nil {
fmt.Fprintln(os.Stderr, err)
Expand All @@ -71,9 +78,9 @@ func RunRevive(extraRules ...revivelib.ExtraRule) {
os.Exit(exitCode) //revive:disable-line:deep-exit
}

func runRevive(logger *slog.Logger, extraRules ...revivelib.ExtraRule) (int, error) {
doneConfig := timing.Track(logger, "config-load", "config", configPath)
conf, err := config.GetConfig(configPath)
func runRevive(logger *slog.Logger, opts options, extraRules ...revivelib.ExtraRule) (int, error) {
doneConfig := timing.Track(logger, "config-load", "config", opts.configPath)
conf, err := config.GetConfig(opts.configPath)
if err != nil {
doneConfig("error", err)
return 0, err
Expand All @@ -82,8 +89,8 @@ func runRevive(logger *slog.Logger, extraRules ...revivelib.ExtraRule) (int, err

revive, err := revivelib.New(
conf,
setExitStatus,
maxOpenFiles,
opts.setExitStatus,
opts.maxOpenFiles,
extraRules...,
)
if err != nil {
Expand All @@ -97,7 +104,7 @@ func runRevive(logger *slog.Logger, extraRules ...revivelib.ExtraRule) (int, err
packages = append(packages, revivelib.Include(file))
}

for _, file := range excludePatterns {
for _, file := range opts.excludePatterns {
packages = append(packages, revivelib.Exclude(file))
}

Expand All @@ -106,7 +113,7 @@ func runRevive(logger *slog.Logger, extraRules ...revivelib.ExtraRule) (int, err
return 0, err
}

output, exitCode, err := revive.Format(formatterName, failures)
output, exitCode, err := revive.Format(opts.formatterName, failures)
if err != nil {
return 0, err
}
Expand All @@ -118,17 +125,6 @@ func runRevive(logger *slog.Logger, extraRules ...revivelib.ExtraRule) (int, err
return exitCode, nil
}

var (
configPath string
excludePatterns revivelib.ArrayFlags
formatterName string
versionFlag bool
setExitStatus bool
maxOpenFiles int
)

var originalUsage = flag.Usage

func logo() string {
return color.YellowString(` _ __ _____ _(_)__ _____
| '__/ _ \ \ / / \ \ / / _ \
Expand Down Expand Up @@ -171,11 +167,12 @@ func buildDefaultConfigPath() string {
return result
}

func initConfig() error {
func initConfig() (options, error) {
if os.Getenv("REVIVE_FORCE_COLOR") == "1" {
color.NoColor = false //nolint:reassign // We want to reassign the default value of NoColor to force colorizing for non-TTY environments.
}

originalUsage := flag.Usage
flag.Usage = func() { //nolint:reassign // We want to reassign the default usage function to print our banner.
fmt.Println(banner())
originalUsage()
Expand All @@ -193,15 +190,17 @@ func initConfig() error {

defaultConfigPath := buildDefaultConfigPath()

flag.StringVar(&configPath, "config", defaultConfigPath, configUsage)
flag.Var(&excludePatterns, "exclude", excludeUsage)
flag.StringVar(&formatterName, "formatter", "", formatterUsage)
flag.BoolVar(&versionFlag, "version", false, versionUsage)
flag.BoolVar(&setExitStatus, "set_exit_status", false, exitStatusUsage)
flag.IntVar(&maxOpenFiles, "max_open_files", 0, maxOpenFilesUsage)
var opts options
flag.StringVar(&opts.configPath, "config", defaultConfigPath, configUsage)
flag.Var(&opts.excludePatterns, "exclude", excludeUsage)
flag.StringVar(&opts.formatterName, "formatter", "", formatterUsage)
flag.BoolVar(&opts.version, "version", false, versionUsage)
flag.BoolVar(&opts.setExitStatus, "set_exit_status", false, exitStatusUsage)
flag.IntVar(&opts.maxOpenFiles, "max_open_files", 0, maxOpenFilesUsage)

flag.CommandLine.Init(os.Args[0], flag.ContinueOnError)
return flag.CommandLine.Parse(os.Args[1:])
err := flag.CommandLine.Parse(os.Args[1:])
return opts, err
}

// getVersion returns build info (version, commit, date, and builtBy).
Expand Down Expand Up @@ -229,6 +228,6 @@ func getVersion(builtBy, date, commit, version string) string {
}

func fileExist(path string) bool {
_, err := AppFs.Stat(path)
_, err := os.Stat(path) //nolint:gosec // ignore G703: path is the user config location from $XDG_CONFIG_HOME or $HOME
return err == nil
}
2 changes: 0 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ require (
github.com/fatih/structtag v1.2.0
github.com/hashicorp/go-version v1.9.0
github.com/revive-lint/dots v1.1.0
github.com/spf13/afero v1.15.0
golang.org/x/mod v0.41.0
golang.org/x/sync v0.23.0
golang.org/x/tools v0.50.0
Expand All @@ -19,5 +18,4 @@ require (
github.com/mattn/go-colorable v0.1.14 // indirect
github.com/mattn/go-isatty v0.0.22 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.37.0 // indirect
)
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,11 @@ github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/revive-lint/dots v1.1.0 h1:lPzAYhkTbKSeXO+SEAgP6VFEcTG5yaQZyo2MH94TXp4=
github.com/revive-lint/dots v1.1.0/go.mod h1:UFUd5ptnAifP8PYMw8T9dq00JqM0F4BAEw8Y/erUfNk=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU=
golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0=
4 changes: 3 additions & 1 deletion lint/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,12 @@ type Package struct {
logger *slog.Logger
}

var (
const (
trueValue = 1
falseValue = 2
)

var (
// Go111 is a constant representing the Go version 1.11.
Go111 = goversion.Must(goversion.NewVersion("1.11"))
// Go115 is a constant representing the Go version 1.15.
Expand Down
17 changes: 9 additions & 8 deletions rule/defer.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@ import (
"github.com/mgechev/revive/lint"
)

var (
deferOptionLoop = config.NormalizeOption("loop")
deferOptionCallChain = config.NormalizeOption("callChain")
deferOptionMethodCall = config.NormalizeOption("methodCall")
deferOptionReturn = config.NormalizeOption("return")
deferOptionRecover = config.NormalizeOption("recover")
deferOptionImmediateRecover = config.NormalizeOption("immediateRecover")
deferOptionExitAfterDefer = config.NormalizeOption("exitAfterDefer")
// Subcase names normalized with [config.NormalizeOption].
const (
deferOptionLoop = "loop"
deferOptionCallChain = "callchain"
deferOptionMethodCall = "methodcall"
deferOptionReturn = "return"
deferOptionRecover = "recover"
deferOptionImmediateRecover = "immediaterecover"
deferOptionExitAfterDefer = "exitafterdefer"
)

// DeferRule lints gotchas in defer statements.
Expand Down
9 changes: 2 additions & 7 deletions rule/file_header.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,6 @@ type FileHeaderRule struct {
header string
}

var (
multiRegexp = regexp.MustCompile(`^/\*`)
singleRegexp = regexp.MustCompile("^//")
)

var _ lint.ConfigurableRule = (*FileHeaderRule)(nil)

// Configure validates the rule configuration, and configures the rule accordingly.
Expand Down Expand Up @@ -63,9 +58,9 @@ func (r *FileHeaderRule) Apply(file *lint.File, _ lint.Arguments) []lint.Failure
var comment strings.Builder
for _, c := range g.List {
text := c.Text
if multiRegexp.MatchString(text) {
if strings.HasPrefix(text, "/*") {
text = text[2 : len(text)-2]
} else if singleRegexp.MatchString(text) {
} else if strings.HasPrefix(text, "//") {
text = text[2:]
}
comment.WriteString(text)
Expand Down
7 changes: 4 additions & 3 deletions rule/get_return.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,10 @@ func (*GetReturnRule) Name() string {
return "get-return"
}

const getterPrefix = "GET"

var lenGetterPrefix = len(getterPrefix)
const (
getterPrefix = "GET"
lenGetterPrefix = len(getterPrefix)
)

func isGetter(name string) bool {
nameHasGetterPrefix := strings.HasPrefix(strings.ToUpper(name), getterPrefix)
Expand Down
28 changes: 13 additions & 15 deletions rule/time_date.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,22 +55,20 @@ const (
timeDateArgTimezone timeDateArgument = "timezone"
)

var (
// timeDateArgumentNames are the names of the arguments of [time.Date].
timeDateArgumentNames = []timeDateArgument{
timeDateArgYear,
timeDateArgMonth,
timeDateArgDay,
timeDateArgHour,
timeDateArgMinute,
timeDateArgSecond,
timeDateArgNanosecond,
timeDateArgTimezone,
}
// timeDateArgumentNames are the names of the arguments of [time.Date].
var timeDateArgumentNames = [...]timeDateArgument{
timeDateArgYear,
timeDateArgMonth,
timeDateArgDay,
timeDateArgHour,
timeDateArgMinute,
timeDateArgSecond,
timeDateArgNanosecond,
timeDateArgTimezone,
}

// timeDateArity is the number of arguments of [time.Date].
timeDateArity = len(timeDateArgumentNames)
)
// timeDateArity is the number of arguments of [time.Date].
const timeDateArity = len(timeDateArgumentNames)

var timeDateArgumentBoundaries = map[timeDateArgument][2]int{
// year is not validated
Expand Down
Loading