• This repository has been archived on 10/Apr/2019
  • Stars
    star
    3,507
  • Rank 12,683 (Top 0.3 %)
  • Language
    Go
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

Go Meta Linter


gometalinter is DEPRECATED and the project will be archived on 2019-04-07. See #590 for discussion.

Switch to golangci-lint.


Build Status Gitter chat

The number of tools for statically checking Go source for errors and warnings is impressive.

This is a tool that concurrently runs a whole bunch of those linters and normalises their output to a standard format:

<file>:<line>:[<column>]: <message> (<linter>)

eg.

stutter.go:9::warning: unused global variable unusedGlobal (varcheck)
stutter.go:12:6:warning: exported type MyStruct should have comment or be unexported (golint)

It is intended for use with editor/IDE integration.

Installing

Binary Releases

To install the latest stable release:

curl -L https://git.io/vp6lP | sh

Alternatively you can install a specific version from the releases list.

Homebrew

brew tap alecthomas/homebrew-tap
brew install gometalinter

Editor integration

Supported linters

  • go vet - Reports potential errors that otherwise compile.
  • go tool vet --shadow - Reports variables that may have been unintentionally shadowed.
  • gotype - Syntactic and semantic analysis similar to the Go compiler.
  • gotype -x - Syntactic and semantic analysis in external test packages (similar to the Go compiler).
  • deadcode - Finds unused code.
  • gocyclo - Computes the cyclomatic complexity of functions.
  • golint - Google's (mostly stylistic) linter.
  • varcheck - Find unused global variables and constants.
  • structcheck - Find unused struct fields.
  • maligned - Detect structs that would take less memory if their fields were sorted.
  • errcheck - Check that error return values are used.
  • staticcheck - Statically detect bugs, both obvious and subtle ones.
  • dupl - Reports potentially duplicated code.
  • ineffassign - Detect when assignments to existing variables are not used.
  • interfacer - Suggest narrower interfaces that can be used.
  • unconvert - Detect redundant type conversions.
  • goconst - Finds repeated strings that could be replaced by a constant.
  • gosec - Inspects source code for security problems by scanning the Go AST.

Disabled by default (enable with --enable=<linter>):

  • testify - Show location of failed testify assertions.
  • test - Show location of test failures from the stdlib testing module.
  • gofmt -s - Checks if the code is properly formatted and could not be further simplified.
  • goimports - Checks missing or unreferenced package imports.
  • gochecknoinits - Report init functions, to reduce side effects in code.
  • gochecknoglobals - Report global vars, to reduce side effects in code.
  • lll - Report long lines (see --line-length=N).
  • misspell - Finds commonly misspelled English words.
  • nakedret - Finds naked returns.
  • unparam - Find unused function parameters.
  • safesql - Finds potential SQL injection vulnerabilities.

Additional linters can be added through the command line with --linter=NAME:COMMAND:PATTERN (see below).

Configuration file

gometalinter now supports a JSON configuration file called .gometalinter.json that can be placed at the root of your project. The configuration file will be automatically loaded from the working directory or any parent directory and can be overridden by passing --config=<file> or ignored with --no-config. The format of this file is determined by the Config struct in config.go.

The configuration file mostly corresponds to command-line flags, with the following exceptions:

  • Linters defined in the configuration file will overlay existing definitions, not replace them.
  • "Enable" defines the exact set of linters that will be enabled (default linters are disabled). --help displays the list of default linters with the exact names you must use.

Here is an example configuration file:

{
  "Enable": ["deadcode", "unconvert"]
}

If a .gometalinter.json file is loaded, individual options can still be overridden by passing command-line flags. All flags are parsed in order, meaning configuration passed with the --config flag will override any command-line flags passed before and be overridden by flags passed after.

Format key

The default Format key places the different fields of an Issue into a template. this corresponds to the --format option command-line flag.

Default Format:

Format: "{{.Path}}:{{.Line}}:{{if .Col}}{{.Col}}{{end}}:{{.Severity}}: {{.Message}} ({{.Linter}})"

Format Methods

  • {{.Path.Relative}} - equivalent to {{.Path}} which outputs a relative path to the file
  • {{.Path.Abs}} - outputs an absolute path to the file

Adding Custom linters

Linters can be added and customized from the config file using the Linters field. Linters supports the following fields:

  • Command - the path to the linter binary and any default arguments
  • Pattern - a regular expression used to parse the linter output
  • IsFast - if the linter should be run when the --fast flag is used
  • PartitionStrategy - how paths args should be passed to the linter command:
    • directories - call the linter once with a list of all the directories
    • files - call the linter once with a list of all the files
    • packages - call the linter once with a list of all the package paths
    • files-by-package - call the linter once per package with a list of the files in the package.
    • single-directory - call the linter once per directory

The config for default linters can be overridden by using the name of the linter.

Additional linters can be configured via the command line using the format NAME:COMMAND:PATTERN.

Example:

$ gometalinter --linter='vet:go tool vet -printfuncs=Infof,Debugf,Warningf,Errorf:PATH:LINE:MESSAGE' .

Comment directives

gometalinter supports suppression of linter messages via comment directives. The form of the directive is:

// nolint[: <linter>[, <linter>, ...]]

Suppression works in the following way:

  1. Line-level suppression

    A comment directive suppresses any linter messages on that line.

    eg. In this example any messages for a := 10 will be suppressed and errcheck messages for defer r.Close() will also be suppressed.

    a := 10 // nolint
    a = 2
    defer r.Close() // nolint: errcheck
  2. Statement-level suppression

    A comment directive at the same indentation level as a statement it immediately precedes will also suppress any linter messages in that entire statement.

    eg. In this example all messages for SomeFunc() will be suppressed.

    // nolint
    func SomeFunc() {
    }

Implementation details: gometalinter now performs parsing of Go source code, to extract linter directives and associate them with line ranges. To avoid unnecessary processing, parsing is on-demand: the first time a linter emits a message for a file, that file is parsed for directives.

Quickstart

Install gometalinter (see above).

Run it:

$ cd example
$ gometalinter ./...
stutter.go:13::warning: unused struct field MyStruct.Unused (structcheck)
stutter.go:9::warning: unused global variable unusedGlobal (varcheck)
stutter.go:12:6:warning: exported type MyStruct should have comment or be unexported (golint)
stutter.go:16:6:warning: exported type PublicUndocumented should have comment or be unexported (golint)
stutter.go:8:1:warning: unusedGlobal is unused (deadcode)
stutter.go:12:1:warning: MyStruct is unused (deadcode)
stutter.go:16:1:warning: PublicUndocumented is unused (deadcode)
stutter.go:20:1:warning: duplicateDefer is unused (deadcode)
stutter.go:21:15:warning: error return value not checked (defer a.Close()) (errcheck)
stutter.go:22:15:warning: error return value not checked (defer a.Close()) (errcheck)
stutter.go:27:6:warning: error return value not checked (doit()           // test for errcheck) (errcheck)
stutter.go:29::error: unreachable code (vet)
stutter.go:26::error: missing argument for Printf("%d"): format reads arg 1, have only 0 args (vet)

Gometalinter also supports the commonly seen <path>/... recursive path format. Note that this can be very slow, and you may need to increase the linter --deadline to allow linters to complete.

FAQ

Exit status

gometalinter sets two bits of the exit status to indicate different issues:

Bit Meaning
0 A linter generated an issue.
1 An underlying error occurred; eg. a linter failed to execute. In this situation a warning will also be displayed.

eg. linter only = 1, underlying only = 2, linter + underlying = 3

What's the best way to use gometalinter in CI?

There are two main problems running in a CI:

  1. Linters break, causing gometalinter --install --update to error (this is no longer an issue as all linters are vendored).
  2. gometalinter adds a new linter.

I have solved 1 by vendoring the linters.

For 2, the best option is to disable all linters, then explicitly enable the ones you want:

gometalinter --disable-all --enable=errcheck --enable=vet --enable=vetshadow ...

How do I make gometalinter work with Go 1.5 vendoring?

gometalinter has a --vendor flag that just sets GO15VENDOREXPERIMENT=1, however the underlying tools must support it. Ensure that all of the linters are up to date and built with Go 1.5 (gometalinter --install --force) then run gometalinter --vendor .. That should be it.

Why does gometalinter --install install a fork of gocyclo?

I forked gocyclo because the upstream behaviour is to recursively check all subdirectories even when just a single directory is specified. This made it unusably slow when vendoring. The recursive behaviour can be achieved with gometalinter by explicitly specifying <path>/.... There is a pull request open.

Many unexpected errors are being reported

If you see a whole bunch of errors being reported that you wouldn't expect, such as compile errors, this typically means that something is wrong with your Go environment. Try go install and fix any issues with your go installation, then try gometalinter again.

Gometalinter is not working

That's more of a statement than a question, but okay.

Sometimes gometalinter will not report issues that you think it should. There are three things to try in that case:

1. Update to the latest build of gometalinter and all linters

curl -L https://git.io/vp6lP | sh

If you're lucky, this will fix the problem.

2. Analyse the debug output

If that doesn't help, the problem may be elsewhere (in no particular order):

  1. Upstream linter has changed its output or semantics.
  2. gometalinter is not invoking the tool correctly.
  3. gometalinter regular expression matches are not correct for a linter.
  4. Linter is exceeding the deadline.

To find out what's going on run in debug mode:

gometalinter --debug

This will show all output from the linters and should indicate why it is failing.

3. Report an issue.

Failing all else, if the problem looks like a bug please file an issue and include the output of gometalinter --debug.

How do I filter issues between two git refs?

revgrep can be used to filter the output of gometalinter to show issues on lines that have changed between two git refs, such as unstaged changes, changes in HEAD vs master and between master and origin/master. See the project's documentation and -help usage for more information.

go get -u github.com/bradleyfalzon/revgrep/...
gometalinter |& revgrep               # If unstaged changes or untracked files, those issues are shown.
gometalinter |& revgrep               # Else show issues in the last commit.
gometalinter |& revgrep master        # Show issues between master and HEAD (or any other reference).
gometalinter |& revgrep origin/master # Show issues that haven't been pushed.

Checkstyle XML format

gometalinter supports checkstyle compatible XML output format. It is triggered with --checkstyle flag:

gometalinter --checkstyle

Checkstyle format can be used to integrate gometalinter with Jenkins CI with the help of Checkstyle Plugin.

More Repositories

1

chroma

A general purpose syntax highlighter in pure Go
Go
4,360
star
2

kingpin

CONTRIBUTIONS ONLY: A Go (golang) command line and flag parser
Go
3,497
star
3

participle

A parser library for Go
Go
3,479
star
4

entityx

EntityX - A fast, type-safe C++ Entity-Component system
C++
2,170
star
5

kong

Kong is a command-line parser for Go
Go
2,132
star
6

voluptuous

CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.
Python
1,793
star
7

go_serialization_benchmarks

Benchmarks of Go serialization methods
Go
1,560
star
8

jsonschema

Maintenance has moved to https://github.com/invopop/jsonschema
Go
750
star
9

pawk

PAWK - A Python line processor (like AWK)
Python
516
star
10

gozmq

Go (golang) bindings for the 0mq (zmq, zeromq) C API
Go
468
star
11

log4go

Logging package similar to log4j for the Go programming language
Go
309
star
12

ondir

OnDir is a small program to automate tasks specific to certain directories
C
195
star
13

mph

Minimal Perfect Hashing for Go
Go
173
star
14

repr

Python's repr() for Go
Go
163
star
15

assert

A simple assertion library using Go generics
Go
147
star
16

units

Helpful unit multipliers and functions for Go
Go
123
star
17

importmagic

A Python library for finding unresolved symbols in Python code, and the corresponding imports
Python
120
star
18

gorx

A package and tool providing Reactive eXtensions for Go.
Go
94
star
19

devtodo2

DevTodo the Second
Go
89
star
20

template

Fork of Go's text/template adding newline elision
Go
56
star
21

hcl

Parsing, encoding and decoding of HCL to and from Go types and an AST.
Go
49
star
22

binary

General purpose binary encoder/decoder
Go
48
star
23

SublimeLinter-contrib-gometalinter

SublimeLinter plugin for gometalinter
Python
47
star
24

localcache

Local file-based atomic cache manager
Go
44
star
25

gobundle

DEPRECATED: I recommend https://github.com/GeertJohan/go.rice
Go
39
star
26

geoip

A pure Go interface to the free MaxMind GeoIP database
Go
38
star
27

unsafeslice

Unsafe zero-copy slice casts for Go
Go
37
star
28

SublimePythonImportMagic

This Sublime Text 2 plugin attempts to automatically manage Python imports.
Python
34
star
29

inject

Guice-ish dependency injection for Go.
Go
31
star
30

sequel

Sequel - A Go <-> SQL mapping package
Go
26
star
31

multiplex

This Go package multiplexes streams over a single underlying transport io.ReadWriteCloser.
Go
25
star
32

arena

A very fast arena allocator for Go
Go
22
star
33

tuplespace

A RESTful tuple space server
Go
21
star
34

langx

Language experimentation.
Go
21
star
35

mango-kong

Mango (man page generator) integration for Kong
Go
20
star
36

go-check-sumtype

A simple utility for running exhaustiveness checks on Go "sum types."
Go
20
star
37

atomic

Type-safe atomic values for Go
Go
19
star
38

go-rpcgen

Generates Go RPC server and client boilerplate for interfaces.
Go
17
star
39

SublimeFoldPythonDocstrings

Automatically folds Python docstrings longer than 1 line.
Python
16
star
40

colour

Quake-style colour formatting for Unix terminals
Go
15
star
41

protobuf

A Protobuf IDL parser for Go
Go
15
star
42

oink

Oink is a Python to Javascript translator.
Python
15
star
43

entityx_python

Python bindings for EntityX
C++
14
star
44

kong-yaml

Go
14
star
45

bit

Bit - A simple yet powerful build tool
Go
12
star
46

shreq

This utility verifies all commands used by a shell script against an allow list
Go
11
star
47

types

Useful generic types for Go
Go
11
star
48

app

Modular application framework for Go.
Go
11
star
49

kdl

Go parser for KDL
Go
10
star
50

vheap

Fast, persistent, mmapped, virtual heap.
Go
8
star
51

errors

A simple errors package for Go
Go
8
star
52

kong-hcl

Go
8
star
53

rapid

RESTful API Daemons (and Clients) for Go
Go
7
star
54

genh

genh is an opinionated tool for generating request-handler boilerplate for Go
Go
7
star
55

ReactiveDataStructures

Reactive data structures for Swift based on RxSwift
Swift
7
star
56

lunatic-go

Lunatic bindings for (Tiny)Go
Go
6
star
57

chrysalis

Chrysalis - Source to a 2D Platformer from 1994
C++
6
star
58

dotfiles

My dotfiles.
Vim Script
6
star
59

bootstrap

Go application bootstrapping
Go
6
star
60

devtodo

DevTodo (legacy)
C
6
star
61

waffle

Waffle - A Dependency-Injection-based application framework for Python
Python
5
star
62

porpoise

Porpoise - A Redis-based analytics framework
Python
5
star
63

waitgroup

Like sync.WaitGroup and ergroup.Group had a baby.
Go
5
star
64

esfmt

An opinionated, zero-configuration formatter for ES/TS/ESX/TSX
Go
5
star
65

flam

flam /flæm/ noun, verb, flammed, flam⋅ming. Informal. –noun 1. a deception or trick. 2. a falsehood; lie. –verb (used with object), verb (used without object) 3. to deceive; delude; cheat.
Python
5
star
66

cly

A Python module for adding powerful text-based consoles to your application.
Python
4
star
67

expr

Runtime evaluation of Go-like expressions
Go
4
star
68

simplenotefs

simplenotefs
Python
4
star
69

concurrency

Types and functions for managing concurrency in Go.
Go
4
star
70

replaylog

A type safe implementation of an op replay log
Go
3
star
71

Cache.swift

A flexible RAM and disk-backed cache for Swift
Swift
3
star
72

wit-go

A partial WIT parser and code generator for Go
Go
3
star
73

SublimeLinter-contrib-errcheck

SublimeLinter integration for the Go errcheck utility
Python
3
star
74

SublimeLinter-contrib-golang-cilint

DEPRECATED: Use https://github.com/cixtor/SublimeLinter-golangcilint
Python
2
star
75

aspect

Lightweight Aspect-oriented Module for Python
Python
2
star
76

gptcc

Add Conventional Commits to commit messages using ChatGPT
Shell
2
star
77

WaveGrowl.app

Wave notifications via Growl on Mac
Python
2
star
78

cut

Core Utilities - A set of core utility classes for Python.
Python
2
star
79

kong-toml

Kong configuration loader for TOML
Shell
2
star
80

rest

Go
2
star
81

prototemplate

Process Protocol Buffer definitions with text templates and JavaScript functions
Go
2
star
82

webservice

A webservice dispatcher for Go
Go
1
star
83

pathways

Pathways - An opinionated RESTful web service framework for Go
Go
1
star
84

cktphotography.com

Christine Knight Thomas Photography (website)
JavaScript
1
star
85

psmap

Persistent static maps for Go
Go
1
star