Categorygithub.com/shamwow/revive
repositorypackage
1.2.0
Repository: https://github.com/shamwow/revive.git
Documentation: pkg.go.dev

# Packages

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author

# README

Build Status

revive

Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. Revive provides a framework for development of custom rules, and lets you define a strict preset for enhancing your development & code review processes.


Logo by Georgi Serev

Here's how revive is different from golint:

  • Allows to enable or disable rules using a configuration file.
  • Allows to configure the linting rules with a TOML file.
  • 2x faster running the same rules as golint.
  • Provides functionality for disabling a specific rule or the entire linter for a file or a range of lines.
    • golint allows this only for generated files.
  • Optional type checking. Most rules in golint do not require type checking. If you disable them in the config file, revive will run over 6x faster than golint.
  • Provides multiple formatters which let us customize the output.
  • Allows to customize the return code for the entire linter or based on the failure of only some rules.
  • Everyone can extend it easily with custom rules or formatters.
  • Revive provides more rules compared to golint.

Who uses Revive

  • tidb - TiDB is a distributed HTAP database compatible with the MySQL protocol
  • grafana - The tool for beautiful monitoring and metric analytics & dashboards for Graphite, InfluxDB & Prometheus & More
  • etcd - Distributed reliable key-value store for the most critical data of a distributed system
  • ferret - Declarative web scraping
  • gopass - The slightly more awesome standard unix password manager for teams
  • gitea - Git with a cup of tea, painless self-hosted git service
  • excelize - Go library for reading and writing Microsoft Excel™ (XLSX) files
  • aurora - aurora is a web-based Beanstalk queue server console written in Go
  • soar - SQL Optimizer And Rewriter
  • gorush - A push notification server written in Go (Golang)a
  • go-echarts - The adorable charts library for Golang
  • reviewdog - Automated code review tool integrated with any code analysis tools regardless of programming language
  • sklearn - A partial port of scikit-learn written in Go
  • lorawan-stack - The Things Network Stack for LoRaWAN V3
  • gofight - Testing API Handler written in Golang.
  • ggz - An URL shortener service written in Golang
  • Codeac.io - Automated code review service integrates with GitHub, Bitbucket and GitLab (even self-hosted) and helps you fight technical debt.

Open a PR to add your project.

Usage

Since the default behavior of revive is compatible with golint, without providing any additional flags, the only difference you'd notice is faster execution.

revive supports a -config flag whose value should correspond to a TOML file describing which rules to use for revive's linting. If not provided, revive will try to use a global config file (assumed to be located at $HOME/revive.toml). Otherwise, if no configuration TOML file is found then revive uses a built-in set of default linting rules.

Bazel

If you want to use revive with Bazel, take a look at the rules that Atlassian maintains.

Text Editors

call ale#linter#Define('go', {
\   'name': 'revive',
\   'output_stream': 'both',
\   'executable': 'revive',
\   'read_buffer': 0,
\   'command': 'revive %t',
\   'callback': 'ale#handlers#unix#HandleAsWarning',
\})

GitHub Actions

Continuous Integration

Codeac.io - Automated code review service integrates with GitHub, Bitbucket and GitLab (even self-hosted) and helps you fight technical debt. Check your pull-requests with revive automatically. (free for open-source projects)

Installation

go get -u github.com/shamwow/revive

Command Line Flags

revive accepts three command line parameters:

  • -config [PATH] - path to config file in TOML format, defaults to $HOME/revive.toml if present.

  • -exclude [PATTERN] - pattern for files/directories/packages to be excluded for linting. You can specify the files you want to exclude for linting either as package name (i.e. github.com/shamwow/revive), list them as individual files (i.e. file.go), directories (i.e. ./foo/...), or any combination of the three.

  • -formatter [NAME] - formatter to be used for the output. The currently available formatters are:

    • default - will output the failures the same way that golint does.
    • json - outputs the failures in JSON format.
    • ndjson - outputs the failures as stream in newline delimited JSON (NDJSON) format.
    • friendly - outputs the failures when found. Shows summary of all the failures.
    • stylish - formats the failures in a table. Keep in mind that it doesn't stream the output so it might be perceived as slower compared to others.
    • checkstyle - outputs the failures in XML format compatible with that of Java's Checkstyle.

Sample Invocations

revive -config revive.toml -exclude file1.go -exclude file2.go -formatter friendly github.com/shamwow/revive package/...
  • The command above will use the configuration from revive.toml
  • revive will ignore file1.go and file2.go
  • The output will be formatted with the friendly formatter
  • The linter will analyze github.com/shamwow/revive and the files in package

Comment Directives

Using comments, you can disable the linter for the entire file or only range of lines:

//revive:disable

func Public() {}
//revive:enable

The snippet above, will disable revive between the revive:disable and revive:enable comments. If you skip revive:enable, the linter will be disabled for the rest of the file.

With revive:disable-next-line and revive:disable-line you can disable revive on a particular code line.

You can do the same on a rule level. In case you want to disable only a particular rule, you can use:

//revive:disable:unexported-return
func Public() private {
  return private
}
//revive:enable:unexported-return

This way, revive will not warn you for that you're returning an object of an unexported type, from an exported function.

You can document why you disable the linter by adding a trailing text in the directive, for example

//revive:disable Until the code is stable
//revive:disable:cyclomatic High complexity score but easy to understand 

You can also configure revive to enforce documenting linter disabling directives by adding

[directive.specify-disable-reason]

in the configuration. You can set the severity (defaults to warning) of the violation of this directive

[directive.specify-disable-reason]
    severity = "error"

Configuration

revive can be configured with a TOML file. Here's a sample configuration with explanation for the individual properties:

# When set to false, ignores files with "GENERATED" header, similar to golint
ignoreGeneratedHeader = true

# Sets the default severity to "warning"
severity = "warning"

# Sets the default failure confidence. This means that linting errors
# with less than 0.8 confidence will be ignored.
confidence = 0.8

# Sets the error code for failures with severity "error"
errorCode = 0

# Sets the error code for failures with severity "warning"
warningCode = 0

# Configuration of the `cyclomatic` rule. Here we specify that
# the rule should fail if it detects code with higher complexity than 10.
[rule.cyclomatic]
  arguments = [10]

# Sets the severity of the `package-comments` rule to "error".
[rule.package-comments]
  severity = "error"

Default Configuration

The default configuration of revive can be found at defaults.toml. This will enable all rules available in golint and use their default configuration (i.e. the way they are hardcoded in golint).

revive -config defaults.toml github.com/shamwow/revive

This will use the configuration file defaults.toml, the default formatter, and will run linting over the github.com/shamwow/revive package.

Custom Configuration

revive -config config.toml -formatter friendly github.com/shamwow/revive

This will use config.toml, the friendly formatter, and will run linting over the github.com/shamwow/revive package.

Recommended Configuration

The following snippet contains the recommended revive configuration that you can use in your project:

ignoreGeneratedHeader = false
severity = "warning"
confidence = 0.8
errorCode = 0
warningCode = 0

[rule.blank-imports]
[rule.context-as-argument]
[rule.context-keys-type]
[rule.dot-imports]
[rule.error-return]
[rule.error-strings]
[rule.error-naming]
[rule.exported]
[rule.if-return]
[rule.increment-decrement]
[rule.var-naming]
[rule.var-declaration]
[rule.package-comments]
[rule.range]
[rule.receiver-naming]
[rule.time-naming]
[rule.unexported-return]
[rule.indent-error-flow]
[rule.errorf]
[rule.empty-block]
[rule.superfluous-else]
[rule.unused-parameter]
[rule.unreachable-code]
[rule.redefines-builtin-id]

Available Rules

List of all available rules. The rules ported from golint are left unchanged and indicated in the golint column.

NameConfigDescriptiongolintTyped
context-keys-typen/aDisallows the usage of basic types in context.WithValue.yesyes
time-namingn/aConventions around the naming of time variables.yesyes
var-declarationn/aReduces redundancies around variable declaration.yesyes
unexported-returnn/aWarns when a public return is from unexported type.yesyes
errorfn/aShould replace errors.New(fmt.Sprintf()) with fmt.Errorf()yesyes
blank-importsn/aDisallows blank importsyesno
context-as-argumentn/acontext.Context should be the first argument of a function.yesno
dot-importsn/aForbids . imports.yesno
error-returnn/aThe error return parameter should be last.yesno
error-stringsn/aConventions around error strings.yesno
error-namingn/aNaming of error variables.yesno
exportedn/aNaming and commenting conventions on exported symbols.yesno
if-returnn/aRedundant if when returning an error.yesno
increment-decrementn/aUse i++ and i-- instead of i += 1 and i -= 1.yesno
var-namingwhitelist & blacklist of initialismsNaming rules.yesno
package-commentsn/aPackage commenting conventions.yesno
rangen/aPrevents redundant variables when iterating over a collection.yesno
receiver-namingn/aConventions around the naming of receivers.yesno
indent-error-flown/aPrevents redundant else statements.yesno
argument-limitintSpecifies the maximum number of arguments a function can receivenono
cyclomaticintSets restriction for maximum Cyclomatic complexity.nono
max-public-structsintThe maximum number of public structs in a file.nono
file-headerstringHeader which each file should have.nono
empty-blockn/aWarns on empty code blocksnoyes
superfluous-elsen/aPrevents redundant else statements (extends indent-error-flow)nono
confusing-namingn/aWarns on methods with names that differ only by capitalizationnono
get-returnn/aWarns on getters that do not yield any resultnono
modifies-parametern/aWarns on assignments to function parametersnono
confusing-resultsn/aSuggests to name potentially confusing function resultsnono
deep-exitn/aLooks for program exits in funcs other than main() or init()nono
unused-parametern/aSuggests to rename or remove unused function parametersnono
unreachable-coden/aWarns on unreachable codenono
add-constantmapSuggests using constant for magic numbers and string literalsnono
flag-parametern/aWarns on boolean parameters that create a control couplingnono
unnecessary-stmtn/aSuggests removing or simplifying unnecessary statementsnono
struct-tagn/aChecks common struct tags like json,xml,yamlnono
modifies-value-receivern/aWarns on assignments to value-passed method receiversnoyes
constant-logical-exprn/aWarns on constant logical expressionsnono
bool-literal-in-exprn/aSuggests removing Boolean literals from logic expressionsnono
redefines-builtin-idn/aWarns on redefinitions of builtin identifiersnono
function-result-limitintSpecifies the maximum number of results a function can returnnono
imports-blacklist[]stringDisallows importing the specified packagesnono
range-val-in-closuren/aWarns if range value is used in a closure dispatched as goroutinenono
range-val-addressn/aWarns if address of range value is used dangerouslynono
waitgroup-by-valuen/aWarns on functions taking sync.WaitGroup as a by-value parameternono
atomicn/aCheck for common mistaken usages of the sync/atomic packagenono
empty-linesn/aWarns when there are heading or trailing newlines in a blocknono
line-length-limitintSpecifies the maximum number of characters in a linenono
call-to-gcn/aWarns on explicit call to the garbage collectornono
duplicated-importsn/aLooks for packages that are imported two or more timesnono
import-shadowingn/aSpots identifiers that shadow an importnono
bare-returnn/aWarns on bare returnsnono
unused-receivern/aSuggests to rename or remove unused method receiversnono
unhandled-error[]stringWarns on unhandled errors returned by funcion callsnoyes
cognitive-complexityintSets restriction for maximum Cognitive complexity.nono
string-of-intn/aWarns on suspicious casts from int to stringnoyes
early-returnn/aSpots if-then-else statements that can be refactored to simplify code readingnono
unconditional-recursionn/aWarns on function calls that will lead to (direct) infinite recursionnono
identical-branchesn/aSpots if-then-else statements with identical then and else branchesnono

Configurable rules

Here you can find how you can configure some of the existing rules:

var-naming

This rule accepts two slices of strings, a whitelist and a blacklist of initialisms. By default the rule behaves exactly as the alternative in golint but optionally, you can relax it (see golint/lint/issues/89)

[rule.var-naming]
  arguments = [["ID"], ["VM"]]

This way, revive will not warn for identifier called customId but will warn that customVm should be called customVM.

Available Formatters

This section lists all the available formatters and provides a screenshot for each one.

Friendly

Friendly formatter

Stylish

Stylish formatter

Default

The default formatter produces the same output as golint.

Default formatter

Plain

The plain formatter produces the same output as the default formatter and appends URL to the rule description.

Plain formatter

Unix

The unix formatter produces the same output as the default formatter but surrounds the rules in [].

Unix formatter

Extensibility

The tool can be extended with custom rules or formatters. This section contains additional information on how to implement such.

To extend the linter with a custom rule or a formatter you'll have to push it to this repository or fork it. This is due to the limited -buildmode=plugin support which works only on Linux (with known issues).

Custom Rule

Each rule needs to implement the lint.Rule interface:

type Rule interface {
	Name() string
	Apply(*File, Arguments) []Failure
}

The Arguments type is an alias of the type []interface{}. The arguments of the rule are passed from the configuration file.

Example

Let's suppose we have developed a rule called BanStructNameRule which disallow us to name a structure with given identifier. We can set the banned identifier by using the TOML configuration file:

[rule.ban-struct-name]
  arguments = ["Foo"]

With the snippet above we:

  • Enable the rule with name ban-struct-name. The Name() method of our rule should return a string which matches ban-struct-name.
  • Configure the rule with the argument Foo. The list of arguments will be passed to Apply(*File, Arguments) together with the target file we're linting currently.

A sample rule implementation can be found here.

Custom Formatter

Each formatter needs to implement the following interface:

type Formatter interface {
	Format(<-chan Failure, Config) (string, error)
	Name() string
}

The Format method accepts a channel of Failure instances and the configuration of the enabled rules. The Name() method should return a string different from the names of the already existing rules. This string is used when specifying the formatter when invoking the revive CLI tool.

For a sample formatter, take a look at this file.

Speed Comparison

Compared to golint, revive performs better because it lints the files for each individual rule into a separate goroutine. Here's a basic performance benchmark on MacBook Pro Early 2013 run on kubernetes:

golint

time golint kubernetes/... > /dev/null

real    0m54.837s
user    0m57.844s
sys     0m9.146s

revive

# no type checking
time revive -config untyped.toml kubernetes/... > /dev/null

real    0m8.471s
user    0m40.721s
sys     0m3.262s

Keep in mind that if you use rules which require type checking, the performance may drop to 2x faster than golint:

# type checking enabled
time revive kubernetes/... > /dev/null

real    0m26.211s
user    2m6.708s
sys     0m17.192s

Currently, type checking is enabled by default. If you want to run the linter without type checking, remove all typed rules from the configuration file.

Overriding colorization detection

By default, revive determines whether or not to colorize its output based on whether it's connected to a TTY or not. This works for most use cases, but may not behave as expected if you use revive in a pipeline of commands, where STDOUT is being piped to another command.

To force colorization, add REVIVE_FORCE_COLOR=1 to the environment you're running in. For example:

REVIVE_FORCE_COLOR=1 revive -formatter friendly ./... | tee revive.log

Contributors

mgechevchavacavaxuridshemingsamokovarovmorphy2k
mgechevchavacavaxuridshemingsamokovarovmorphy2k
markelogtamirdmapreal19ClivernAragurDEVbernhardreisenberger
markelogtamirdmapreal19ClivernAragurDEVbernhardreisenberger
yangdiangzbquasilytejamesmaidmentjohnrichardrinehartmichalhisimpa-m
yangdiangzbquasilytejamesmaidmentjohnrichardrinehartmichalhisimpa-m
paul-at-startridvansumsetJaremavkrolhaya14busa
paul-at-startridvansumsetJaremavkrolhaya14busa

License

MIT