Convert Figma logo to code with AI

mgechev logorevive

🔥 ~6x faster, stricter, configurable, extensible, and beautiful drop-in replacement for golint

4,735
276
4,735
27

Top Related Projects

Fast linters runner for Go

Staticcheck - The advanced Go linter

7,791

Go security checker

DEPRECATED: Use https://github.com/golangci/golangci-lint

errcheck checks that you checked errors.

Quick Overview

Revive is a fast, configurable, extensible, flexible, and beautiful linter for Go. It's designed to be a drop-in replacement for golint with significantly more features and better performance. Revive helps developers maintain code quality and consistency in Go projects.

Pros

  • Highly customizable with over 70 built-in rules and support for custom rules
  • Faster execution compared to golint
  • Provides detailed and actionable feedback on code issues
  • Integrates well with various IDEs and CI/CD pipelines

Cons

  • May require initial setup and configuration to tailor to specific project needs
  • Some users might find the extensive rule set overwhelming at first
  • Occasional false positives, though these can be mitigated through configuration

Getting Started

To install Revive, run:

go install github.com/mgechev/revive@latest

To use Revive with default configuration:

revive ./...

To use a custom configuration file:

revive -config config.toml ./...

To generate a default configuration file:

revive -config config.toml -formatter friendly

For more advanced usage and integration with your development workflow, refer to the project's documentation on GitHub.

Competitor Comparisons

Fast linters runner for Go

Pros of golangci-lint

  • Integrates multiple linters (including Revive) into a single tool
  • Faster execution due to parallel processing and caching
  • Extensive configuration options and customization

Cons of golangci-lint

  • More complex setup and configuration
  • Potentially overwhelming for beginners due to numerous options
  • May require more frequent updates to keep all linters current

Code Comparison

golangci-lint configuration:

linters:
  enable:
    - revive
    - govet
    - errcheck
  disable:
    - deadcode

Revive configuration:

[rule.var-naming]
  arguments = [["ID"], ["URL"]]
[rule.exported]
  severity = "warning"

Both tools offer powerful linting capabilities for Go projects. golangci-lint provides a comprehensive suite of linters, including Revive, making it a one-stop solution for code quality checks. It excels in performance and customization but may be more complex to set up. Revive, on the other hand, focuses solely on style checking and is easier to configure, making it a good choice for projects that require a simpler linting setup or want to use Revive alongside other specific tools.

Staticcheck - The advanced Go linter

Pros of go-tools

  • Offers a wider range of analysis tools beyond linting, including complexity analysis and unused code detection
  • Provides more in-depth static analysis capabilities, potentially catching more subtle issues
  • Integrates well with other Go development tools and IDEs

Cons of go-tools

  • May have a steeper learning curve due to its broader scope and advanced features
  • Could be considered overkill for projects primarily seeking basic linting functionality
  • Potentially slower performance when running full analysis compared to focused linters

Code Comparison

revive:

package main

func main() {
    var x int
    x = 5
}

go-tools (using staticcheck):

package main

func main() {
    x := 5
    _ = x
}

In this example, revive might flag the unused variable, while go-tools (staticcheck) suggests using short variable declaration and explicitly marks the variable as unused.

Both tools are valuable for Go developers, with revive focusing more on customizable linting and go-tools offering a comprehensive suite of analysis tools. The choice between them depends on project requirements and team preferences.

7,791

Go security checker

Pros of gosec

  • Focused specifically on security-related issues in Go code
  • Integrates with popular CI/CD tools for automated security checks
  • Provides detailed explanations and remediation advice for identified vulnerabilities

Cons of gosec

  • Limited scope compared to revive's broader linting capabilities
  • May produce more false positives due to its security-focused approach
  • Less frequent updates and smaller community compared to revive

Code Comparison

revive:

package main

func main() {
    var x int
    x = 5
}

gosec:

package main

import "crypto/md5"

func main() {
    h := md5.New() // G501: Blacklisted import crypto/md5: weak cryptographic primitive
}

revive focuses on general code quality and style issues, while gosec specifically targets security vulnerabilities. In the example above, revive might flag the unused variable x, whereas gosec would identify the use of a weak cryptographic function (MD5) and provide a security warning.

Both tools serve different purposes: revive as a comprehensive linter for Go code, and gosec as a specialized security scanner. Developers may benefit from using both tools in conjunction to ensure both code quality and security best practices are followed in their Go projects.

DEPRECATED: Use https://github.com/golangci/golangci-lint

Pros of Gometalinter

  • Aggregates multiple linters into a single tool
  • Offers a wide range of linters out of the box
  • Provides concurrent execution for faster performance

Cons of Gometalinter

  • No longer actively maintained (deprecated)
  • Can be slower compared to Revive for large projects
  • More complex configuration and setup

Code Comparison

Gometalinter configuration:

linters:
  enable:
    - golint
    - vet
    - errcheck

Revive configuration:

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

[rule.exported]
    severity = "warning"

Gometalinter combines multiple linters, offering a broader range of checks but with a more complex setup. Revive, on the other hand, focuses on being a fast, extensible, and configurable linter with a simpler configuration format.

While Gometalinter provides a comprehensive set of linters, its deprecated status makes Revive a more future-proof choice for Go projects. Revive offers better performance for large codebases and is actively maintained, making it a preferred option for many developers.

errcheck checks that you checked errors.

Pros of errcheck

  • Focused specifically on error checking, providing deep analysis in this area
  • Lightweight and fast execution for error-specific linting
  • Integrates well with other Go tools and CI pipelines

Cons of errcheck

  • Limited scope compared to revive's comprehensive linting capabilities
  • Lacks customization options and rule configuration flexibility
  • May require additional linters to cover other code quality aspects

Code Comparison

errcheck example:

if err := doSomething(); err != nil {
    // errcheck will flag if this error is not handled
}

revive example:

if err := doSomething(); err != nil {
    // revive can check this and many other linting rules
}
// revive can also check for unused variables, formatting, etc.

Both tools aim to improve Go code quality, but revive offers a more comprehensive set of linting rules and customization options. errcheck excels in its focused approach to error checking, while revive provides a broader range of code quality checks. Developers may choose errcheck for its specialized error analysis or opt for revive for a more all-encompassing linting solution.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

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
  • cadence - Cadence is a distributed, scalable, durable, and highly available orchestration engine by Uber to execute asynchronous long-running business logic in a scalable and resilient way
  • 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
  • pyroscope - Continuous profiling platform
  • gorush - A push notification server written in Go (Golang).
  • dry - dry - A Docker manager for the terminal.
  • go-echarts - The adorable charts library for Golang
  • reviewdog - Automated code review tool integrated with any code analysis tools regardless of programming language
  • rudder-server - Privacy and Security focused Segment-alternative, in Golang and React.
  • sklearn - A partial port of scikit-learn written in Go.
  • protoc-gen-doc - Documentation generator plugin for Google Protocol Buffers.
  • llvm - Library for interacting with LLVM IR in pure Go.
  • jenkins-library - Jenkins shared library for Continuous Delivery pipelines by SAP.
  • pd - Placement driver for TiKV.
  • shellhub - ShellHub enables teams to easily access any Linux device behind firewall and NAT.
  • lorawan-stack - The Things Network Stack for LoRaWAN V3
  • gin-jwt - This is a JWT middleware for Gin framework.
  • gofight - Testing API Handler written in Golang.
  • Beaver - A Real Time Messaging Server.
  • 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.
  • DevLake - Apache DevLake is an open-source dev data platform to ingest, analyze, and visualize the fragmented data from DevOps tools,which can distill insights to improve engineering productivity.
  • checker - Checker helps validating user input through rules defined in struct tags or directly through functions.
  • milvus - A cloud-native vector database, storage for next generation AI applications.

Open a PR to add your project.

Installation

go install github.com/mgechev/revive@latest

or get a released executable from the Releases page.

You can install the main branch (including the last commit) with:

go install github.com/mgechev/revive@master

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.

Docker

A volume must be mounted to share the current repository with the container. Please refer to the bind mounts Docker documentation

docker run -v "$(pwd)":/var/<repository> ghcr.io/mgechev/revive:v1.3.7 -config /var/<repository>/revive.toml -formatter stylish ./var/kidle/...
  • -v is for the volume
  • ghcr.io/mgechev/revive:v1.3.7 is the image name and its version corresponds to revive command
  • The provided flags are the same as the binary usage.

Bazel

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

Text Editors

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)

Linter aggregators

golangci-lint

To enable revive in golangci-lint you need to add revive to the list of enabled linters:

# golangci-lint configuration file
linters:
   enable:
     - revive

Then revive can be configured by adding an entry to the linters-settings section of the configuration, for example:

# golangci-lint configuration file
linters-settings:
  revive:
    ignore-generated-header: true
    severity: warning
    rules:
      - name: atomic
      - name: line-length-limit
        severity: error
        arguments: [80]
      - name: unhandled-error
        arguments : ["fmt.Printf", "myFunction"]

The above configuration enables three rules of revive: atomic, line-length-limit and unhandled-error and pass some arguments to the last two. The Configuration section of this document provides details on how to configure revive. Note that while revive configuration is in TOML, that of golangci-lint is in YAML.

Please notice that if no particular configuration is provided, revive will behave as go-lint does, i.e. all go-lint rules are enabled (the Available Rules table details what are the go-lint rules). When a configuration is provided, only rules in the configuration are enabled.

Command Line Flags

revive accepts the following command line parameters:

  • -config [PATH] - path to the 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/mgechev/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 a stream in newline delimited JSON (NDJSON) format.
    • friendly - outputs the failures when found. Shows the 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.
  • -max_open_files - maximum number of open files at the same time. Defaults to unlimited.

  • -set_exit_status - set exit status to 1 if any issues are found, overwrites errorCode and warningCode in config.

  • -version - get revive version.

Sample Invocations

revive -config revive.toml -exclude file1.go -exclude file2.go -formatter friendly github.com/mgechev/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/mgechev/revive and the files in package

Comment Directives

Using comments, you can disable the linter for the entire file or only a 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 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 an explanation of 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 the "error" severity
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"

By default revive will enable only the linting rules that are named in the configuration file. For example, the previous configuration file makes revive to enable only cyclomatic and package-comments linting rules.

To enable all available rules you need to add:

enableAllRules = true

This will enable all available rules no matter what rules are named in the configuration file.

To disable a rule, you simply mark it as disabled in the configuration. For example:

[rule.line-length-limit]
    Disabled = true

When enabling all rules you still need/can provide specific configurations for rules. The following file is an example configuration where all rules are enabled, except for those that are explicitly disabled, and some rules are configured with particular arguments:

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

# Enable all available rules
enableAllRules = true

# Disabled rules
[rule.blank-imports]
    Disabled = true
[rule.file-header]
    Disabled = true
[rule.max-public-structs]
    Disabled = true
[rule.line-length-limit]
    Disabled = true
[rule.function-length]
    Disabled = true
[rule.banned-characters]
    Disabled = true

# Rule tuning
[rule.argument-limit]
    Arguments = [5]
[rule.cyclomatic]
    Arguments = [10]
[rule.cognitive-complexity]
    Arguments = [7]
[rule.function-result-limit]
    Arguments = [3]
[rule.error-strings]
    Arguments = ["mypackage.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/mgechev/revive

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

Custom Configuration

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

This will use config.toml, the friendly formatter, and will run linting over the github.com/mgechev/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.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]

Rule-level file excludes

You also can setup custom excludes for each rule.

It's an alternative for the global -exclude program arg.

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

[rule.blank-imports]
   Exclude=["**/*.pb.go"]
[rule.context-as-argument]
   Exclude=["src/somepkg/*.go", "TEST"]

You can use the following exclude patterns

  1. full paths to files src/pkg/mypkg/some.go
  2. globs src/**/*.pb.go
  3. regexes (should have prefix ~) ~\.(pb|auto|generated)\.go$
  4. well-known TEST (same as **/*_test.go)
  5. special cases: a. * and ~ patterns exclude all files (same effect as disabling the rule) b. "" (empty) pattern excludes nothing

NOTE: do not mess with exclude that can be used at the top level of TOML file, that means "exclude package patterns", not "exclude file patterns"

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-equaln/aSuggests to use time.Time.Equal instead of == and != for equality check time.noyes
time-namingn/aConventions around the naming of time variables.yesyes
unchecked-type-assertionsn/aDisallows type assertions without checking the result.noyes
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-strings[]stringConventions around error strings.yesno
error-namingn/aNaming of error variables.yesno
exported[]stringNaming and commenting conventions on exported symbols.yesno
if-returnn/aRedundant if when returning an error.nono
increment-decrementn/aUse i++ and i-- instead of i += 1 and i -= 1.yesno
var-namingallowlist & blocklist 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-flow[]stringPrevents redundant else statements.yesno
argument-limitint (defaults to 8)Specifies the maximum number of arguments a function can receivenono
cyclomaticint (defaults to 10)Sets restriction for maximum Cyclomatic complexity.nono
max-public-structsint (defaults to 5)The maximum number of public structs in a file.nono
file-headerstring (defaults to none)Header which each file should have.nono
empty-blockn/aWarns on empty code blocksnoyes
superfluous-else[]stringPrevents 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-tag[]stringChecks 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-limitint (defaults to 3)Specifies the maximum number of results a function can returnnono
imports-blocklist[]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 dangerouslynoyes
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-limitint (defaults to 80)Specifies 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 function callsnoyes
cognitive-complexityint (defaults to 7)Sets restriction for maximum Cognitive complexity.nono
string-of-intn/aWarns on suspicious casts from int to stringnoyes
string-formatmapWarns on specific string literals that fail one or more user-configured regular expressionsnono
early-return[]stringSpots if-then-else statements where the predicate may be inverted to reduce nestingnono
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
defermapWarns on some defer gotchasnono
unexported-namingn/aWarns on wrongly named un-exported symbolsnono
function-lengthint, int (defaults to 50 statements, 75 lines)Warns on functions exceeding the statements or lines maxnono
nested-structsn/aWarns on structs within structsnono
useless-breakn/aWarns on useless break statements in case clausesnono
banned-characters[]string (defaults to []string{})Checks banned characters in identifiersnono
optimize-operands-ordern/aChecks inefficient conditional expressionsnono
use-anyn/aProposes to replace interface{} with its alias anynono
dataracen/aSpots potential dataracesnono
comment-spacings[]stringWarns on malformed commentsnono
redundant-import-aliasn/aWarns on import aliases matching the imported package namenono
import-alias-namingstring or map[string]string (defaults to allow regex pattern ^[a-z][a-z0-9]{0,}$)Conventions around the naming of import aliases.nono
enforce-map-stylestring (defaults to "any")Enforces consistent usage of make(map[type]type) or map[type]type{} for map initialization. Does not affect make(map[type]type, size) constructions.nono
enforce-slice-stylestring (defaults to "any")Enforces consistent usage of make([]type, 0) or []type{} for slice initialization. Does not affect make(map[type]type, non_zero_len, or_non_zero_cap) constructions.nono
enforce-repeated-arg-type-stylestring (defaults to "any")Enforces consistent style for repeated argument and/or return value types.nono
max-control-nestingint (defaults to 5)Sets restriction for maximum nesting of control structures.nono
comments-densityint (defaults to 0)Enforces a minimum comment / code relationnono

Configurable rules

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

var-naming

This rule accepts two slices of strings, an allowlist and a blocklist 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 an 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 the 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

SARIF

The sarif formatter produces outputs in SARIF, for Static Analysis Results Interchange Format, a standard JSON-based format for the output of static analysis tools defined and promoted by OASIS.

Current supported version of the standard is SARIF-v2.1.0.

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 you can push it to this repository or use revive as a library (see below)

To add a custom 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).

Writing a 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 a 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 the name ban-struct-name. The Name() method of our rule should return a string that 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.

Using revive as a library

If a rule is specific to your use case (i.e. it is not a good candidate to be added to revive's rule set) you can add it to your linter using revive as a linting engine.

The following code shows how to use revive in your application. In the example only one rule is added (myRule), of course, you can add as many as you need to. Your rules can be configured programmatically or with the standard revive configuration file. The full rule set of revive is also actionable by your application.

package main

import (
	"github.com/mgechev/revive/cli"
	"github.com/mgechev/revive/lint"
	"github.com/mgechev/revive/revivelib"
)

func main() {
	cli.RunRevive(revivelib.NewExtraRule(&myRule{}, lint.RuleConfig{}))
}

type myRule struct{}

func (f myRule) Name() string {
	return "myRule"
}

func (f myRule) Apply(*lint.File, lint.Arguments) []lint.Failure { ... }

You can still go further and use revive without its CLI, as part of your library, or your CLI:

package mylib

import (
	"github.com/mgechev/revive/cli"
	"github.com/mgechev/revive/revivelib"
	"github.com/mgechev/revive/lint"
)

// Error checking removed for clarity
func LintMyFile(file string) {
	conf, _:= config.GetConfig("../defaults.toml")

	revive, _ := revivelib.New(
		conf,  // Configuration file
		true,  // Set exit status
		2048,  // Max open files

		// Then add as many extra rules as you need
		revivelib.NewExtraRule(&myRule{}, lint.RuleConfig{}),
	)

	failuresChan, err := revive.Lint(
 		revivelib.Include(file),
 		revivelib.Exclude("./fixtures"),
 		// You can use as many revivelib.Include or revivelib.Exclude as required
 	)
  	if err != nil {
  	 	panic("Shouldn't have failed: " + err.Error)
  	}

  	// Now let's return the formatted errors
	failures, exitCode, _ := revive.Format("stylish", failuresChan)

  	// failures is the string with all formatted lint error messages
  	// exit code is 0 if no errors, 1 if errors (unless config options change it)
  	// ... do something with them
}

type myRule struct{}

func (f myRule) Name() string {
	return "myRule"
}

func (f myRule) Apply(*lint.File, lint.Arguments) []lint.Failure { ... }

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 that 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

renovate[bot]mgechevchavacavarenovate-botxuridenisvmedia
renovate[bot]mgechevchavacavarenovate-botxuridenisvmedia
mfederowiczdoniacldClivernmorphy2kbernhardreisenbergeralexandear
mfederowiczdoniacldClivernmorphy2kbernhardreisenbergeralexandear
dsheminbutuzovrawen17sina-develtymonxmdelah
dsheminbutuzovrawen17sina-develtymonxmdelah
ldezgsamokovarovcomdivheynemannccemapreal19
ldezgsamokovarovcomdivheynemannccemapreal19
zimmskishmsrgit-hulkccoVeilletamirdmarkelog
zimmskishmsrgit-hulkccoVeilletamirdmarkelog
mihaitodordvejmzdamif94abeltayzeripathGroxx
mihaitodordvejmzdamif94abeltayzeripathGroxx
StephenBrown2qascaderidvansumsetrliebzrdeusserrmarku
StephenBrown2qascaderidvansumsetrliebzrdeusserrmarku
rnikoopourrafamadrizpaco0xweasturpa-mcinar
rnikoopourrafamadrizpaco0xweasturpa-mcinar
natefinchflessery-yagitechknowlogickokhowangmeanguy
natefinchflessery-yagitechknowlogickokhowangmeanguy
likyhkerneltraveljmckenziearkhaya14busafreginydah
likyhkerneltraveljmckenziearkhaya14busafreginydah
WillAbidesheyvitoscopvkrolJarematartale
WillAbidesheyvitoscopvkrolJarematartale
tmzanefelipedavideuankJuneezeeechoixEXHades
tmzanefelipedavideuankJuneezeeechoixEXHades
petethepigDirk007yangdiangzbderekperkinsbborehamattiss
petethepigDirk007yangdiangzbderekperkinsbborehamattiss
AragurkultiAbirdcflyabhinavr-riccinunnatsa
AragurkultiAbirdcflyabhinavr-riccinunnatsa
michalhisimmathieu-aubinmartinsirbeavorimavery-amusedjohnrichardrinehart
michalhisimmathieu-aubinmartinsirbeavorimavery-amusedjohnrichardrinehart
wallesjefersonfjan-xyzjamesmaidmentgrongortie
wallesjefersonfjan-xyzjamesmaidmentgrongortie
quasilytedavidhsingyuchengburanovginglis13
quasilytedavidhsingyuchengburanovginglis13

License

MIT