A vet analyzer to detect magic numbers.
What is a magic number?
A magic number is a numeric literal that is not defined as a constant, but which may change, and therefore can be hard to update. It's considered a bad programming practice to use numbers directly in any source code without an explanation. It makes programs harder to read, understand, and maintain.
This analyzer requires Golang in version >= 1.12 because it's depends on the go/analysis API.
go get -u github.com/tommy-muehle/go-mnd/v2/cmd/mnd
You can run go-mnd as a GitHub action as follows:
name: Example workflow
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
tests:
runs-on: ubuntu-latest
env:
GO111MODULE: on
steps:
- name: Checkout Source
uses: actions/checkout@v2
- name: Run go-mnd
uses: tommy-muehle/go-mnd@master
with:
args: ./...
You can run go-mnd inside a GitLab CI pipeline as follows:
stages:
- lint
go:lint:mnd:
stage: lint
needs: []
image: golang:latest
before_script:
- go get -u github.com/tommy-muehle/go-mnd/v2/cmd/mnd
- go mod tidy
- go mod vendor
script:
- go vet -vettool $(which mnd) ./...
To install with Homebrew, run:
brew tap tommy-muehle/tap && brew install tommy-muehle/tap/mnd
To get the latest available Docker image:
docker pull tommymuehle/go-mnd
On Windows download the latest release.
go vet -vettool $(which mnd) ./...
or directly
mnd ./...
or via Docker
docker run --rm -v "$PWD":/app -w /app tommymuehle/go-mnd:latest ./...
The -checks
option let's you define a comma separated list of checks.
The -ignored-numbers
option let's you define a comma separated list of numbers to ignore.
For example: -ignored-numbers=1000,10_000,3.14159264
The -ignored-functions
option let's you define a comma separated list of function name regexp patterns to exclude.
For example: -ignored-functions=math.*,http.StatusText,make
The -ignored-files
option let's you define a comma separated list of filename regexp patterns to exclude.
For example: -ignored-files=magic_.*.go,.*_numbers.go
By default this detector analyses arguments, assigns, cases, conditions, operations and return statements.
- argument
t := http.StatusText(200)
- assign
c := &http.Client{
Timeout: 5 * time.Second,
}
- case
switch x {
case 3:
}
- condition
if x > 7 {
}
- operation
var x, y int
y = 10 * x
- return
return 3
By default the numbers 0 and 1 as well as test files are excluded!
The function "Date" in the "Time" package.
t := time.Date(2017, time.September, 26, 12, 13, 14, 0, time.UTC)
Additional custom excludes can be defined via option flag.
You can build the binary with:
make
You can run all unit tests using:
make test
And with coverage report:
make test-coverage
You can also build locally the docker image by using the command:
make image
Just drop me a message via Twitter DM or email if you want some go-mnd stickers for you or your Gopher usergroup.
The MIT License (MIT). Please see LICENSE for more information.