зеркало из https://github.com/Azure/ARO-RP.git
vendor
This commit is contained in:
Родитель
4f0b68928f
Коммит
44e1c425d7
1
deps.go
1
deps.go
|
@ -11,6 +11,7 @@ import (
|
|||
_ "github.com/axw/gocov/gocov"
|
||||
_ "github.com/go-bindata/go-bindata/go-bindata"
|
||||
_ "github.com/golang/mock/mockgen"
|
||||
_ "github.com/golangci/golangci-lint/cmd/golangci-lint"
|
||||
_ "github.com/jim-minter/go-cosmosdb/cmd/gencosmosdb"
|
||||
_ "github.com/jstemmer/go-junit-report"
|
||||
_ "golang.org/x/tools/cmd/goimports"
|
||||
|
|
2
go.mod
2
go.mod
|
@ -39,6 +39,7 @@ require (
|
|||
github.com/go-playground/validator/v10 v10.4.1 // indirect
|
||||
github.com/go-test/deep v1.0.7
|
||||
github.com/golang/mock v1.4.4
|
||||
github.com/golangci/golangci-lint v1.32.2
|
||||
github.com/google/go-cmp v0.5.3
|
||||
github.com/google/gofuzz v1.2.0 // indirect
|
||||
github.com/googleapis/gnostic v0.5.3
|
||||
|
@ -51,7 +52,6 @@ require (
|
|||
github.com/jstemmer/go-junit-report v0.9.1
|
||||
github.com/klauspost/compress v1.11.3 // indirect
|
||||
github.com/libvirt/libvirt-go v6.9.0+incompatible // indirect
|
||||
github.com/mattn/go-colorable v0.1.8 // indirect
|
||||
github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
|
||||
github.com/nxadm/tail v1.4.5 // indirect
|
||||
github.com/onsi/ginkgo v1.14.2
|
||||
|
|
263
go.sum
263
go.sum
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2018 Leigh McCulloch
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
154
vendor/4d63.com/gochecknoglobals/checknoglobals/check_no_globals.go
сгенерированный
поставляемый
Normal file
154
vendor/4d63.com/gochecknoglobals/checknoglobals/check_no_globals.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,154 @@
|
|||
package checknoglobals
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/tools/go/analysis"
|
||||
)
|
||||
|
||||
// allowedExpression is a struct representing packages and methods that will
|
||||
// be an allowed combination to use as a global variable, f.ex. Name `regexp`
|
||||
// and SelName `MustCompile`.
|
||||
type allowedExpression struct {
|
||||
Name string
|
||||
SelName string
|
||||
}
|
||||
|
||||
const Doc = `check that no global variables exist
|
||||
|
||||
This analyzer checks for global variables and errors on any found.
|
||||
|
||||
A global variable is a variable declared in package scope and that can be read
|
||||
and written to by any function within the package. Global variables can cause
|
||||
side effects which are difficult to keep track of. A code in one function may
|
||||
change the variables state while another unrelated chunk of code may be
|
||||
effected by it.`
|
||||
|
||||
// Analyzer provides an Analyzer that checks that there are no global
|
||||
// variables, except for errors and variables containing regular
|
||||
// expressions.
|
||||
func Analyzer() *analysis.Analyzer {
|
||||
return &analysis.Analyzer{
|
||||
Name: "gochecknoglobals",
|
||||
Doc: Doc,
|
||||
Run: checkNoGlobals,
|
||||
Flags: flags(),
|
||||
RunDespiteErrors: true,
|
||||
}
|
||||
}
|
||||
|
||||
func flags() flag.FlagSet {
|
||||
flags := flag.NewFlagSet("", flag.ExitOnError)
|
||||
flags.Bool("t", false, "Include tests")
|
||||
|
||||
return *flags
|
||||
}
|
||||
|
||||
func isAllowed(v ast.Node) bool {
|
||||
switch i := v.(type) {
|
||||
case *ast.Ident:
|
||||
return i.Name == "_" || i.Name == "version" || looksLikeError(i)
|
||||
case *ast.CallExpr:
|
||||
if expr, ok := i.Fun.(*ast.SelectorExpr); ok {
|
||||
return isAllowedSelectorExpression(expr)
|
||||
}
|
||||
case *ast.CompositeLit:
|
||||
if expr, ok := i.Type.(*ast.SelectorExpr); ok {
|
||||
return isAllowedSelectorExpression(expr)
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func isAllowedSelectorExpression(v *ast.SelectorExpr) bool {
|
||||
x, ok := v.X.(*ast.Ident)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
allowList := []allowedExpression{
|
||||
{Name: "regexp", SelName: "MustCompile"},
|
||||
}
|
||||
|
||||
for _, i := range allowList {
|
||||
if x.Name == i.Name && v.Sel.Name == i.SelName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// looksLikeError returns true if the AST identifier starts
|
||||
// with 'err' or 'Err', or false otherwise.
|
||||
//
|
||||
// TODO: https://github.com/leighmcculloch/gochecknoglobals/issues/5
|
||||
func looksLikeError(i *ast.Ident) bool {
|
||||
prefix := "err"
|
||||
if i.IsExported() {
|
||||
prefix = "Err"
|
||||
}
|
||||
return strings.HasPrefix(i.Name, prefix)
|
||||
}
|
||||
|
||||
func checkNoGlobals(pass *analysis.Pass) (interface{}, error) {
|
||||
includeTests := pass.Analyzer.Flags.Lookup("t").Value.(flag.Getter).Get().(bool)
|
||||
|
||||
for _, file := range pass.Files {
|
||||
filename := pass.Fset.Position(file.Pos()).Filename
|
||||
if !strings.HasSuffix(filename, ".go") {
|
||||
continue
|
||||
}
|
||||
if !includeTests && strings.HasSuffix(filename, "_test.go") {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, decl := range file.Decls {
|
||||
genDecl, ok := decl.(*ast.GenDecl)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if genDecl.Tok != token.VAR {
|
||||
continue
|
||||
}
|
||||
for _, spec := range genDecl.Specs {
|
||||
valueSpec := spec.(*ast.ValueSpec)
|
||||
onlyAllowedValues := false
|
||||
|
||||
for _, vn := range valueSpec.Values {
|
||||
if isAllowed(vn) {
|
||||
onlyAllowedValues = true
|
||||
continue
|
||||
}
|
||||
|
||||
onlyAllowedValues = false
|
||||
break
|
||||
}
|
||||
|
||||
if onlyAllowedValues {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, vn := range valueSpec.Names {
|
||||
if isAllowed(vn) {
|
||||
continue
|
||||
}
|
||||
|
||||
message := fmt.Sprintf("%s is a global variable", vn.Name)
|
||||
pass.Report(analysis.Diagnostic{
|
||||
Pos: vn.Pos(),
|
||||
Category: "global",
|
||||
Message: message,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, built with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
# Dependency directories (remove the comment below to include it)
|
||||
# vendor/
|
|
@ -0,0 +1,150 @@
|
|||
# This file contains all available configuration options
|
||||
# with their default values.
|
||||
|
||||
# options for analysis running
|
||||
run:
|
||||
# default concurrency is a available CPU number
|
||||
concurrency: 4
|
||||
|
||||
# timeout for analysis, e.g. 30s, 5m, default is 1m
|
||||
deadline: 15m
|
||||
|
||||
# exit code when at least one issue was found, default is 1
|
||||
issues-exit-code: 1
|
||||
|
||||
# include test files or not, default is true
|
||||
tests: false
|
||||
|
||||
# list of build tags, all linters use it. Default is empty list.
|
||||
#build-tags:
|
||||
# - mytag
|
||||
|
||||
# which dirs to skip: they won't be analyzed;
|
||||
# can use regexp here: generated.*, regexp is applied on full path;
|
||||
# default value is empty list, but next dirs are always skipped independently
|
||||
# from this option's value:
|
||||
# vendor$, third_party$, testdata$, examples$, Godeps$, builtin$
|
||||
skip-dirs:
|
||||
- /gen$
|
||||
|
||||
# which files to skip: they will be analyzed, but issues from them
|
||||
# won't be reported. Default value is empty list, but there is
|
||||
# no need to include all autogenerated files, we confidently recognize
|
||||
# autogenerated files. If it's not please let us know.
|
||||
skip-files:
|
||||
- ".*\\.my\\.go$"
|
||||
- lib/bad.go
|
||||
- ".*\\.template\\.go$"
|
||||
|
||||
# output configuration options
|
||||
output:
|
||||
# colored-line-number|line-number|json|tab|checkstyle, default is "colored-line-number"
|
||||
format: colored-line-number
|
||||
|
||||
# print lines of code with issue, default is true
|
||||
print-issued-lines: true
|
||||
|
||||
# print linter name in the end of issue text, default is true
|
||||
print-linter-name: true
|
||||
|
||||
# all available settings of specific linters
|
||||
linters-settings:
|
||||
errcheck:
|
||||
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
|
||||
# default is false: such cases aren't reported by default.
|
||||
check-type-assertions: false
|
||||
|
||||
# report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`;
|
||||
# default is false: such cases aren't reported by default.
|
||||
check-blank: false
|
||||
govet:
|
||||
# report about shadowed variables
|
||||
check-shadowing: true
|
||||
|
||||
# Obtain type information from installed (to $GOPATH/pkg) package files:
|
||||
# golangci-lint will execute `go install -i` and `go test -i` for analyzed packages
|
||||
# before analyzing them.
|
||||
# By default this option is disabled and govet gets type information by loader from source code.
|
||||
# Loading from source code is slow, but it's done only once for all linters.
|
||||
# Go-installing of packages first time is much slower than loading them from source code,
|
||||
# therefore this option is disabled by default.
|
||||
# But repeated installation is fast in go >= 1.10 because of build caching.
|
||||
# Enable this option only if all conditions are met:
|
||||
# 1. you use only "fast" linters (--fast e.g.): no program loading occurs
|
||||
# 2. you use go >= 1.10
|
||||
# 3. you do repeated runs (false for CI) or cache $GOPATH/pkg or `go env GOCACHE` dir in CI.
|
||||
use-installed-packages: false
|
||||
golint:
|
||||
# minimal confidence for issues, default is 0.8
|
||||
min-confidence: 0.8
|
||||
gofmt:
|
||||
# simplify code: gofmt with `-s` option, true by default
|
||||
simplify: true
|
||||
gocyclo:
|
||||
# minimal code complexity to report, 30 by default (but we recommend 10-20)
|
||||
min-complexity: 10
|
||||
maligned:
|
||||
# print struct with more effective memory layout or not, false by default
|
||||
suggest-new: true
|
||||
dupl:
|
||||
# tokens count to trigger issue, 150 by default
|
||||
threshold: 100
|
||||
goconst:
|
||||
# minimal length of string constant, 3 by default
|
||||
min-len: 3
|
||||
# minimal occurrences count to trigger, 3 by default
|
||||
min-occurrences: 3
|
||||
depguard:
|
||||
list-type: blacklist
|
||||
include-go-root: false
|
||||
packages:
|
||||
- github.com/davecgh/go-spew/spew
|
||||
|
||||
linters:
|
||||
#enable:
|
||||
# - staticcheck
|
||||
# - unused
|
||||
# - gosimple
|
||||
enable-all: true
|
||||
disable:
|
||||
- lll
|
||||
disable-all: false
|
||||
#presets:
|
||||
# - bugs
|
||||
# - unused
|
||||
fast: false
|
||||
|
||||
issues:
|
||||
# List of regexps of issue texts to exclude, empty list by default.
|
||||
# But independently from this option we use default exclude patterns,
|
||||
# it can be disabled by `exclude-use-default: false`. To list all
|
||||
# excluded by default patterns execute `golangci-lint run --help`
|
||||
exclude:
|
||||
- "`parseTained` is unused"
|
||||
- "`parseState` is unused"
|
||||
|
||||
# Independently from option `exclude` we use default exclude patterns,
|
||||
# it can be disabled by this option. To list all
|
||||
# excluded by default patterns execute `golangci-lint run --help`.
|
||||
# Default value for this option is false.
|
||||
exclude-use-default: false
|
||||
|
||||
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
|
||||
max-per-linter: 0
|
||||
|
||||
# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
|
||||
max-same: 0
|
||||
|
||||
# Show only new issues: if there are unstaged changes or untracked files,
|
||||
# only those changes are analyzed, else only changes in HEAD~ are analyzed.
|
||||
# It's a super-useful option for integration of golangci-lint into existing
|
||||
# large codebase. It's not practical to fix all existing issues at the moment
|
||||
# of integration: much better don't allow issues in new code.
|
||||
# Default is false.
|
||||
new: false
|
||||
|
||||
# Show only new issues created after git revision `REV`
|
||||
#new-from-rev: REV
|
||||
|
||||
# Show only new issues created in git patch with set file path.
|
||||
#new-from-patch: path/to/patch/file
|
|
@ -0,0 +1,24 @@
|
|||
language: go
|
||||
|
||||
go:
|
||||
- "1.13"
|
||||
- "1.14"
|
||||
- tip
|
||||
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
|
||||
before_install:
|
||||
- go get github.com/axw/gocov/gocov
|
||||
- go get github.com/mattn/goveralls
|
||||
- go get golang.org/x/tools/cmd/cover
|
||||
- go get golang.org/x/tools/cmd/goimports
|
||||
- wget -O - -q https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh| sh
|
||||
|
||||
script:
|
||||
- test -z "$(goimports -d ./ 2>&1)"
|
||||
- ./bin/golangci-lint run
|
||||
- go test -v -race ./...
|
||||
|
||||
after_success:
|
||||
- test "$TRAVIS_GO_VERSION" = "1.14" && goveralls -service=travis-ci
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2020 Djarvur
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -0,0 +1,75 @@
|
|||
= err113 image:https://godoc.org/github.com/Djarvur/go-err113?status.svg["GoDoc",link="http://godoc.org/github.com/Djarvur/go-err113"] image:https://travis-ci.org/Djarvur/go-err113.svg["Build Status",link="https://travis-ci.org/Djarvur/go-err113"] image:https://coveralls.io/repos/Djarvur/go-err113/badge.svg?branch=master&service=github["Coverage Status",link="https://coveralls.io/github/Djarvur/go-err113?branch=master"]
|
||||
Daniel Podolsky
|
||||
:toc:
|
||||
|
||||
Golang linter to check the errors handling expressions
|
||||
|
||||
== Details
|
||||
|
||||
Starting from Go 1.13 the standard `error` type behaviour was changed: one `error` could be derived from another with `fmt.Errorf()` method using `%w` format specifier.
|
||||
|
||||
So the errors hierarchy could be built for flexible and responsible errors processing.
|
||||
|
||||
And to make this possible at least two simple rules should be followed:
|
||||
|
||||
1. `error` values should not be compared directly but with `errors.Is()` method.
|
||||
1. `error` should not be created dynamically from scratch but by the wrapping the static (package-level) error.
|
||||
|
||||
This linter is checking the code for these 2 rules compliance.
|
||||
|
||||
=== Reports
|
||||
|
||||
So, `err113` reports every `==` and `!=` comparison for exact `error` type variables except comparison to `nil` and `io.EOF`.
|
||||
|
||||
Also, any call of `errors.New()` and `fmt.Errorf()` methods are reported except the calls used to initialise package-level variables and the `fmt.Errorf()` calls wrapping the other errors.
|
||||
|
||||
Note: non-standard packages, like `github.com/pkg/errors` are ignored completely.
|
||||
|
||||
== Install
|
||||
|
||||
```
|
||||
go get -u github.com/Djarvur/go-err113/cmd/err113
|
||||
```
|
||||
|
||||
== Usage
|
||||
|
||||
Defined by link:https://pkg.go.dev/golang.org/x/tools/go/analysis/singlechecker[singlechecker] package.
|
||||
|
||||
```
|
||||
err113: checks the error handling rules according to the Go 1.13 new error type
|
||||
|
||||
Usage: err113 [-flag] [package]
|
||||
|
||||
|
||||
Flags:
|
||||
-V print version and exit
|
||||
-all
|
||||
no effect (deprecated)
|
||||
-c int
|
||||
display offending line with this many lines of context (default -1)
|
||||
-cpuprofile string
|
||||
write CPU profile to this file
|
||||
-debug string
|
||||
debug flags, any subset of "fpstv"
|
||||
-fix
|
||||
apply all suggested fixes
|
||||
-flags
|
||||
print analyzer flags in JSON
|
||||
-json
|
||||
emit JSON output
|
||||
-memprofile string
|
||||
write memory profile to this file
|
||||
-source
|
||||
no effect (deprecated)
|
||||
-tags string
|
||||
no effect (deprecated)
|
||||
-trace string
|
||||
write trace log to this file
|
||||
-v no effect (deprecated)
|
||||
```
|
||||
|
||||
== Thanks
|
||||
|
||||
To link:https://github.com/quasilyte[Iskander (Alex) Sharipov] for the really useful advices.
|
||||
|
||||
To link:https://github.com/jackwhelpton[Jack Whelpton] for the bugfix provided.
|
|
@ -0,0 +1,103 @@
|
|||
package err113
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"go/types"
|
||||
|
||||
"golang.org/x/tools/go/analysis"
|
||||
)
|
||||
|
||||
func inspectComparision(pass *analysis.Pass, n ast.Node) bool { // nolint: unparam
|
||||
// check whether the call expression matches time.Now().Sub()
|
||||
be, ok := n.(*ast.BinaryExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
// check if it is a comparison operation
|
||||
if be.Op != token.EQL && be.Op != token.NEQ {
|
||||
return true
|
||||
}
|
||||
|
||||
// check that both left and right hand side are not nil
|
||||
if pass.TypesInfo.Types[be.X].IsNil() || pass.TypesInfo.Types[be.Y].IsNil() {
|
||||
return true
|
||||
}
|
||||
|
||||
// check that both left and right hand side are not io.EOF
|
||||
if isEOF(be.X, pass.TypesInfo) || isEOF(be.Y, pass.TypesInfo) {
|
||||
return true
|
||||
}
|
||||
|
||||
// check that both left and right hand side are errors
|
||||
if !isError(be.X, pass.TypesInfo) && !isError(be.Y, pass.TypesInfo) {
|
||||
return true
|
||||
}
|
||||
|
||||
oldExpr := render(pass.Fset, be)
|
||||
|
||||
negate := ""
|
||||
if be.Op == token.NEQ {
|
||||
negate = "!"
|
||||
}
|
||||
|
||||
newExpr := fmt.Sprintf("%s%s.Is(%s, %s)", negate, "errors", be.X, be.Y)
|
||||
|
||||
pass.Report(
|
||||
analysis.Diagnostic{
|
||||
Pos: be.Pos(),
|
||||
Message: fmt.Sprintf("do not compare errors directly, use errors.Is() instead: %q", oldExpr),
|
||||
SuggestedFixes: []analysis.SuggestedFix{
|
||||
{
|
||||
Message: fmt.Sprintf("should replace %q with %q", oldExpr, newExpr),
|
||||
TextEdits: []analysis.TextEdit{
|
||||
{
|
||||
Pos: be.Pos(),
|
||||
End: be.End(),
|
||||
NewText: []byte(newExpr),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func isError(v ast.Expr, info *types.Info) bool {
|
||||
if intf, ok := info.TypeOf(v).Underlying().(*types.Interface); ok {
|
||||
return intf.NumMethods() == 1 && intf.Method(0).FullName() == "(error).Error"
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func isEOF(ex ast.Expr, info *types.Info) bool {
|
||||
se, ok := ex.(*ast.SelectorExpr)
|
||||
if !ok || se.Sel.Name != "EOF" {
|
||||
return false
|
||||
}
|
||||
|
||||
if ep, ok := asImportedName(se.X, info); !ok || ep != "io" {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func asImportedName(ex ast.Expr, info *types.Info) (string, bool) {
|
||||
ei, ok := ex.(*ast.Ident)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
|
||||
ep, ok := info.ObjectOf(ei).(*types.PkgName)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return ep.Imported().Path(), true
|
||||
}
|
|
@ -0,0 +1,74 @@
|
|||
package err113
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/types"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/tools/go/analysis"
|
||||
)
|
||||
|
||||
var methods2check = map[string]map[string]func(*ast.CallExpr, *types.Info) bool{ // nolint: gochecknoglobals
|
||||
"errors": {"New": justTrue},
|
||||
"fmt": {"Errorf": checkWrap},
|
||||
}
|
||||
|
||||
func justTrue(*ast.CallExpr, *types.Info) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func checkWrap(ce *ast.CallExpr, info *types.Info) bool {
|
||||
return !(len(ce.Args) > 0 && strings.Contains(toString(ce.Args[0], info), `%w`))
|
||||
}
|
||||
|
||||
func inspectDefinition(pass *analysis.Pass, tlds map[*ast.CallExpr]struct{}, n ast.Node) bool { //nolint: unparam
|
||||
// check whether the call expression matches time.Now().Sub()
|
||||
ce, ok := n.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
if _, ok = tlds[ce]; ok {
|
||||
return true
|
||||
}
|
||||
|
||||
fn, ok := ce.Fun.(*ast.SelectorExpr)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
fxName, ok := asImportedName(fn.X, pass.TypesInfo)
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
methods, ok := methods2check[fxName]
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
checkFunc, ok := methods[fn.Sel.Name]
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
|
||||
if !checkFunc(ce, pass.TypesInfo) {
|
||||
return true
|
||||
}
|
||||
|
||||
pass.Reportf(
|
||||
ce.Pos(),
|
||||
"do not define dynamic errors, use wrapped static errors instead: %q",
|
||||
render(pass.Fset, ce),
|
||||
)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func toString(ex ast.Expr, info *types.Info) string {
|
||||
if tv, ok := info.Types[ex]; ok && tv.Value != nil {
|
||||
return tv.Value.String()
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
|
@ -0,0 +1,90 @@
|
|||
// Package err113 is a Golang linter to check the errors handling expressions
|
||||
package err113
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"go/ast"
|
||||
"go/printer"
|
||||
"go/token"
|
||||
|
||||
"golang.org/x/tools/go/analysis"
|
||||
)
|
||||
|
||||
// NewAnalyzer creates a new analysis.Analyzer instance tuned to run err113 checks
|
||||
func NewAnalyzer() *analysis.Analyzer {
|
||||
return &analysis.Analyzer{
|
||||
Name: "err113",
|
||||
Doc: "checks the error handling rules according to the Go 1.13 new error type",
|
||||
Run: run,
|
||||
}
|
||||
}
|
||||
|
||||
func run(pass *analysis.Pass) (interface{}, error) {
|
||||
for _, file := range pass.Files {
|
||||
tlds := enumerateFileDecls(file)
|
||||
|
||||
ast.Inspect(
|
||||
file,
|
||||
func(n ast.Node) bool {
|
||||
return inspectComparision(pass, n) &&
|
||||
inspectDefinition(pass, tlds, n)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// render returns the pretty-print of the given node
|
||||
func render(fset *token.FileSet, x interface{}) string {
|
||||
var buf bytes.Buffer
|
||||
if err := printer.Fprint(&buf, fset, x); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func enumerateFileDecls(f *ast.File) map[*ast.CallExpr]struct{} {
|
||||
res := make(map[*ast.CallExpr]struct{})
|
||||
|
||||
var ces []*ast.CallExpr // nolint: prealloc
|
||||
|
||||
for _, d := range f.Decls {
|
||||
ces = append(ces, enumerateDeclVars(d)...)
|
||||
}
|
||||
|
||||
for _, ce := range ces {
|
||||
res[ce] = struct{}{}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func enumerateDeclVars(d ast.Decl) (res []*ast.CallExpr) {
|
||||
td, ok := d.(*ast.GenDecl)
|
||||
if !ok || td.Tok != token.VAR {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, s := range td.Specs {
|
||||
res = append(res, enumerateSpecValues(s)...)
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
func enumerateSpecValues(s ast.Spec) (res []*ast.CallExpr) {
|
||||
vs, ok := s.(*ast.ValueSpec)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
for _, v := range vs.Values {
|
||||
if ce, ok := v.(*ast.CallExpr); ok {
|
||||
res = append(res, ce)
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
module github.com/Djarvur/go-err113
|
||||
|
||||
go 1.13
|
||||
|
||||
require golang.org/x/tools v0.0.0-20200324003944-a576cf524670
|
|
@ -0,0 +1,20 @@
|
|||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/mod v0.2.0 h1:KU7oHjnv3XNWfa5COkzUifxZmxp1TyI7ImMXqFxLwvQ=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20200324003944-a576cf524670 h1:fW7EP/GZqIvbHessHd1PLca+77TBOsRBqtaybMgXJq8=
|
||||
golang.org/x/tools v0.0.0-20200324003944-a576cf524670/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
|
@ -0,0 +1,29 @@
|
|||
language: go
|
||||
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- 1.10.x
|
||||
- 1.11.x
|
||||
- 1.12.x
|
||||
- tip
|
||||
|
||||
# Setting sudo access to false will let Travis CI use containers rather than
|
||||
# VMs to run the tests. For more details see:
|
||||
# - http://docs.travis-ci.com/user/workers/container-based-infrastructure/
|
||||
# - http://docs.travis-ci.com/user/workers/standard-infrastructure/
|
||||
sudo: false
|
||||
|
||||
script:
|
||||
- make setup
|
||||
- make test
|
||||
|
||||
notifications:
|
||||
webhooks:
|
||||
urls:
|
||||
- https://webhooks.gitter.im/e/06e3328629952dabe3e0
|
||||
on_success: change # options: [always|never|change] default: always
|
||||
on_failure: always # options: [always|never|change] default: always
|
||||
on_start: never # options: [always|never|change] default: always
|
|
@ -0,0 +1,109 @@
|
|||
# 1.5.0 (2019-09-11)
|
||||
|
||||
## Added
|
||||
|
||||
- #103: Add basic fuzzing for `NewVersion()` (thanks @jesse-c)
|
||||
|
||||
## Changed
|
||||
|
||||
- #82: Clarify wildcard meaning in range constraints and update tests for it (thanks @greysteil)
|
||||
- #83: Clarify caret operator range for pre-1.0.0 dependencies (thanks @greysteil)
|
||||
- #72: Adding docs comment pointing to vert for a cli
|
||||
- #71: Update the docs on pre-release comparator handling
|
||||
- #89: Test with new go versions (thanks @thedevsaddam)
|
||||
- #87: Added $ to ValidPrerelease for better validation (thanks @jeremycarroll)
|
||||
|
||||
## Fixed
|
||||
|
||||
- #78: Fix unchecked error in example code (thanks @ravron)
|
||||
- #70: Fix the handling of pre-releases and the 0.0.0 release edge case
|
||||
- #97: Fixed copyright file for proper display on GitHub
|
||||
- #107: Fix handling prerelease when sorting alphanum and num
|
||||
- #109: Fixed where Validate sometimes returns wrong message on error
|
||||
|
||||
# 1.4.2 (2018-04-10)
|
||||
|
||||
## Changed
|
||||
- #72: Updated the docs to point to vert for a console appliaction
|
||||
- #71: Update the docs on pre-release comparator handling
|
||||
|
||||
## Fixed
|
||||
- #70: Fix the handling of pre-releases and the 0.0.0 release edge case
|
||||
|
||||
# 1.4.1 (2018-04-02)
|
||||
|
||||
## Fixed
|
||||
- Fixed #64: Fix pre-release precedence issue (thanks @uudashr)
|
||||
|
||||
# 1.4.0 (2017-10-04)
|
||||
|
||||
## Changed
|
||||
- #61: Update NewVersion to parse ints with a 64bit int size (thanks @zknill)
|
||||
|
||||
# 1.3.1 (2017-07-10)
|
||||
|
||||
## Fixed
|
||||
- Fixed #57: number comparisons in prerelease sometimes inaccurate
|
||||
|
||||
# 1.3.0 (2017-05-02)
|
||||
|
||||
## Added
|
||||
- #45: Added json (un)marshaling support (thanks @mh-cbon)
|
||||
- Stability marker. See https://masterminds.github.io/stability/
|
||||
|
||||
## Fixed
|
||||
- #51: Fix handling of single digit tilde constraint (thanks @dgodd)
|
||||
|
||||
## Changed
|
||||
- #55: The godoc icon moved from png to svg
|
||||
|
||||
# 1.2.3 (2017-04-03)
|
||||
|
||||
## Fixed
|
||||
- #46: Fixed 0.x.x and 0.0.x in constraints being treated as *
|
||||
|
||||
# Release 1.2.2 (2016-12-13)
|
||||
|
||||
## Fixed
|
||||
- #34: Fixed issue where hyphen range was not working with pre-release parsing.
|
||||
|
||||
# Release 1.2.1 (2016-11-28)
|
||||
|
||||
## Fixed
|
||||
- #24: Fixed edge case issue where constraint "> 0" does not handle "0.0.1-alpha"
|
||||
properly.
|
||||
|
||||
# Release 1.2.0 (2016-11-04)
|
||||
|
||||
## Added
|
||||
- #20: Added MustParse function for versions (thanks @adamreese)
|
||||
- #15: Added increment methods on versions (thanks @mh-cbon)
|
||||
|
||||
## Fixed
|
||||
- Issue #21: Per the SemVer spec (section 9) a pre-release is unstable and
|
||||
might not satisfy the intended compatibility. The change here ignores pre-releases
|
||||
on constraint checks (e.g., ~ or ^) when a pre-release is not part of the
|
||||
constraint. For example, `^1.2.3` will ignore pre-releases while
|
||||
`^1.2.3-alpha` will include them.
|
||||
|
||||
# Release 1.1.1 (2016-06-30)
|
||||
|
||||
## Changed
|
||||
- Issue #9: Speed up version comparison performance (thanks @sdboyer)
|
||||
- Issue #8: Added benchmarks (thanks @sdboyer)
|
||||
- Updated Go Report Card URL to new location
|
||||
- Updated Readme to add code snippet formatting (thanks @mh-cbon)
|
||||
- Updating tagging to v[SemVer] structure for compatibility with other tools.
|
||||
|
||||
# Release 1.1.0 (2016-03-11)
|
||||
|
||||
- Issue #2: Implemented validation to provide reasons a versions failed a
|
||||
constraint.
|
||||
|
||||
# Release 1.0.1 (2015-12-31)
|
||||
|
||||
- Fixed #1: * constraint failing on valid versions.
|
||||
|
||||
# Release 1.0.0 (2015-10-20)
|
||||
|
||||
- Initial release
|
|
@ -0,0 +1,19 @@
|
|||
Copyright (C) 2014-2019, Matt Butcher and Matt Farina
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -0,0 +1,36 @@
|
|||
.PHONY: setup
|
||||
setup:
|
||||
go get -u gopkg.in/alecthomas/gometalinter.v1
|
||||
gometalinter.v1 --install
|
||||
|
||||
.PHONY: test
|
||||
test: validate lint
|
||||
@echo "==> Running tests"
|
||||
go test -v
|
||||
|
||||
.PHONY: validate
|
||||
validate:
|
||||
@echo "==> Running static validations"
|
||||
@gometalinter.v1 \
|
||||
--disable-all \
|
||||
--enable deadcode \
|
||||
--severity deadcode:error \
|
||||
--enable gofmt \
|
||||
--enable gosimple \
|
||||
--enable ineffassign \
|
||||
--enable misspell \
|
||||
--enable vet \
|
||||
--tests \
|
||||
--vendor \
|
||||
--deadline 60s \
|
||||
./... || exit_code=1
|
||||
|
||||
.PHONY: lint
|
||||
lint:
|
||||
@echo "==> Running linters"
|
||||
@gometalinter.v1 \
|
||||
--disable-all \
|
||||
--enable golint \
|
||||
--vendor \
|
||||
--deadline 60s \
|
||||
./... || :
|
|
@ -0,0 +1,194 @@
|
|||
# SemVer
|
||||
|
||||
The `semver` package provides the ability to work with [Semantic Versions](http://semver.org) in Go. Specifically it provides the ability to:
|
||||
|
||||
* Parse semantic versions
|
||||
* Sort semantic versions
|
||||
* Check if a semantic version fits within a set of constraints
|
||||
* Optionally work with a `v` prefix
|
||||
|
||||
[![Stability:
|
||||
Active](https://masterminds.github.io/stability/active.svg)](https://masterminds.github.io/stability/active.html)
|
||||
[![Build Status](https://travis-ci.org/Masterminds/semver.svg)](https://travis-ci.org/Masterminds/semver) [![Build status](https://ci.appveyor.com/api/projects/status/jfk66lib7hb985k8/branch/master?svg=true&passingText=windows%20build%20passing&failingText=windows%20build%20failing)](https://ci.appveyor.com/project/mattfarina/semver/branch/master) [![GoDoc](https://godoc.org/github.com/Masterminds/semver?status.svg)](https://godoc.org/github.com/Masterminds/semver) [![Go Report Card](https://goreportcard.com/badge/github.com/Masterminds/semver)](https://goreportcard.com/report/github.com/Masterminds/semver)
|
||||
|
||||
If you are looking for a command line tool for version comparisons please see
|
||||
[vert](https://github.com/Masterminds/vert) which uses this library.
|
||||
|
||||
## Parsing Semantic Versions
|
||||
|
||||
To parse a semantic version use the `NewVersion` function. For example,
|
||||
|
||||
```go
|
||||
v, err := semver.NewVersion("1.2.3-beta.1+build345")
|
||||
```
|
||||
|
||||
If there is an error the version wasn't parseable. The version object has methods
|
||||
to get the parts of the version, compare it to other versions, convert the
|
||||
version back into a string, and get the original string. For more details
|
||||
please see the [documentation](https://godoc.org/github.com/Masterminds/semver).
|
||||
|
||||
## Sorting Semantic Versions
|
||||
|
||||
A set of versions can be sorted using the [`sort`](https://golang.org/pkg/sort/)
|
||||
package from the standard library. For example,
|
||||
|
||||
```go
|
||||
raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",}
|
||||
vs := make([]*semver.Version, len(raw))
|
||||
for i, r := range raw {
|
||||
v, err := semver.NewVersion(r)
|
||||
if err != nil {
|
||||
t.Errorf("Error parsing version: %s", err)
|
||||
}
|
||||
|
||||
vs[i] = v
|
||||
}
|
||||
|
||||
sort.Sort(semver.Collection(vs))
|
||||
```
|
||||
|
||||
## Checking Version Constraints
|
||||
|
||||
Checking a version against version constraints is one of the most featureful
|
||||
parts of the package.
|
||||
|
||||
```go
|
||||
c, err := semver.NewConstraint(">= 1.2.3")
|
||||
if err != nil {
|
||||
// Handle constraint not being parseable.
|
||||
}
|
||||
|
||||
v, _ := semver.NewVersion("1.3")
|
||||
if err != nil {
|
||||
// Handle version not being parseable.
|
||||
}
|
||||
// Check if the version meets the constraints. The a variable will be true.
|
||||
a := c.Check(v)
|
||||
```
|
||||
|
||||
## Basic Comparisons
|
||||
|
||||
There are two elements to the comparisons. First, a comparison string is a list
|
||||
of comma separated and comparisons. These are then separated by || separated or
|
||||
comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a
|
||||
comparison that's greater than or equal to 1.2 and less than 3.0.0 or is
|
||||
greater than or equal to 4.2.3.
|
||||
|
||||
The basic comparisons are:
|
||||
|
||||
* `=`: equal (aliased to no operator)
|
||||
* `!=`: not equal
|
||||
* `>`: greater than
|
||||
* `<`: less than
|
||||
* `>=`: greater than or equal to
|
||||
* `<=`: less than or equal to
|
||||
|
||||
## Working With Pre-release Versions
|
||||
|
||||
Pre-releases, for those not familiar with them, are used for software releases
|
||||
prior to stable or generally available releases. Examples of pre-releases include
|
||||
development, alpha, beta, and release candidate releases. A pre-release may be
|
||||
a version such as `1.2.3-beta.1` while the stable release would be `1.2.3`. In the
|
||||
order of precidence, pre-releases come before their associated releases. In this
|
||||
example `1.2.3-beta.1 < 1.2.3`.
|
||||
|
||||
According to the Semantic Version specification pre-releases may not be
|
||||
API compliant with their release counterpart. It says,
|
||||
|
||||
> A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version.
|
||||
|
||||
SemVer comparisons without a pre-release comparator will skip pre-release versions.
|
||||
For example, `>=1.2.3` will skip pre-releases when looking at a list of releases
|
||||
while `>=1.2.3-0` will evaluate and find pre-releases.
|
||||
|
||||
The reason for the `0` as a pre-release version in the example comparison is
|
||||
because pre-releases can only contain ASCII alphanumerics and hyphens (along with
|
||||
`.` separators), per the spec. Sorting happens in ASCII sort order, again per the spec. The lowest character is a `0` in ASCII sort order (see an [ASCII Table](http://www.asciitable.com/))
|
||||
|
||||
Understanding ASCII sort ordering is important because A-Z comes before a-z. That
|
||||
means `>=1.2.3-BETA` will return `1.2.3-alpha`. What you might expect from case
|
||||
sensitivity doesn't apply here. This is due to ASCII sort ordering which is what
|
||||
the spec specifies.
|
||||
|
||||
## Hyphen Range Comparisons
|
||||
|
||||
There are multiple methods to handle ranges and the first is hyphens ranges.
|
||||
These look like:
|
||||
|
||||
* `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5`
|
||||
* `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5`
|
||||
|
||||
## Wildcards In Comparisons
|
||||
|
||||
The `x`, `X`, and `*` characters can be used as a wildcard character. This works
|
||||
for all comparison operators. When used on the `=` operator it falls
|
||||
back to the pack level comparison (see tilde below). For example,
|
||||
|
||||
* `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0`
|
||||
* `>= 1.2.x` is equivalent to `>= 1.2.0`
|
||||
* `<= 2.x` is equivalent to `< 3`
|
||||
* `*` is equivalent to `>= 0.0.0`
|
||||
|
||||
## Tilde Range Comparisons (Patch)
|
||||
|
||||
The tilde (`~`) comparison operator is for patch level ranges when a minor
|
||||
version is specified and major level changes when the minor number is missing.
|
||||
For example,
|
||||
|
||||
* `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0`
|
||||
* `~1` is equivalent to `>= 1, < 2`
|
||||
* `~2.3` is equivalent to `>= 2.3, < 2.4`
|
||||
* `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0`
|
||||
* `~1.x` is equivalent to `>= 1, < 2`
|
||||
|
||||
## Caret Range Comparisons (Major)
|
||||
|
||||
The caret (`^`) comparison operator is for major level changes. This is useful
|
||||
when comparisons of API versions as a major change is API breaking. For example,
|
||||
|
||||
* `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0`
|
||||
* `^0.0.1` is equivalent to `>= 0.0.1, < 1.0.0`
|
||||
* `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0`
|
||||
* `^2.3` is equivalent to `>= 2.3, < 3`
|
||||
* `^2.x` is equivalent to `>= 2.0.0, < 3`
|
||||
|
||||
# Validation
|
||||
|
||||
In addition to testing a version against a constraint, a version can be validated
|
||||
against a constraint. When validation fails a slice of errors containing why a
|
||||
version didn't meet the constraint is returned. For example,
|
||||
|
||||
```go
|
||||
c, err := semver.NewConstraint("<= 1.2.3, >= 1.4")
|
||||
if err != nil {
|
||||
// Handle constraint not being parseable.
|
||||
}
|
||||
|
||||
v, _ := semver.NewVersion("1.3")
|
||||
if err != nil {
|
||||
// Handle version not being parseable.
|
||||
}
|
||||
|
||||
// Validate a version against a constraint.
|
||||
a, msgs := c.Validate(v)
|
||||
// a is false
|
||||
for _, m := range msgs {
|
||||
fmt.Println(m)
|
||||
|
||||
// Loops over the errors which would read
|
||||
// "1.3 is greater than 1.2.3"
|
||||
// "1.3 is less than 1.4"
|
||||
}
|
||||
```
|
||||
|
||||
# Fuzzing
|
||||
|
||||
[dvyukov/go-fuzz](https://github.com/dvyukov/go-fuzz) is used for fuzzing.
|
||||
|
||||
1. `go-fuzz-build`
|
||||
2. `go-fuzz -workdir=fuzz`
|
||||
|
||||
# Contribute
|
||||
|
||||
If you find an issue or want to contribute please file an [issue](https://github.com/Masterminds/semver/issues)
|
||||
or [create a pull request](https://github.com/Masterminds/semver/pulls).
|
|
@ -0,0 +1,44 @@
|
|||
version: build-{build}.{branch}
|
||||
|
||||
clone_folder: C:\gopath\src\github.com\Masterminds\semver
|
||||
shallow_clone: true
|
||||
|
||||
environment:
|
||||
GOPATH: C:\gopath
|
||||
|
||||
platform:
|
||||
- x64
|
||||
|
||||
install:
|
||||
- go version
|
||||
- go env
|
||||
- go get -u gopkg.in/alecthomas/gometalinter.v1
|
||||
- set PATH=%PATH%;%GOPATH%\bin
|
||||
- gometalinter.v1.exe --install
|
||||
|
||||
build_script:
|
||||
- go install -v ./...
|
||||
|
||||
test_script:
|
||||
- "gometalinter.v1 \
|
||||
--disable-all \
|
||||
--enable deadcode \
|
||||
--severity deadcode:error \
|
||||
--enable gofmt \
|
||||
--enable gosimple \
|
||||
--enable ineffassign \
|
||||
--enable misspell \
|
||||
--enable vet \
|
||||
--tests \
|
||||
--vendor \
|
||||
--deadline 60s \
|
||||
./... || exit_code=1"
|
||||
- "gometalinter.v1 \
|
||||
--disable-all \
|
||||
--enable golint \
|
||||
--vendor \
|
||||
--deadline 60s \
|
||||
./... || :"
|
||||
- go test -v
|
||||
|
||||
deploy: off
|
|
@ -0,0 +1,24 @@
|
|||
package semver
|
||||
|
||||
// Collection is a collection of Version instances and implements the sort
|
||||
// interface. See the sort package for more details.
|
||||
// https://golang.org/pkg/sort/
|
||||
type Collection []*Version
|
||||
|
||||
// Len returns the length of a collection. The number of Version instances
|
||||
// on the slice.
|
||||
func (c Collection) Len() int {
|
||||
return len(c)
|
||||
}
|
||||
|
||||
// Less is needed for the sort interface to compare two Version objects on the
|
||||
// slice. If checks if one is less than the other.
|
||||
func (c Collection) Less(i, j int) bool {
|
||||
return c[i].LessThan(c[j])
|
||||
}
|
||||
|
||||
// Swap is needed for the sort interface to replace the Version objects
|
||||
// at two different positions in the slice.
|
||||
func (c Collection) Swap(i, j int) {
|
||||
c[i], c[j] = c[j], c[i]
|
||||
}
|
|
@ -0,0 +1,423 @@
|
|||
package semver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Constraints is one or more constraint that a semantic version can be
|
||||
// checked against.
|
||||
type Constraints struct {
|
||||
constraints [][]*constraint
|
||||
}
|
||||
|
||||
// NewConstraint returns a Constraints instance that a Version instance can
|
||||
// be checked against. If there is a parse error it will be returned.
|
||||
func NewConstraint(c string) (*Constraints, error) {
|
||||
|
||||
// Rewrite - ranges into a comparison operation.
|
||||
c = rewriteRange(c)
|
||||
|
||||
ors := strings.Split(c, "||")
|
||||
or := make([][]*constraint, len(ors))
|
||||
for k, v := range ors {
|
||||
cs := strings.Split(v, ",")
|
||||
result := make([]*constraint, len(cs))
|
||||
for i, s := range cs {
|
||||
pc, err := parseConstraint(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
result[i] = pc
|
||||
}
|
||||
or[k] = result
|
||||
}
|
||||
|
||||
o := &Constraints{constraints: or}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// Check tests if a version satisfies the constraints.
|
||||
func (cs Constraints) Check(v *Version) bool {
|
||||
// loop over the ORs and check the inner ANDs
|
||||
for _, o := range cs.constraints {
|
||||
joy := true
|
||||
for _, c := range o {
|
||||
if !c.check(v) {
|
||||
joy = false
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if joy {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Validate checks if a version satisfies a constraint. If not a slice of
|
||||
// reasons for the failure are returned in addition to a bool.
|
||||
func (cs Constraints) Validate(v *Version) (bool, []error) {
|
||||
// loop over the ORs and check the inner ANDs
|
||||
var e []error
|
||||
|
||||
// Capture the prerelease message only once. When it happens the first time
|
||||
// this var is marked
|
||||
var prerelesase bool
|
||||
for _, o := range cs.constraints {
|
||||
joy := true
|
||||
for _, c := range o {
|
||||
// Before running the check handle the case there the version is
|
||||
// a prerelease and the check is not searching for prereleases.
|
||||
if c.con.pre == "" && v.pre != "" {
|
||||
if !prerelesase {
|
||||
em := fmt.Errorf("%s is a prerelease version and the constraint is only looking for release versions", v)
|
||||
e = append(e, em)
|
||||
prerelesase = true
|
||||
}
|
||||
joy = false
|
||||
|
||||
} else {
|
||||
|
||||
if !c.check(v) {
|
||||
em := fmt.Errorf(c.msg, v, c.orig)
|
||||
e = append(e, em)
|
||||
joy = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if joy {
|
||||
return true, []error{}
|
||||
}
|
||||
}
|
||||
|
||||
return false, e
|
||||
}
|
||||
|
||||
var constraintOps map[string]cfunc
|
||||
var constraintMsg map[string]string
|
||||
var constraintRegex *regexp.Regexp
|
||||
|
||||
func init() {
|
||||
constraintOps = map[string]cfunc{
|
||||
"": constraintTildeOrEqual,
|
||||
"=": constraintTildeOrEqual,
|
||||
"!=": constraintNotEqual,
|
||||
">": constraintGreaterThan,
|
||||
"<": constraintLessThan,
|
||||
">=": constraintGreaterThanEqual,
|
||||
"=>": constraintGreaterThanEqual,
|
||||
"<=": constraintLessThanEqual,
|
||||
"=<": constraintLessThanEqual,
|
||||
"~": constraintTilde,
|
||||
"~>": constraintTilde,
|
||||
"^": constraintCaret,
|
||||
}
|
||||
|
||||
constraintMsg = map[string]string{
|
||||
"": "%s is not equal to %s",
|
||||
"=": "%s is not equal to %s",
|
||||
"!=": "%s is equal to %s",
|
||||
">": "%s is less than or equal to %s",
|
||||
"<": "%s is greater than or equal to %s",
|
||||
">=": "%s is less than %s",
|
||||
"=>": "%s is less than %s",
|
||||
"<=": "%s is greater than %s",
|
||||
"=<": "%s is greater than %s",
|
||||
"~": "%s does not have same major and minor version as %s",
|
||||
"~>": "%s does not have same major and minor version as %s",
|
||||
"^": "%s does not have same major version as %s",
|
||||
}
|
||||
|
||||
ops := make([]string, 0, len(constraintOps))
|
||||
for k := range constraintOps {
|
||||
ops = append(ops, regexp.QuoteMeta(k))
|
||||
}
|
||||
|
||||
constraintRegex = regexp.MustCompile(fmt.Sprintf(
|
||||
`^\s*(%s)\s*(%s)\s*$`,
|
||||
strings.Join(ops, "|"),
|
||||
cvRegex))
|
||||
|
||||
constraintRangeRegex = regexp.MustCompile(fmt.Sprintf(
|
||||
`\s*(%s)\s+-\s+(%s)\s*`,
|
||||
cvRegex, cvRegex))
|
||||
}
|
||||
|
||||
// An individual constraint
|
||||
type constraint struct {
|
||||
// The callback function for the restraint. It performs the logic for
|
||||
// the constraint.
|
||||
function cfunc
|
||||
|
||||
msg string
|
||||
|
||||
// The version used in the constraint check. For example, if a constraint
|
||||
// is '<= 2.0.0' the con a version instance representing 2.0.0.
|
||||
con *Version
|
||||
|
||||
// The original parsed version (e.g., 4.x from != 4.x)
|
||||
orig string
|
||||
|
||||
// When an x is used as part of the version (e.g., 1.x)
|
||||
minorDirty bool
|
||||
dirty bool
|
||||
patchDirty bool
|
||||
}
|
||||
|
||||
// Check if a version meets the constraint
|
||||
func (c *constraint) check(v *Version) bool {
|
||||
return c.function(v, c)
|
||||
}
|
||||
|
||||
type cfunc func(v *Version, c *constraint) bool
|
||||
|
||||
func parseConstraint(c string) (*constraint, error) {
|
||||
m := constraintRegex.FindStringSubmatch(c)
|
||||
if m == nil {
|
||||
return nil, fmt.Errorf("improper constraint: %s", c)
|
||||
}
|
||||
|
||||
ver := m[2]
|
||||
orig := ver
|
||||
minorDirty := false
|
||||
patchDirty := false
|
||||
dirty := false
|
||||
if isX(m[3]) {
|
||||
ver = "0.0.0"
|
||||
dirty = true
|
||||
} else if isX(strings.TrimPrefix(m[4], ".")) || m[4] == "" {
|
||||
minorDirty = true
|
||||
dirty = true
|
||||
ver = fmt.Sprintf("%s.0.0%s", m[3], m[6])
|
||||
} else if isX(strings.TrimPrefix(m[5], ".")) {
|
||||
dirty = true
|
||||
patchDirty = true
|
||||
ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6])
|
||||
}
|
||||
|
||||
con, err := NewVersion(ver)
|
||||
if err != nil {
|
||||
|
||||
// The constraintRegex should catch any regex parsing errors. So,
|
||||
// we should never get here.
|
||||
return nil, errors.New("constraint Parser Error")
|
||||
}
|
||||
|
||||
cs := &constraint{
|
||||
function: constraintOps[m[1]],
|
||||
msg: constraintMsg[m[1]],
|
||||
con: con,
|
||||
orig: orig,
|
||||
minorDirty: minorDirty,
|
||||
patchDirty: patchDirty,
|
||||
dirty: dirty,
|
||||
}
|
||||
return cs, nil
|
||||
}
|
||||
|
||||
// Constraint functions
|
||||
func constraintNotEqual(v *Version, c *constraint) bool {
|
||||
if c.dirty {
|
||||
|
||||
// If there is a pre-release on the version but the constraint isn't looking
|
||||
// for them assume that pre-releases are not compatible. See issue 21 for
|
||||
// more details.
|
||||
if v.Prerelease() != "" && c.con.Prerelease() == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if c.con.Major() != v.Major() {
|
||||
return true
|
||||
}
|
||||
if c.con.Minor() != v.Minor() && !c.minorDirty {
|
||||
return true
|
||||
} else if c.minorDirty {
|
||||
return false
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return !v.Equal(c.con)
|
||||
}
|
||||
|
||||
func constraintGreaterThan(v *Version, c *constraint) bool {
|
||||
|
||||
// If there is a pre-release on the version but the constraint isn't looking
|
||||
// for them assume that pre-releases are not compatible. See issue 21 for
|
||||
// more details.
|
||||
if v.Prerelease() != "" && c.con.Prerelease() == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
return v.Compare(c.con) == 1
|
||||
}
|
||||
|
||||
func constraintLessThan(v *Version, c *constraint) bool {
|
||||
// If there is a pre-release on the version but the constraint isn't looking
|
||||
// for them assume that pre-releases are not compatible. See issue 21 for
|
||||
// more details.
|
||||
if v.Prerelease() != "" && c.con.Prerelease() == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if !c.dirty {
|
||||
return v.Compare(c.con) < 0
|
||||
}
|
||||
|
||||
if v.Major() > c.con.Major() {
|
||||
return false
|
||||
} else if v.Minor() > c.con.Minor() && !c.minorDirty {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func constraintGreaterThanEqual(v *Version, c *constraint) bool {
|
||||
|
||||
// If there is a pre-release on the version but the constraint isn't looking
|
||||
// for them assume that pre-releases are not compatible. See issue 21 for
|
||||
// more details.
|
||||
if v.Prerelease() != "" && c.con.Prerelease() == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
return v.Compare(c.con) >= 0
|
||||
}
|
||||
|
||||
func constraintLessThanEqual(v *Version, c *constraint) bool {
|
||||
// If there is a pre-release on the version but the constraint isn't looking
|
||||
// for them assume that pre-releases are not compatible. See issue 21 for
|
||||
// more details.
|
||||
if v.Prerelease() != "" && c.con.Prerelease() == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if !c.dirty {
|
||||
return v.Compare(c.con) <= 0
|
||||
}
|
||||
|
||||
if v.Major() > c.con.Major() {
|
||||
return false
|
||||
} else if v.Minor() > c.con.Minor() && !c.minorDirty {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// ~*, ~>* --> >= 0.0.0 (any)
|
||||
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0, <3.0.0
|
||||
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0, <2.1.0
|
||||
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0
|
||||
// ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0
|
||||
// ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0
|
||||
func constraintTilde(v *Version, c *constraint) bool {
|
||||
// If there is a pre-release on the version but the constraint isn't looking
|
||||
// for them assume that pre-releases are not compatible. See issue 21 for
|
||||
// more details.
|
||||
if v.Prerelease() != "" && c.con.Prerelease() == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if v.LessThan(c.con) {
|
||||
return false
|
||||
}
|
||||
|
||||
// ~0.0.0 is a special case where all constraints are accepted. It's
|
||||
// equivalent to >= 0.0.0.
|
||||
if c.con.Major() == 0 && c.con.Minor() == 0 && c.con.Patch() == 0 &&
|
||||
!c.minorDirty && !c.patchDirty {
|
||||
return true
|
||||
}
|
||||
|
||||
if v.Major() != c.con.Major() {
|
||||
return false
|
||||
}
|
||||
|
||||
if v.Minor() != c.con.Minor() && !c.minorDirty {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// When there is a .x (dirty) status it automatically opts in to ~. Otherwise
|
||||
// it's a straight =
|
||||
func constraintTildeOrEqual(v *Version, c *constraint) bool {
|
||||
// If there is a pre-release on the version but the constraint isn't looking
|
||||
// for them assume that pre-releases are not compatible. See issue 21 for
|
||||
// more details.
|
||||
if v.Prerelease() != "" && c.con.Prerelease() == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if c.dirty {
|
||||
c.msg = constraintMsg["~"]
|
||||
return constraintTilde(v, c)
|
||||
}
|
||||
|
||||
return v.Equal(c.con)
|
||||
}
|
||||
|
||||
// ^* --> (any)
|
||||
// ^2, ^2.x, ^2.x.x --> >=2.0.0, <3.0.0
|
||||
// ^2.0, ^2.0.x --> >=2.0.0, <3.0.0
|
||||
// ^1.2, ^1.2.x --> >=1.2.0, <2.0.0
|
||||
// ^1.2.3 --> >=1.2.3, <2.0.0
|
||||
// ^1.2.0 --> >=1.2.0, <2.0.0
|
||||
func constraintCaret(v *Version, c *constraint) bool {
|
||||
// If there is a pre-release on the version but the constraint isn't looking
|
||||
// for them assume that pre-releases are not compatible. See issue 21 for
|
||||
// more details.
|
||||
if v.Prerelease() != "" && c.con.Prerelease() == "" {
|
||||
return false
|
||||
}
|
||||
|
||||
if v.LessThan(c.con) {
|
||||
return false
|
||||
}
|
||||
|
||||
if v.Major() != c.con.Major() {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var constraintRangeRegex *regexp.Regexp
|
||||
|
||||
const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` +
|
||||
`(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` +
|
||||
`(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?`
|
||||
|
||||
func isX(x string) bool {
|
||||
switch x {
|
||||
case "x", "*", "X":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func rewriteRange(i string) string {
|
||||
m := constraintRangeRegex.FindAllStringSubmatch(i, -1)
|
||||
if m == nil {
|
||||
return i
|
||||
}
|
||||
o := i
|
||||
for _, v := range m {
|
||||
t := fmt.Sprintf(">= %s, <= %s", v[1], v[11])
|
||||
o = strings.Replace(o, v[0], t, 1)
|
||||
}
|
||||
|
||||
return o
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
/*
|
||||
Package semver provides the ability to work with Semantic Versions (http://semver.org) in Go.
|
||||
|
||||
Specifically it provides the ability to:
|
||||
|
||||
* Parse semantic versions
|
||||
* Sort semantic versions
|
||||
* Check if a semantic version fits within a set of constraints
|
||||
* Optionally work with a `v` prefix
|
||||
|
||||
Parsing Semantic Versions
|
||||
|
||||
To parse a semantic version use the `NewVersion` function. For example,
|
||||
|
||||
v, err := semver.NewVersion("1.2.3-beta.1+build345")
|
||||
|
||||
If there is an error the version wasn't parseable. The version object has methods
|
||||
to get the parts of the version, compare it to other versions, convert the
|
||||
version back into a string, and get the original string. For more details
|
||||
please see the documentation at https://godoc.org/github.com/Masterminds/semver.
|
||||
|
||||
Sorting Semantic Versions
|
||||
|
||||
A set of versions can be sorted using the `sort` package from the standard library.
|
||||
For example,
|
||||
|
||||
raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",}
|
||||
vs := make([]*semver.Version, len(raw))
|
||||
for i, r := range raw {
|
||||
v, err := semver.NewVersion(r)
|
||||
if err != nil {
|
||||
t.Errorf("Error parsing version: %s", err)
|
||||
}
|
||||
|
||||
vs[i] = v
|
||||
}
|
||||
|
||||
sort.Sort(semver.Collection(vs))
|
||||
|
||||
Checking Version Constraints
|
||||
|
||||
Checking a version against version constraints is one of the most featureful
|
||||
parts of the package.
|
||||
|
||||
c, err := semver.NewConstraint(">= 1.2.3")
|
||||
if err != nil {
|
||||
// Handle constraint not being parseable.
|
||||
}
|
||||
|
||||
v, err := semver.NewVersion("1.3")
|
||||
if err != nil {
|
||||
// Handle version not being parseable.
|
||||
}
|
||||
// Check if the version meets the constraints. The a variable will be true.
|
||||
a := c.Check(v)
|
||||
|
||||
Basic Comparisons
|
||||
|
||||
There are two elements to the comparisons. First, a comparison string is a list
|
||||
of comma separated and comparisons. These are then separated by || separated or
|
||||
comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a
|
||||
comparison that's greater than or equal to 1.2 and less than 3.0.0 or is
|
||||
greater than or equal to 4.2.3.
|
||||
|
||||
The basic comparisons are:
|
||||
|
||||
* `=`: equal (aliased to no operator)
|
||||
* `!=`: not equal
|
||||
* `>`: greater than
|
||||
* `<`: less than
|
||||
* `>=`: greater than or equal to
|
||||
* `<=`: less than or equal to
|
||||
|
||||
Hyphen Range Comparisons
|
||||
|
||||
There are multiple methods to handle ranges and the first is hyphens ranges.
|
||||
These look like:
|
||||
|
||||
* `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5`
|
||||
* `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5`
|
||||
|
||||
Wildcards In Comparisons
|
||||
|
||||
The `x`, `X`, and `*` characters can be used as a wildcard character. This works
|
||||
for all comparison operators. When used on the `=` operator it falls
|
||||
back to the pack level comparison (see tilde below). For example,
|
||||
|
||||
* `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0`
|
||||
* `>= 1.2.x` is equivalent to `>= 1.2.0`
|
||||
* `<= 2.x` is equivalent to `<= 3`
|
||||
* `*` is equivalent to `>= 0.0.0`
|
||||
|
||||
Tilde Range Comparisons (Patch)
|
||||
|
||||
The tilde (`~`) comparison operator is for patch level ranges when a minor
|
||||
version is specified and major level changes when the minor number is missing.
|
||||
For example,
|
||||
|
||||
* `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0`
|
||||
* `~1` is equivalent to `>= 1, < 2`
|
||||
* `~2.3` is equivalent to `>= 2.3, < 2.4`
|
||||
* `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0`
|
||||
* `~1.x` is equivalent to `>= 1, < 2`
|
||||
|
||||
Caret Range Comparisons (Major)
|
||||
|
||||
The caret (`^`) comparison operator is for major level changes. This is useful
|
||||
when comparisons of API versions as a major change is API breaking. For example,
|
||||
|
||||
* `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0`
|
||||
* `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0`
|
||||
* `^2.3` is equivalent to `>= 2.3, < 3`
|
||||
* `^2.x` is equivalent to `>= 2.0.0, < 3`
|
||||
*/
|
||||
package semver
|
|
@ -0,0 +1,425 @@
|
|||
package semver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// The compiled version of the regex created at init() is cached here so it
|
||||
// only needs to be created once.
|
||||
var versionRegex *regexp.Regexp
|
||||
var validPrereleaseRegex *regexp.Regexp
|
||||
|
||||
var (
|
||||
// ErrInvalidSemVer is returned a version is found to be invalid when
|
||||
// being parsed.
|
||||
ErrInvalidSemVer = errors.New("Invalid Semantic Version")
|
||||
|
||||
// ErrInvalidMetadata is returned when the metadata is an invalid format
|
||||
ErrInvalidMetadata = errors.New("Invalid Metadata string")
|
||||
|
||||
// ErrInvalidPrerelease is returned when the pre-release is an invalid format
|
||||
ErrInvalidPrerelease = errors.New("Invalid Prerelease string")
|
||||
)
|
||||
|
||||
// SemVerRegex is the regular expression used to parse a semantic version.
|
||||
const SemVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` +
|
||||
`(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` +
|
||||
`(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?`
|
||||
|
||||
// ValidPrerelease is the regular expression which validates
|
||||
// both prerelease and metadata values.
|
||||
const ValidPrerelease string = `^([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*)$`
|
||||
|
||||
// Version represents a single semantic version.
|
||||
type Version struct {
|
||||
major, minor, patch int64
|
||||
pre string
|
||||
metadata string
|
||||
original string
|
||||
}
|
||||
|
||||
func init() {
|
||||
versionRegex = regexp.MustCompile("^" + SemVerRegex + "$")
|
||||
validPrereleaseRegex = regexp.MustCompile(ValidPrerelease)
|
||||
}
|
||||
|
||||
// NewVersion parses a given version and returns an instance of Version or
|
||||
// an error if unable to parse the version.
|
||||
func NewVersion(v string) (*Version, error) {
|
||||
m := versionRegex.FindStringSubmatch(v)
|
||||
if m == nil {
|
||||
return nil, ErrInvalidSemVer
|
||||
}
|
||||
|
||||
sv := &Version{
|
||||
metadata: m[8],
|
||||
pre: m[5],
|
||||
original: v,
|
||||
}
|
||||
|
||||
var temp int64
|
||||
temp, err := strconv.ParseInt(m[1], 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error parsing version segment: %s", err)
|
||||
}
|
||||
sv.major = temp
|
||||
|
||||
if m[2] != "" {
|
||||
temp, err = strconv.ParseInt(strings.TrimPrefix(m[2], "."), 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error parsing version segment: %s", err)
|
||||
}
|
||||
sv.minor = temp
|
||||
} else {
|
||||
sv.minor = 0
|
||||
}
|
||||
|
||||
if m[3] != "" {
|
||||
temp, err = strconv.ParseInt(strings.TrimPrefix(m[3], "."), 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error parsing version segment: %s", err)
|
||||
}
|
||||
sv.patch = temp
|
||||
} else {
|
||||
sv.patch = 0
|
||||
}
|
||||
|
||||
return sv, nil
|
||||
}
|
||||
|
||||
// MustParse parses a given version and panics on error.
|
||||
func MustParse(v string) *Version {
|
||||
sv, err := NewVersion(v)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return sv
|
||||
}
|
||||
|
||||
// String converts a Version object to a string.
|
||||
// Note, if the original version contained a leading v this version will not.
|
||||
// See the Original() method to retrieve the original value. Semantic Versions
|
||||
// don't contain a leading v per the spec. Instead it's optional on
|
||||
// implementation.
|
||||
func (v *Version) String() string {
|
||||
var buf bytes.Buffer
|
||||
|
||||
fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch)
|
||||
if v.pre != "" {
|
||||
fmt.Fprintf(&buf, "-%s", v.pre)
|
||||
}
|
||||
if v.metadata != "" {
|
||||
fmt.Fprintf(&buf, "+%s", v.metadata)
|
||||
}
|
||||
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// Original returns the original value passed in to be parsed.
|
||||
func (v *Version) Original() string {
|
||||
return v.original
|
||||
}
|
||||
|
||||
// Major returns the major version.
|
||||
func (v *Version) Major() int64 {
|
||||
return v.major
|
||||
}
|
||||
|
||||
// Minor returns the minor version.
|
||||
func (v *Version) Minor() int64 {
|
||||
return v.minor
|
||||
}
|
||||
|
||||
// Patch returns the patch version.
|
||||
func (v *Version) Patch() int64 {
|
||||
return v.patch
|
||||
}
|
||||
|
||||
// Prerelease returns the pre-release version.
|
||||
func (v *Version) Prerelease() string {
|
||||
return v.pre
|
||||
}
|
||||
|
||||
// Metadata returns the metadata on the version.
|
||||
func (v *Version) Metadata() string {
|
||||
return v.metadata
|
||||
}
|
||||
|
||||
// originalVPrefix returns the original 'v' prefix if any.
|
||||
func (v *Version) originalVPrefix() string {
|
||||
|
||||
// Note, only lowercase v is supported as a prefix by the parser.
|
||||
if v.original != "" && v.original[:1] == "v" {
|
||||
return v.original[:1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// IncPatch produces the next patch version.
|
||||
// If the current version does not have prerelease/metadata information,
|
||||
// it unsets metadata and prerelease values, increments patch number.
|
||||
// If the current version has any of prerelease or metadata information,
|
||||
// it unsets both values and keeps curent patch value
|
||||
func (v Version) IncPatch() Version {
|
||||
vNext := v
|
||||
// according to http://semver.org/#spec-item-9
|
||||
// Pre-release versions have a lower precedence than the associated normal version.
|
||||
// according to http://semver.org/#spec-item-10
|
||||
// Build metadata SHOULD be ignored when determining version precedence.
|
||||
if v.pre != "" {
|
||||
vNext.metadata = ""
|
||||
vNext.pre = ""
|
||||
} else {
|
||||
vNext.metadata = ""
|
||||
vNext.pre = ""
|
||||
vNext.patch = v.patch + 1
|
||||
}
|
||||
vNext.original = v.originalVPrefix() + "" + vNext.String()
|
||||
return vNext
|
||||
}
|
||||
|
||||
// IncMinor produces the next minor version.
|
||||
// Sets patch to 0.
|
||||
// Increments minor number.
|
||||
// Unsets metadata.
|
||||
// Unsets prerelease status.
|
||||
func (v Version) IncMinor() Version {
|
||||
vNext := v
|
||||
vNext.metadata = ""
|
||||
vNext.pre = ""
|
||||
vNext.patch = 0
|
||||
vNext.minor = v.minor + 1
|
||||
vNext.original = v.originalVPrefix() + "" + vNext.String()
|
||||
return vNext
|
||||
}
|
||||
|
||||
// IncMajor produces the next major version.
|
||||
// Sets patch to 0.
|
||||
// Sets minor to 0.
|
||||
// Increments major number.
|
||||
// Unsets metadata.
|
||||
// Unsets prerelease status.
|
||||
func (v Version) IncMajor() Version {
|
||||
vNext := v
|
||||
vNext.metadata = ""
|
||||
vNext.pre = ""
|
||||
vNext.patch = 0
|
||||
vNext.minor = 0
|
||||
vNext.major = v.major + 1
|
||||
vNext.original = v.originalVPrefix() + "" + vNext.String()
|
||||
return vNext
|
||||
}
|
||||
|
||||
// SetPrerelease defines the prerelease value.
|
||||
// Value must not include the required 'hypen' prefix.
|
||||
func (v Version) SetPrerelease(prerelease string) (Version, error) {
|
||||
vNext := v
|
||||
if len(prerelease) > 0 && !validPrereleaseRegex.MatchString(prerelease) {
|
||||
return vNext, ErrInvalidPrerelease
|
||||
}
|
||||
vNext.pre = prerelease
|
||||
vNext.original = v.originalVPrefix() + "" + vNext.String()
|
||||
return vNext, nil
|
||||
}
|
||||
|
||||
// SetMetadata defines metadata value.
|
||||
// Value must not include the required 'plus' prefix.
|
||||
func (v Version) SetMetadata(metadata string) (Version, error) {
|
||||
vNext := v
|
||||
if len(metadata) > 0 && !validPrereleaseRegex.MatchString(metadata) {
|
||||
return vNext, ErrInvalidMetadata
|
||||
}
|
||||
vNext.metadata = metadata
|
||||
vNext.original = v.originalVPrefix() + "" + vNext.String()
|
||||
return vNext, nil
|
||||
}
|
||||
|
||||
// LessThan tests if one version is less than another one.
|
||||
func (v *Version) LessThan(o *Version) bool {
|
||||
return v.Compare(o) < 0
|
||||
}
|
||||
|
||||
// GreaterThan tests if one version is greater than another one.
|
||||
func (v *Version) GreaterThan(o *Version) bool {
|
||||
return v.Compare(o) > 0
|
||||
}
|
||||
|
||||
// Equal tests if two versions are equal to each other.
|
||||
// Note, versions can be equal with different metadata since metadata
|
||||
// is not considered part of the comparable version.
|
||||
func (v *Version) Equal(o *Version) bool {
|
||||
return v.Compare(o) == 0
|
||||
}
|
||||
|
||||
// Compare compares this version to another one. It returns -1, 0, or 1 if
|
||||
// the version smaller, equal, or larger than the other version.
|
||||
//
|
||||
// Versions are compared by X.Y.Z. Build metadata is ignored. Prerelease is
|
||||
// lower than the version without a prerelease.
|
||||
func (v *Version) Compare(o *Version) int {
|
||||
// Compare the major, minor, and patch version for differences. If a
|
||||
// difference is found return the comparison.
|
||||
if d := compareSegment(v.Major(), o.Major()); d != 0 {
|
||||
return d
|
||||
}
|
||||
if d := compareSegment(v.Minor(), o.Minor()); d != 0 {
|
||||
return d
|
||||
}
|
||||
if d := compareSegment(v.Patch(), o.Patch()); d != 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
// At this point the major, minor, and patch versions are the same.
|
||||
ps := v.pre
|
||||
po := o.Prerelease()
|
||||
|
||||
if ps == "" && po == "" {
|
||||
return 0
|
||||
}
|
||||
if ps == "" {
|
||||
return 1
|
||||
}
|
||||
if po == "" {
|
||||
return -1
|
||||
}
|
||||
|
||||
return comparePrerelease(ps, po)
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements JSON.Unmarshaler interface.
|
||||
func (v *Version) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
temp, err := NewVersion(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v.major = temp.major
|
||||
v.minor = temp.minor
|
||||
v.patch = temp.patch
|
||||
v.pre = temp.pre
|
||||
v.metadata = temp.metadata
|
||||
v.original = temp.original
|
||||
temp = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements JSON.Marshaler interface.
|
||||
func (v *Version) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(v.String())
|
||||
}
|
||||
|
||||
func compareSegment(v, o int64) int {
|
||||
if v < o {
|
||||
return -1
|
||||
}
|
||||
if v > o {
|
||||
return 1
|
||||
}
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
func comparePrerelease(v, o string) int {
|
||||
|
||||
// split the prelease versions by their part. The separator, per the spec,
|
||||
// is a .
|
||||
sparts := strings.Split(v, ".")
|
||||
oparts := strings.Split(o, ".")
|
||||
|
||||
// Find the longer length of the parts to know how many loop iterations to
|
||||
// go through.
|
||||
slen := len(sparts)
|
||||
olen := len(oparts)
|
||||
|
||||
l := slen
|
||||
if olen > slen {
|
||||
l = olen
|
||||
}
|
||||
|
||||
// Iterate over each part of the prereleases to compare the differences.
|
||||
for i := 0; i < l; i++ {
|
||||
// Since the lentgh of the parts can be different we need to create
|
||||
// a placeholder. This is to avoid out of bounds issues.
|
||||
stemp := ""
|
||||
if i < slen {
|
||||
stemp = sparts[i]
|
||||
}
|
||||
|
||||
otemp := ""
|
||||
if i < olen {
|
||||
otemp = oparts[i]
|
||||
}
|
||||
|
||||
d := comparePrePart(stemp, otemp)
|
||||
if d != 0 {
|
||||
return d
|
||||
}
|
||||
}
|
||||
|
||||
// Reaching here means two versions are of equal value but have different
|
||||
// metadata (the part following a +). They are not identical in string form
|
||||
// but the version comparison finds them to be equal.
|
||||
return 0
|
||||
}
|
||||
|
||||
func comparePrePart(s, o string) int {
|
||||
// Fastpath if they are equal
|
||||
if s == o {
|
||||
return 0
|
||||
}
|
||||
|
||||
// When s or o are empty we can use the other in an attempt to determine
|
||||
// the response.
|
||||
if s == "" {
|
||||
if o != "" {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
if o == "" {
|
||||
if s != "" {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// When comparing strings "99" is greater than "103". To handle
|
||||
// cases like this we need to detect numbers and compare them. According
|
||||
// to the semver spec, numbers are always positive. If there is a - at the
|
||||
// start like -99 this is to be evaluated as an alphanum. numbers always
|
||||
// have precedence over alphanum. Parsing as Uints because negative numbers
|
||||
// are ignored.
|
||||
|
||||
oi, n1 := strconv.ParseUint(o, 10, 64)
|
||||
si, n2 := strconv.ParseUint(s, 10, 64)
|
||||
|
||||
// The case where both are strings compare the strings
|
||||
if n1 != nil && n2 != nil {
|
||||
if s > o {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
} else if n1 != nil {
|
||||
// o is a string and s is a number
|
||||
return -1
|
||||
} else if n2 != nil {
|
||||
// s is a string and o is a number
|
||||
return 1
|
||||
}
|
||||
// Both are numbers
|
||||
if si > oi {
|
||||
return 1
|
||||
}
|
||||
return -1
|
||||
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
// +build gofuzz
|
||||
|
||||
package semver
|
||||
|
||||
func Fuzz(data []byte) int {
|
||||
if _, err := NewVersion(string(data)); err != nil {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, build with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
.idea
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
|
@ -0,0 +1,77 @@
|
|||
# Depguard
|
||||
|
||||
Go linter that checks package imports are in a list of acceptable packages. It
|
||||
supports a white list and black list option and can do prefix or glob matching.
|
||||
This allows you to allow imports from a whole organization or only
|
||||
allow specific packages within a repository. It is recommended to use prefix
|
||||
matching as it is faster than glob matching. The fewer glob matches the better.
|
||||
|
||||
> If a pattern is matched by prefix it does not try to match via glob.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
go get -u github.com/OpenPeeDeeP/depguard
|
||||
```
|
||||
|
||||
## Config
|
||||
|
||||
By default, Depguard looks for a file named `.depguard.json` in the current
|
||||
current working directory. If it is somewhere else, pass in the `-c` flag with
|
||||
the location of your configuration file.
|
||||
|
||||
The following is an example configuration file.
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "whitelist",
|
||||
"packages": ["github.com/OpenPeeDeeP/depguard"],
|
||||
"packageErrorMessages": {
|
||||
"github.com/OpenPeeDeeP/depguards": "Please use \"github.com/OpenPeeDeeP/depguard\","
|
||||
},
|
||||
"inTests": ["github.com/stretchr/testify"],
|
||||
"includeGoStdLib": true
|
||||
}
|
||||
```
|
||||
|
||||
- `type` can be either `whitelist` or `blacklist`. This check is case insensitive.
|
||||
If not specified the default is `blacklist`.
|
||||
- `packages` is a list of packages for the list type specified.
|
||||
- `packageErrorMessages` is a mapping from packages to the error message to display
|
||||
- `inTests` is a list of packages allowed/disallowed only in test files.
|
||||
- Set `includeGoStdLib` (`includeGoRoot` for backwards compatability) to true if you want to check the list against standard lib.
|
||||
If not specified the default is false.
|
||||
|
||||
## Gometalinter
|
||||
|
||||
The binary installation of this linter can be used with
|
||||
[Gometalinter](github.com/alecthomas/gometalinter).
|
||||
|
||||
If you use a configuration file for Gometalinter then the following will need to
|
||||
be added to your configuration file.
|
||||
|
||||
```json
|
||||
{
|
||||
"linters": {
|
||||
"depguard": {
|
||||
"command": "depguard -c path/to/config.json",
|
||||
"pattern": "PATH:LINE:COL:MESSAGE",
|
||||
"installFrom": "github.com/OpenPeeDeeP/depguard",
|
||||
"isFast": true,
|
||||
"partitionStrategy": "packages"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you prefer the command line way the following will work for you as well.
|
||||
|
||||
```bash
|
||||
gometalinter --linter='depguard:depguard -c path/to/config.json:PATH:LINE:COL:MESSAGE'
|
||||
```
|
||||
|
||||
## Golangci-lint
|
||||
|
||||
This linter was built with
|
||||
[Golangci-lint](https://github.com/golangci/golangci-lint) in mind. It is compatable
|
||||
and read their docs to see how to implement all their linters, including this one.
|
|
@ -0,0 +1,241 @@
|
|||
package depguard
|
||||
|
||||
import (
|
||||
"go/build"
|
||||
"go/token"
|
||||
"io/ioutil"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/gobwas/glob"
|
||||
"golang.org/x/tools/go/loader"
|
||||
)
|
||||
|
||||
// ListType states what kind of list is passed in.
|
||||
type ListType int
|
||||
|
||||
const (
|
||||
// LTBlacklist states the list given is a blacklist. (default)
|
||||
LTBlacklist ListType = iota
|
||||
// LTWhitelist states the list given is a whitelist.
|
||||
LTWhitelist
|
||||
)
|
||||
|
||||
// StringToListType makes it easier to turn a string into a ListType.
|
||||
// It assumes that the string representation is lower case.
|
||||
var StringToListType = map[string]ListType{
|
||||
"whitelist": LTWhitelist,
|
||||
"blacklist": LTBlacklist,
|
||||
}
|
||||
|
||||
// Issue with the package with PackageName at the Position.
|
||||
type Issue struct {
|
||||
PackageName string
|
||||
Position token.Position
|
||||
}
|
||||
|
||||
// Depguard checks imports to make sure they follow the given list and constraints.
|
||||
type Depguard struct {
|
||||
ListType ListType
|
||||
IncludeGoRoot bool
|
||||
|
||||
Packages []string
|
||||
prefixPackages []string
|
||||
globPackages []glob.Glob
|
||||
|
||||
TestPackages []string
|
||||
prefixTestPackages []string
|
||||
globTestPackages []glob.Glob
|
||||
|
||||
prefixRoot []string
|
||||
}
|
||||
|
||||
// Run checks for dependencies given the program and validates them against
|
||||
// Packages.
|
||||
func (dg *Depguard) Run(config *loader.Config, prog *loader.Program) ([]*Issue, error) {
|
||||
// Shortcut execution on an empty blacklist as that means every package is allowed
|
||||
if dg.ListType == LTBlacklist && len(dg.Packages) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if err := dg.initialize(config, prog); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
directImports, err := dg.createImportMap(prog)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var issues []*Issue
|
||||
for pkg, positions := range directImports {
|
||||
for _, pos := range positions {
|
||||
|
||||
prefixList, globList := dg.prefixPackages, dg.globPackages
|
||||
if len(dg.TestPackages) > 0 && strings.Index(pos.Filename, "_test.go") != -1 {
|
||||
prefixList, globList = dg.prefixTestPackages, dg.globTestPackages
|
||||
}
|
||||
|
||||
if dg.flagIt(pkg, prefixList, globList) {
|
||||
issues = append(issues, &Issue{
|
||||
PackageName: pkg,
|
||||
Position: pos,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
return issues, nil
|
||||
}
|
||||
|
||||
func (dg *Depguard) initialize(config *loader.Config, prog *loader.Program) error {
|
||||
// parse ordinary guarded packages
|
||||
for _, pkg := range dg.Packages {
|
||||
if strings.ContainsAny(pkg, "!?*[]{}") {
|
||||
g, err := glob.Compile(pkg, '/')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dg.globPackages = append(dg.globPackages, g)
|
||||
} else {
|
||||
dg.prefixPackages = append(dg.prefixPackages, pkg)
|
||||
}
|
||||
}
|
||||
|
||||
// Sort the packages so we can have a faster search in the array
|
||||
sort.Strings(dg.prefixPackages)
|
||||
|
||||
// parse guarded tests packages
|
||||
for _, pkg := range dg.TestPackages {
|
||||
if strings.ContainsAny(pkg, "!?*[]{}") {
|
||||
g, err := glob.Compile(pkg, '/')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dg.globTestPackages = append(dg.globTestPackages, g)
|
||||
} else {
|
||||
dg.prefixTestPackages = append(dg.prefixTestPackages, pkg)
|
||||
}
|
||||
}
|
||||
|
||||
// Sort the test packages so we can have a faster search in the array
|
||||
sort.Strings(dg.prefixTestPackages)
|
||||
|
||||
if !dg.IncludeGoRoot {
|
||||
var err error
|
||||
dg.prefixRoot, err = listRootPrefixs(config.Build)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dg *Depguard) createImportMap(prog *loader.Program) (map[string][]token.Position, error) {
|
||||
importMap := make(map[string][]token.Position)
|
||||
// For the directly imported packages
|
||||
for _, imported := range prog.InitialPackages() {
|
||||
// Go through their files
|
||||
for _, file := range imported.Files {
|
||||
// And populate a map of all direct imports and their positions
|
||||
// This will filter out GoRoot depending on the Depguard.IncludeGoRoot
|
||||
for _, fileImport := range file.Imports {
|
||||
fileImportPath := cleanBasicLitString(fileImport.Path.Value)
|
||||
if !dg.IncludeGoRoot && dg.isRoot(fileImportPath) {
|
||||
continue
|
||||
}
|
||||
position := prog.Fset.Position(fileImport.Pos())
|
||||
positions, found := importMap[fileImportPath]
|
||||
if !found {
|
||||
importMap[fileImportPath] = []token.Position{
|
||||
position,
|
||||
}
|
||||
continue
|
||||
}
|
||||
importMap[fileImportPath] = append(positions, position)
|
||||
}
|
||||
}
|
||||
}
|
||||
return importMap, nil
|
||||
}
|
||||
|
||||
func pkgInList(pkg string, prefixList []string, globList []glob.Glob) bool {
|
||||
if pkgInPrefixList(pkg, prefixList) {
|
||||
return true
|
||||
}
|
||||
return pkgInGlobList(pkg, globList)
|
||||
}
|
||||
|
||||
func pkgInPrefixList(pkg string, prefixList []string) bool {
|
||||
// Idx represents where in the package slice the passed in package would go
|
||||
// when sorted. -1 Just means that it would be at the very front of the slice.
|
||||
idx := sort.Search(len(prefixList), func(i int) bool {
|
||||
return prefixList[i] > pkg
|
||||
}) - 1
|
||||
// This means that the package passed in has no way to be prefixed by anything
|
||||
// in the package list as it is already smaller then everything
|
||||
if idx == -1 {
|
||||
return false
|
||||
}
|
||||
return strings.HasPrefix(pkg, prefixList[idx])
|
||||
}
|
||||
|
||||
func pkgInGlobList(pkg string, globList []glob.Glob) bool {
|
||||
for _, g := range globList {
|
||||
if g.Match(pkg) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// InList | WhiteList | BlackList
|
||||
// y | | x
|
||||
// n | x |
|
||||
func (dg *Depguard) flagIt(pkg string, prefixList []string, globList []glob.Glob) bool {
|
||||
return pkgInList(pkg, prefixList, globList) == (dg.ListType == LTBlacklist)
|
||||
}
|
||||
|
||||
func cleanBasicLitString(value string) string {
|
||||
return strings.Trim(value, "\"\\")
|
||||
}
|
||||
|
||||
// We can do this as all imports that are not root are either prefixed with a domain
|
||||
// or prefixed with `./` or `/` to dictate it is a local file reference
|
||||
func listRootPrefixs(buildCtx *build.Context) ([]string, error) {
|
||||
if buildCtx == nil {
|
||||
buildCtx = &build.Default
|
||||
}
|
||||
root := path.Join(buildCtx.GOROOT, "src")
|
||||
fs, err := ioutil.ReadDir(root)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var pkgPrefix []string
|
||||
for _, f := range fs {
|
||||
if !f.IsDir() {
|
||||
continue
|
||||
}
|
||||
pkgPrefix = append(pkgPrefix, f.Name())
|
||||
}
|
||||
return pkgPrefix, nil
|
||||
}
|
||||
|
||||
func (dg *Depguard) isRoot(importPath string) bool {
|
||||
// Idx represents where in the package slice the passed in package would go
|
||||
// when sorted. -1 Just means that it would be at the very front of the slice.
|
||||
idx := sort.Search(len(dg.prefixRoot), func(i int) bool {
|
||||
return dg.prefixRoot[i] > importPath
|
||||
}) - 1
|
||||
// This means that the package passed in has no way to be prefixed by anything
|
||||
// in the package list as it is already smaller then everything
|
||||
if idx == -1 {
|
||||
return false
|
||||
}
|
||||
// if it is prefixed by a root prefix we need to check if it is an exact match
|
||||
// or prefix with `/` as this could return false posative if the domain was
|
||||
// `archive.com` for example as `archive` is a go root package.
|
||||
if strings.HasPrefix(importPath, dg.prefixRoot[idx]) {
|
||||
return strings.HasPrefix(importPath, dg.prefixRoot[idx]+"/") || importPath == dg.prefixRoot[idx]
|
||||
}
|
||||
return false
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
module github.com/OpenPeeDeeP/depguard
|
||||
|
||||
go 1.13
|
||||
|
||||
require (
|
||||
github.com/gobwas/glob v0.2.3
|
||||
github.com/kisielk/gotool v1.0.0
|
||||
golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b
|
||||
)
|
|
@ -0,0 +1,6 @@
|
|||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||
github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b h1:7tibmaEqrQYA+q6ri7NQjuxqSwechjtDHKq6/e85S38=
|
||||
golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
@ -0,0 +1,70 @@
|
|||
|
||||
# Created by https://www.gitignore.io/api/go,vim,macos
|
||||
|
||||
### Go ###
|
||||
# Binaries for programs and plugins
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
|
||||
# Test binary, build with `go test -c`
|
||||
*.test
|
||||
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
### Go Patch ###
|
||||
/vendor/
|
||||
/Godeps/
|
||||
|
||||
### macOS ###
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### Vim ###
|
||||
# Swap
|
||||
[._]*.s[a-v][a-z]
|
||||
[._]*.sw[a-p]
|
||||
[._]s[a-rt-v][a-z]
|
||||
[._]ss[a-gi-z]
|
||||
[._]sw[a-p]
|
||||
|
||||
# Session
|
||||
Session.vim
|
||||
|
||||
# Temporary
|
||||
.netrwhist
|
||||
*~
|
||||
# Auto-generated tag files
|
||||
tags
|
||||
# Persistent undo
|
||||
[._]*.un~
|
||||
|
||||
|
||||
# End of https://www.gitignore.io/api/go,vim,macos
|
|
@ -0,0 +1,25 @@
|
|||
---
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.13.x
|
||||
- 1.12.x
|
||||
- 1.11.x
|
||||
|
||||
env:
|
||||
global:
|
||||
- GO111MODULE=on
|
||||
|
||||
install:
|
||||
- go get -v golang.org/x/tools/cmd/cover github.com/mattn/goveralls
|
||||
|
||||
script:
|
||||
- go test -v -covermode=count -coverprofile=coverage.out
|
||||
|
||||
after_script:
|
||||
- $HOME/gopath/bin/goveralls -coverprofile=coverage.out -service=travis-ci
|
||||
|
||||
notifications:
|
||||
email: false
|
||||
|
||||
# vim: set ts=2 sw=2 et:
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2018 Simon Sawert
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
|
@ -0,0 +1,125 @@
|
|||
# WSL - Whitespace Linter
|
||||
|
||||
[![forthebadge](https://forthebadge.com/images/badges/made-with-go.svg)](https://forthebadge.com)
|
||||
[![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com)
|
||||
|
||||
[![Build Status](https://travis-ci.org/bombsimon/wsl.svg?branch=master)](https://travis-ci.org/bombsimon/wsl)
|
||||
[![Coverage Status](https://coveralls.io/repos/github/bombsimon/wsl/badge.svg?branch=master)](https://coveralls.io/github/bombsimon/wsl?branch=master)
|
||||
|
||||
WSL is a linter that enforces a very **non scientific** vision of how to make
|
||||
code more readable by enforcing empty lines at the right places.
|
||||
|
||||
I think too much code out there is to cuddly and a bit too warm for it's own
|
||||
good, making it harder for other people to read and understand. The linter will
|
||||
warn about newlines in and around blocks, in the beginning of files and other
|
||||
places in the code.
|
||||
|
||||
**I know this linter is aggressive** and a lot of projects I've tested it on
|
||||
have failed miserably. For this linter to be useful at all I want to be open to
|
||||
new ideas, configurations and discussions! Also note that some of the warnings
|
||||
might be bugs or unintentional false positives so I would love an
|
||||
[issue](https://github.com/bombsimon/wsl/issues/new) to fix, discuss, change or
|
||||
make something configurable!
|
||||
|
||||
## Installation
|
||||
|
||||
### By `go get` (local installation)
|
||||
|
||||
You can do that by using:
|
||||
|
||||
```sh
|
||||
go get -u github.com/bombsimon/wsl/cmd/...
|
||||
```
|
||||
|
||||
### By golangci-lint (CI automation)
|
||||
|
||||
`wsl` is already integrated with
|
||||
[golangci-lint](https://github.com/golangci/golangci-lint). Please refer to the
|
||||
instructions there.
|
||||
|
||||
## Usage
|
||||
|
||||
How to use depends on how you install `wsl`.
|
||||
|
||||
### With local binary
|
||||
|
||||
The general command format for `wsl` is:
|
||||
|
||||
```sh
|
||||
$ wsl [flags] <file1> [files...]
|
||||
$ wsl [flags] </path/to/package/...>
|
||||
|
||||
# Examples
|
||||
|
||||
$ wsl ./main.go
|
||||
$ wsl --no-test ./main.go
|
||||
$ wsl --allow-cuddle-declarations ./main.go
|
||||
$ wsl --no-test --allow-cuddle-declaration ./main.go
|
||||
$ wsl --no-test --allow-trailing-comment ./myProject/...
|
||||
```
|
||||
|
||||
The "..." wildcard is not used like other `go` commands but instead can only
|
||||
be to a relative or absolute path.
|
||||
|
||||
By default, the linter will run on `./...` which means all go files in the
|
||||
current path and all subsequent paths, including test files. To disable linting
|
||||
test files, use `-n` or `--no-test`.
|
||||
|
||||
### By `golangci-lint` (CI automation)
|
||||
|
||||
The recommended command is:
|
||||
|
||||
```sh
|
||||
golangci-lint run --disable-all --enable wsl
|
||||
```
|
||||
|
||||
For more information, please refer to
|
||||
[golangci-lint](https://github.com/golangci/golangci-lint)'s documentation.
|
||||
|
||||
## Issues and configuration
|
||||
|
||||
The linter suppers a few ways to configure it to satisfy more than one kind of
|
||||
code style. These settings could be set either with flags or with YAML
|
||||
configuration if used via `golangci-lint`.
|
||||
|
||||
The supported configuration can be found [in the documentation](doc/configuration.md).
|
||||
|
||||
Below are the available checklist for any hit from `wsl`. If you do not see any,
|
||||
feel free to raise an [issue](https://github.com/bombsimon/wsl/issues/new).
|
||||
|
||||
> **Note**: this linter doesn't take in consideration the issues that will be
|
||||
> fixed with `go fmt -s` so ensure that the code is properly formatted before
|
||||
> use.
|
||||
|
||||
* [Anonymous switch statements should never be cuddled](doc/rules.md#anonymous-switch-statements-should-never-be-cuddled)
|
||||
* [Append only allowed to cuddle with appended value](doc/rules.md#append-only-allowed-to-cuddle-with-appended-value)
|
||||
* [Assignments should only be cuddled with other assignments](doc/rules.md#assignments-should-only-be-cuddled-with-other-assignments)
|
||||
* [Block should not end with a whitespace (or comment)](doc/rules.md#block-should-not-end-with-a-whitespace-or-comment)
|
||||
* [Block should not start with a whitespace](doc/rules.md#block-should-not-start-with-a-whitespace)
|
||||
* [Case block should end with newline at this size](doc/rules.md#case-block-should-end-with-newline-at-this-size)
|
||||
* [Branch statements should not be cuddled if block has more than two lines](doc/rules.md#branch-statements-should-not-be-cuddled-if-block-has-more-than-two-lines)
|
||||
* [Declarations should never be cuddled](doc/rules.md#declarations-should-never-be-cuddled)
|
||||
* [Defer statements should only be cuddled with expressions on same variable](doc/rules.md#defer-statements-should-only-be-cuddled-with-expressions-on-same-variable)
|
||||
* [Expressions should not be cuddled with blocks](doc/rules.md#expressions-should-not-be-cuddled-with-blocks)
|
||||
* [Expressions should not be cuddled with declarations or returns](doc/rules.md#expressions-should-not-be-cuddled-with-declarations-or-returns)
|
||||
* [For statement without condition should never be cuddled](doc/rules.md#for-statement-without-condition-should-never-be-cuddled)
|
||||
* [For statements should only be cuddled with assignments used in the iteration](doc/rules.md#for-statements-should-only-be-cuddled-with-assignments-used-in-the-iteration)
|
||||
* [Go statements can only invoke functions assigned on line above](doc/rules.md#go-statements-can-only-invoke-functions-assigned-on-line-above)
|
||||
* [If statements should only be cuddled with assignments](doc/rules.md#if-statements-should-only-be-cuddled-with-assignments)
|
||||
* [If statements should only be cuddled with assignments used in the if
|
||||
statement
|
||||
itself](doc/rules.md#if-statements-should-only-be-cuddled-with-assignments-used-in-the-if-statement-itself)
|
||||
* [If statements that check an error must be cuddled with the statement that assigned the error](doc/rules.md#if-statements-that-check-an-error-must-be-cuddled-with-the-statement-that-assigned-the-error)
|
||||
* [Only cuddled expressions if assigning variable or using from line
|
||||
above](doc/rules.md#only-cuddled-expressions-if-assigning-variable-or-using-from-line-above)
|
||||
* [Only one cuddle assignment allowed before defer statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-defer-statement)
|
||||
* [Only one cuddle assginment allowed before for statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-for-statement)
|
||||
* [Only one cuddle assignment allowed before go statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-go-statement)
|
||||
* [Only one cuddle assignment allowed before if statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-if-statement)
|
||||
* [Only one cuddle assignment allowed before range statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-range-statement)
|
||||
* [Only one cuddle assignment allowed before switch statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-switch-statement)
|
||||
* [Only one cuddle assignment allowed before type switch statement](doc/rules.md#only-one-cuddle-assignment-allowed-before-type-switch-statement)
|
||||
* [Ranges should only be cuddled with assignments used in the iteration](doc/rules.md#ranges-should-only-be-cuddled-with-assignments-used-in-the-iteration)
|
||||
* [Return statements should not be cuddled if block has more than two lines](doc/rules.md#return-statements-should-not-be-cuddled-if-block-has-more-than-two-lines)
|
||||
* [Switch statements should only be cuddled with variables switched](doc/rules.md#switch-statements-should-only-be-cuddled-with-variables-switched)
|
||||
* [Type switch statements should only be cuddled with variables switched](doc/rules.md#type-switch-statements-should-only-be-cuddled-with-variables-switched)
|
|
@ -0,0 +1,12 @@
|
|||
module github.com/bombsimon/wsl/v3
|
||||
|
||||
go 1.12
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e // indirect
|
||||
github.com/stretchr/testify v1.5.1
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect
|
||||
gopkg.in/yaml.v2 v2.2.8 // indirect
|
||||
)
|
|
@ -0,0 +1,25 @@
|
|||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
|
||||
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
|
||||
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,29 @@
|
|||
BSD 3-Clause License
|
||||
|
||||
Copyright (c) 2020, Xiang Dai
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@ -0,0 +1,366 @@
|
|||
package gci
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
// pkg type: standard, remote, local
|
||||
standard int = iota
|
||||
// 3rd-party packages
|
||||
remote
|
||||
local
|
||||
|
||||
commentFlag = "//"
|
||||
)
|
||||
|
||||
var (
|
||||
importStartFlag = []byte(`
|
||||
import (
|
||||
`)
|
||||
|
||||
importEndFlag = []byte(`
|
||||
)
|
||||
`)
|
||||
)
|
||||
|
||||
type FlagSet struct {
|
||||
LocalFlag string
|
||||
DoWrite, DoDiff *bool
|
||||
}
|
||||
|
||||
type pkg struct {
|
||||
list map[int][]string
|
||||
comment map[string]string
|
||||
alias map[string]string
|
||||
}
|
||||
|
||||
func newPkg(data [][]byte, localFlag string) *pkg {
|
||||
listMap := make(map[int][]string)
|
||||
commentMap := make(map[string]string)
|
||||
aliasMap := make(map[string]string)
|
||||
p := &pkg{
|
||||
list: listMap,
|
||||
comment: commentMap,
|
||||
alias: aliasMap,
|
||||
}
|
||||
|
||||
formatData := make([]string, 0)
|
||||
// remove all empty lines
|
||||
for _, v := range data {
|
||||
if len(v) > 0 {
|
||||
formatData = append(formatData, strings.TrimSpace(string(v)))
|
||||
}
|
||||
}
|
||||
|
||||
n := len(formatData)
|
||||
for i := n - 1; i >= 0; i-- {
|
||||
line := formatData[i]
|
||||
|
||||
// check commentFlag:
|
||||
// 1. one line commentFlag
|
||||
// 2. commentFlag after import path
|
||||
commentIndex := strings.Index(line, commentFlag)
|
||||
if commentIndex == 0 {
|
||||
// comment in the last line is useless, ignore it
|
||||
if i+1 >= n {
|
||||
continue
|
||||
}
|
||||
pkg, _, _ := getPkgInfo(formatData[i+1], strings.Index(formatData[i+1], commentFlag) >= 0)
|
||||
p.comment[pkg] = line
|
||||
continue
|
||||
} else if commentIndex > 0 {
|
||||
pkg, alias, comment := getPkgInfo(line, true)
|
||||
if alias != "" {
|
||||
p.alias[pkg] = alias
|
||||
}
|
||||
|
||||
p.comment[pkg] = comment
|
||||
pkgType := getPkgType(pkg, localFlag)
|
||||
p.list[pkgType] = append(p.list[pkgType], pkg)
|
||||
continue
|
||||
}
|
||||
|
||||
pkg, alias, _ := getPkgInfo(line, false)
|
||||
|
||||
if alias != "" {
|
||||
p.alias[pkg] = alias
|
||||
}
|
||||
|
||||
pkgType := getPkgType(pkg, localFlag)
|
||||
p.list[pkgType] = append(p.list[pkgType], pkg)
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
// fmt format import pkgs as expected
|
||||
func (p *pkg) fmt() []byte {
|
||||
ret := make([]string, 0, 100)
|
||||
|
||||
for pkgType := range []int{standard, remote, local} {
|
||||
sort.Strings(p.list[pkgType])
|
||||
for _, s := range p.list[pkgType] {
|
||||
if p.comment[s] != "" {
|
||||
l := fmt.Sprintf("%s%s%s%s", linebreak, indent, p.comment[s], linebreak)
|
||||
ret = append(ret, l)
|
||||
}
|
||||
|
||||
if p.alias[s] != "" {
|
||||
s = fmt.Sprintf("%s%s%s%s%s", indent, p.alias[s], blank, s, linebreak)
|
||||
} else {
|
||||
s = fmt.Sprintf("%s%s%s", indent, s, linebreak)
|
||||
}
|
||||
|
||||
ret = append(ret, s)
|
||||
}
|
||||
|
||||
if len(p.list[pkgType]) > 0 {
|
||||
ret = append(ret, linebreak)
|
||||
}
|
||||
}
|
||||
if ret[len(ret)-1] == linebreak {
|
||||
ret = ret[:len(ret)-1]
|
||||
}
|
||||
|
||||
// remove duplicate empty lines
|
||||
s1 := fmt.Sprintf("%s%s%s%s", linebreak, linebreak, linebreak, indent)
|
||||
s2 := fmt.Sprintf("%s%s%s", linebreak, linebreak, indent)
|
||||
return []byte(strings.ReplaceAll(strings.Join(ret, ""), s1, s2))
|
||||
}
|
||||
|
||||
// getPkgInfo assume line is a import path, and return (path, alias, comment)
|
||||
func getPkgInfo(line string, comment bool) (string, string, string) {
|
||||
if comment {
|
||||
s := strings.Split(line, commentFlag)
|
||||
pkgArray := strings.Split(s[0], blank)
|
||||
if len(pkgArray) > 1 {
|
||||
return pkgArray[1], pkgArray[0], fmt.Sprintf("%s%s%s", commentFlag, blank, strings.TrimSpace(s[1]))
|
||||
} else {
|
||||
return strings.TrimSpace(pkgArray[0]), "", fmt.Sprintf("%s%s%s", commentFlag, blank, strings.TrimSpace(s[1]))
|
||||
}
|
||||
} else {
|
||||
pkgArray := strings.Split(line, blank)
|
||||
if len(pkgArray) > 1 {
|
||||
return pkgArray[1], pkgArray[0], ""
|
||||
} else {
|
||||
return pkgArray[0], "", ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getPkgType(line, localFlag string) int {
|
||||
if !strings.Contains(line, dot) {
|
||||
return standard
|
||||
} else if strings.Contains(line, localFlag) {
|
||||
return local
|
||||
} else {
|
||||
return remote
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
dot = "."
|
||||
blank = " "
|
||||
indent = "\t"
|
||||
linebreak = "\n"
|
||||
)
|
||||
|
||||
func diff(b1, b2 []byte, filename string) (data []byte, err error) {
|
||||
f1, err := writeTempFile("", "gci", b1)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer os.Remove(f1)
|
||||
|
||||
f2, err := writeTempFile("", "gci", b2)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer os.Remove(f2)
|
||||
|
||||
cmd := "diff"
|
||||
|
||||
data, err = exec.Command(cmd, "-u", f1, f2).CombinedOutput()
|
||||
if len(data) > 0 {
|
||||
// diff exits with a non-zero status when the files don't match.
|
||||
// Ignore that failure as long as we get output.
|
||||
return replaceTempFilename(data, filename)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func writeTempFile(dir, prefix string, data []byte) (string, error) {
|
||||
file, err := ioutil.TempFile(dir, prefix)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, err = file.Write(data)
|
||||
if err1 := file.Close(); err == nil {
|
||||
err = err1
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(file.Name())
|
||||
return "", err
|
||||
}
|
||||
return file.Name(), nil
|
||||
}
|
||||
|
||||
// replaceTempFilename replaces temporary filenames in diff with actual one.
|
||||
//
|
||||
// --- /tmp/gofmt316145376 2017-02-03 19:13:00.280468375 -0500
|
||||
// +++ /tmp/gofmt617882815 2017-02-03 19:13:00.280468375 -0500
|
||||
// ...
|
||||
// ->
|
||||
// --- path/to/file.go.orig 2017-02-03 19:13:00.280468375 -0500
|
||||
// +++ path/to/file.go 2017-02-03 19:13:00.280468375 -0500
|
||||
// ...
|
||||
func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
|
||||
bs := bytes.SplitN(diff, []byte{'\n'}, 3)
|
||||
if len(bs) < 3 {
|
||||
return nil, fmt.Errorf("got unexpected diff for %s", filename)
|
||||
}
|
||||
// Preserve timestamps.
|
||||
var t0, t1 []byte
|
||||
if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
|
||||
t0 = bs[0][i:]
|
||||
}
|
||||
if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
|
||||
t1 = bs[1][i:]
|
||||
}
|
||||
// Always print filepath with slash separator.
|
||||
f := filepath.ToSlash(filename)
|
||||
bs[0] = []byte(fmt.Sprintf("--- %s%s", f+".orig", t0))
|
||||
bs[1] = []byte(fmt.Sprintf("+++ %s%s", f, t1))
|
||||
return bytes.Join(bs, []byte{'\n'}), nil
|
||||
}
|
||||
|
||||
func visitFile(set *FlagSet) filepath.WalkFunc {
|
||||
return func(path string, f os.FileInfo, err error) error {
|
||||
if err == nil && isGoFile(f) {
|
||||
err = processFile(path, os.Stdout, set)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func WalkDir(path string, set *FlagSet) error {
|
||||
return filepath.Walk(path, visitFile(set))
|
||||
}
|
||||
|
||||
func isGoFile(f os.FileInfo) bool {
|
||||
// ignore non-Go files
|
||||
name := f.Name()
|
||||
return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
|
||||
}
|
||||
|
||||
func ProcessFile(filename string, out io.Writer, set *FlagSet) error {
|
||||
return processFile(filename, out, set)
|
||||
}
|
||||
|
||||
func processFile(filename string, out io.Writer, set *FlagSet) error {
|
||||
var err error
|
||||
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
src, err := ioutil.ReadAll(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ori := make([]byte, len(src))
|
||||
copy(ori, src)
|
||||
start := bytes.Index(src, importStartFlag)
|
||||
// in case no importStartFlag or importStartFlag exist in the commentFlag
|
||||
if start < 0 {
|
||||
fmt.Printf("skip file %s since no import\n", filename)
|
||||
return nil
|
||||
}
|
||||
end := bytes.Index(src[start:], importEndFlag) + start
|
||||
|
||||
ret := bytes.Split(src[start+len(importStartFlag):end], []byte(linebreak))
|
||||
|
||||
p := newPkg(ret, set.LocalFlag)
|
||||
|
||||
res := append(src[:start+len(importStartFlag)], append(p.fmt(), src[end+1:]...)...)
|
||||
|
||||
if !bytes.Equal(ori, res) {
|
||||
if *set.DoWrite {
|
||||
// On Windows, we need to re-set the permissions from the file. See golang/go#38225.
|
||||
var perms os.FileMode
|
||||
if fi, err := os.Stat(filename); err == nil {
|
||||
perms = fi.Mode() & os.ModePerm
|
||||
}
|
||||
err = ioutil.WriteFile(filename, res, perms)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if *set.DoDiff {
|
||||
data, err := diff(ori, res, filename)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to diff: %v", err)
|
||||
}
|
||||
fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
|
||||
if _, err := out.Write(data); err != nil {
|
||||
return fmt.Errorf("failed to write: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !*set.DoWrite && !*set.DoDiff {
|
||||
if _, err = out.Write(res); err != nil {
|
||||
return fmt.Errorf("failed to write: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// Run return source and result in []byte if succeed
|
||||
func Run(filename string, set *FlagSet) ([]byte, []byte, error) {
|
||||
var err error
|
||||
|
||||
f, err := os.Open(filename)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
src, err := ioutil.ReadAll(f)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
ori := make([]byte, len(src))
|
||||
copy(ori, src)
|
||||
start := bytes.Index(src, importStartFlag)
|
||||
// in case no importStartFlag or importStartFlag exist in the commentFlag
|
||||
if start < 0 {
|
||||
return nil, nil, nil
|
||||
}
|
||||
end := bytes.Index(src[start:], importEndFlag) + start
|
||||
|
||||
ret := bytes.Split(src[start+len(importStartFlag):end], []byte(linebreak))
|
||||
|
||||
p := newPkg(ret, set.LocalFlag)
|
||||
|
||||
res := append(src[:start+len(importStartFlag)], append(p.fmt(), src[end+1:]...)...)
|
||||
|
||||
if bytes.Equal(ori, res) {
|
||||
return ori, nil, nil
|
||||
}
|
||||
|
||||
return ori, res, nil
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
.idea/
|
|
@ -0,0 +1,674 @@
|
|||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
|
@ -0,0 +1,69 @@
|
|||
# go-header
|
||||
[![Actions Status](https://github.com/denis-tingajkin/go-header/workflows/ci/badge.svg)](https://github.com/denis-tingajkin/go-header/actions)
|
||||
|
||||
Go source code linter providing checks for license headers.
|
||||
|
||||
# Installation
|
||||
|
||||
For installation you can simply use `go get`.
|
||||
|
||||
```
|
||||
go get github.com/denis-tingajkin/go-header/cmd/go-header
|
||||
```
|
||||
|
||||
# Configuration
|
||||
|
||||
To configuring `go-header.yml` linter you simply need to fill the next structures in YAML format.
|
||||
```go
|
||||
// Configuration represents go-header linter setup parameters
|
||||
type Configuration struct {
|
||||
// Values is map of values. Supports two types 'const` and `regexp`. Values can be used recursively.
|
||||
Values map[string]map[string]string `yaml:"values"'`
|
||||
// Template is template for checking. Uses values.
|
||||
Template string `yaml:"template"`
|
||||
// TemplatePath path to the template file. Useful if need to load the template from a specific file.
|
||||
TemplatePath string `yaml:"template-path"`
|
||||
}
|
||||
```
|
||||
Where supported two kinds of values: `const` and `regexp`. NOTE: values can be used recursively.
|
||||
Values with type `const` checks on equality.
|
||||
Values with type `regexp` checks on the match.
|
||||
|
||||
# Execution
|
||||
|
||||
`go-header` linter expects file path on input. If you want to run `go-header` only on diff files, then you can use this command
|
||||
```bash
|
||||
go-header $(git diff --name-only)
|
||||
```
|
||||
|
||||
# Setup example
|
||||
|
||||
## Step 1
|
||||
Create configuration file `.go-header.yaml` in the root of project.
|
||||
```yaml
|
||||
---
|
||||
values:
|
||||
const:
|
||||
MY COMPANY: mycompany.com
|
||||
template-path: ./mypath/mytemplate.txt
|
||||
```
|
||||
## Step 2
|
||||
Write the template file. For example for config above `mytemplate.txt` could be
|
||||
```text
|
||||
{{ MY COMPANY }}
|
||||
SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at:
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
```
|
||||
## Step 3
|
||||
You are ready! Execute `go-header {FILES}` from the root of the project.
|
|
@ -0,0 +1,98 @@
|
|||
package goheader
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Analyzer interface {
|
||||
Analyze(file *ast.File) Issue
|
||||
}
|
||||
|
||||
type analyzer struct {
|
||||
values map[string]Value
|
||||
template string
|
||||
}
|
||||
|
||||
func (a *analyzer) Analyze(file *ast.File) Issue {
|
||||
if a.template == "" {
|
||||
return NewIssue("Missed template for check")
|
||||
}
|
||||
var header string
|
||||
if len(file.Comments) > 0 && file.Comments[0].Pos() < file.Package {
|
||||
if strings.HasPrefix(file.Comments[0].List[0].Text, "/*") {
|
||||
header = (&ast.CommentGroup{List: []*ast.Comment{file.Comments[0].List[0]}}).Text()
|
||||
} else {
|
||||
header = file.Comments[0].Text()
|
||||
}
|
||||
}
|
||||
header = strings.TrimSpace(header)
|
||||
if header == "" {
|
||||
return NewIssue("Missed header for check")
|
||||
}
|
||||
s := NewReader(header)
|
||||
t := NewReader(a.template)
|
||||
for !s.Done() && !t.Done() {
|
||||
templateCh := t.Peek()
|
||||
if templateCh == '{' {
|
||||
name := a.readField(t)
|
||||
if a.values[name] == nil {
|
||||
return NewIssue(fmt.Sprintf("Template has unknown value: %v", name))
|
||||
}
|
||||
if i := a.values[name].Read(s); i != nil {
|
||||
return i
|
||||
}
|
||||
continue
|
||||
}
|
||||
sourceCh := s.Peek()
|
||||
if sourceCh != templateCh {
|
||||
l := s.Location()
|
||||
notNextLine := func(r rune) bool {
|
||||
return r != '\n'
|
||||
}
|
||||
actual := s.ReadWhile(notNextLine)
|
||||
expected := t.ReadWhile(notNextLine)
|
||||
return NewIssueWithLocation(fmt.Sprintf("Actual: %v\nExpected:%v", actual, expected), l)
|
||||
}
|
||||
s.Next()
|
||||
t.Next()
|
||||
}
|
||||
if !s.Done() {
|
||||
l := s.Location()
|
||||
return NewIssueWithLocation(fmt.Sprintf("Unexpected string: %v", s.Finish()), l)
|
||||
}
|
||||
if !t.Done() {
|
||||
l := s.Location()
|
||||
return NewIssueWithLocation(fmt.Sprintf("Missed string: %v", t.Finish()), l)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *analyzer) readField(reader Reader) string {
|
||||
_ = reader.Next()
|
||||
_ = reader.Next()
|
||||
|
||||
r := reader.ReadWhile(func(r rune) bool {
|
||||
return r != '}'
|
||||
})
|
||||
|
||||
_ = reader.Next()
|
||||
_ = reader.Next()
|
||||
|
||||
return strings.ToLower(strings.TrimSpace(r))
|
||||
}
|
||||
|
||||
func New(options ...AnalyzerOption) Analyzer {
|
||||
a := &analyzer{}
|
||||
for _, o := range options {
|
||||
o.apply(a)
|
||||
}
|
||||
for _, v := range a.values {
|
||||
err := v.Calculate(a.values)
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
|
@ -0,0 +1,69 @@
|
|||
package goheader
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"gopkg.in/yaml.v2"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Configuration represents go-header linter setup parameters
|
||||
type Configuration struct {
|
||||
// Values is map of values. Supports two types 'const` and `regexp`. Values can be used recursively.
|
||||
Values map[string]map[string]string `yaml:"values"'`
|
||||
// Template is template for checking. Uses values.
|
||||
Template string `yaml:"template"`
|
||||
// TemplatePath path to the template file. Useful if need to load the template from a specific file.
|
||||
TemplatePath string `yaml:"template-path"`
|
||||
}
|
||||
|
||||
func (c *Configuration) GetValues() (map[string]Value, error) {
|
||||
var result = make(map[string]Value)
|
||||
createConst := func(raw string) Value {
|
||||
return &ConstValue{RawValue: raw}
|
||||
}
|
||||
createRegexp := func(raw string) Value {
|
||||
return &RegexpValue{RawValue: raw}
|
||||
}
|
||||
appendValues := func(m map[string]string, create func(string) Value) {
|
||||
for k, v := range m {
|
||||
key := strings.ToLower(k)
|
||||
result[key] = create(v)
|
||||
}
|
||||
}
|
||||
for k, v := range c.Values {
|
||||
switch k {
|
||||
case "const":
|
||||
appendValues(v, createConst)
|
||||
case "regexp":
|
||||
appendValues(v, createRegexp)
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown value type %v", k)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c *Configuration) GetTemplate() (string, error) {
|
||||
if c.Template != "" {
|
||||
return c.Template, nil
|
||||
}
|
||||
if c.TemplatePath == "" {
|
||||
return "", errors.New("template has not passed")
|
||||
}
|
||||
if b, err := ioutil.ReadFile(c.TemplatePath); err != nil {
|
||||
return "", err
|
||||
} else {
|
||||
c.Template = string(b)
|
||||
return c.Template, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Configuration) Parse(p string) error {
|
||||
b, err := ioutil.ReadFile(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return yaml.Unmarshal(b, c)
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
module github.com/denis-tingajkin/go-header
|
||||
|
||||
go 1.13
|
||||
|
||||
require (
|
||||
github.com/fatih/color v1.9.0
|
||||
github.com/sirupsen/logrus v1.6.0
|
||||
github.com/stretchr/testify v1.5.1
|
||||
gopkg.in/yaml.v2 v2.2.2
|
||||
)
|
|
@ -0,0 +1,31 @@
|
|||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fatih/color v1.9.0 h1:8xPHl4/q1VyqGIPif1F+1V3Y3lSmrq01EabUW3CoW5s=
|
||||
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
|
||||
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
|
||||
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
|
||||
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
|
||||
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.5.1 h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
@ -0,0 +1,32 @@
|
|||
package goheader
|
||||
|
||||
type Issue interface {
|
||||
Location() Location
|
||||
Message() string
|
||||
}
|
||||
|
||||
type issue struct {
|
||||
msg string
|
||||
location Location
|
||||
}
|
||||
|
||||
func (i *issue) Location() Location {
|
||||
return i.location
|
||||
}
|
||||
|
||||
func (i *issue) Message() string {
|
||||
return i.msg
|
||||
}
|
||||
|
||||
func NewIssueWithLocation(msg string, location Location) Issue {
|
||||
return &issue{
|
||||
msg: msg,
|
||||
location: location,
|
||||
}
|
||||
}
|
||||
|
||||
func NewIssue(msg string) Issue {
|
||||
return &issue{
|
||||
msg: msg,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
package goheader
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Location struct {
|
||||
Line int
|
||||
Position int
|
||||
}
|
||||
|
||||
func (l Location) String() string {
|
||||
return fmt.Sprintf("%v:%v", l.Line+1, l.Position)
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package goheader
|
||||
|
||||
import "strings"
|
||||
|
||||
type AnalyzerOption interface {
|
||||
apply(*analyzer)
|
||||
}
|
||||
|
||||
type applyAnalyzerOptionFunc func(*analyzer)
|
||||
|
||||
func (f applyAnalyzerOptionFunc) apply(a *analyzer) {
|
||||
f(a)
|
||||
}
|
||||
|
||||
func WithValues(values map[string]Value) AnalyzerOption {
|
||||
return applyAnalyzerOptionFunc(func(a *analyzer) {
|
||||
a.values = make(map[string]Value)
|
||||
for k, v := range values {
|
||||
a.values[strings.ToLower(k)] = v
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func WithTemplate(template string) AnalyzerOption {
|
||||
return applyAnalyzerOptionFunc(func(a *analyzer) {
|
||||
a.template = template
|
||||
})
|
||||
}
|
|
@ -0,0 +1,105 @@
|
|||
package goheader
|
||||
|
||||
type Reader interface {
|
||||
Peek() rune
|
||||
Next() rune
|
||||
Done() bool
|
||||
Finish() string
|
||||
Position() int
|
||||
Location() Location
|
||||
SetPosition(int)
|
||||
ReadWhile(func(rune) bool) string
|
||||
}
|
||||
|
||||
func NewReader(text string) Reader {
|
||||
return &reader{source: text}
|
||||
}
|
||||
|
||||
type reader struct {
|
||||
source string
|
||||
position int
|
||||
location Location
|
||||
}
|
||||
|
||||
func (r *reader) Position() int {
|
||||
return r.position
|
||||
}
|
||||
|
||||
func (r *reader) Location() Location {
|
||||
return r.location
|
||||
}
|
||||
|
||||
func (r *reader) Peek() rune {
|
||||
if r.Done() {
|
||||
return rune(0)
|
||||
}
|
||||
return rune(r.source[r.position])
|
||||
}
|
||||
|
||||
func (r *reader) Done() bool {
|
||||
return r.position >= len(r.source)
|
||||
}
|
||||
|
||||
func (r *reader) Next() rune {
|
||||
if r.Done() {
|
||||
return rune(0)
|
||||
}
|
||||
reuslt := r.Peek()
|
||||
if reuslt == '\n' {
|
||||
r.location.Line++
|
||||
r.location.Position = 0
|
||||
} else {
|
||||
r.location.Position++
|
||||
}
|
||||
r.position++
|
||||
return reuslt
|
||||
}
|
||||
|
||||
func (r *reader) Finish() string {
|
||||
if r.position >= len(r.source) {
|
||||
return ""
|
||||
}
|
||||
defer r.till()
|
||||
return r.source[r.position:]
|
||||
}
|
||||
|
||||
func (r *reader) SetPosition(pos int) {
|
||||
if pos < 0 {
|
||||
r.position = 0
|
||||
}
|
||||
r.position = pos
|
||||
r.location = r.calculateLocation()
|
||||
}
|
||||
|
||||
func (r *reader) ReadWhile(match func(rune) bool) string {
|
||||
if match == nil {
|
||||
return ""
|
||||
}
|
||||
start := r.position
|
||||
for !r.Done() && match(r.Peek()) {
|
||||
r.Next()
|
||||
}
|
||||
return r.source[start:r.position]
|
||||
}
|
||||
|
||||
func (r *reader) till() {
|
||||
r.position = len(r.source)
|
||||
r.location = r.calculateLocation()
|
||||
}
|
||||
|
||||
func (r *reader) calculateLocation() Location {
|
||||
min := len(r.source)
|
||||
if min > r.position {
|
||||
min = r.position
|
||||
}
|
||||
x, y := 0, 0
|
||||
for i := 0; i < min; i++ {
|
||||
if r.source[i] == '\n' {
|
||||
y++
|
||||
x = 0
|
||||
} else {
|
||||
x++
|
||||
}
|
||||
}
|
||||
return Location{Line: y, Position: x}
|
||||
}
|
|
@ -0,0 +1,112 @@
|
|||
package goheader
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Calculable interface {
|
||||
Calculate(map[string]Value) error
|
||||
Get() string
|
||||
}
|
||||
|
||||
type Value interface {
|
||||
Calculable
|
||||
Read(Reader) Issue
|
||||
}
|
||||
|
||||
func calculateValue(calculable Calculable, values map[string]Value) (string, error) {
|
||||
sb := strings.Builder{}
|
||||
r := calculable.Get()
|
||||
var endIndex int
|
||||
var startIndex int
|
||||
for startIndex = strings.Index(r, "{{"); startIndex >= 0; startIndex = strings.Index(r, "{{") {
|
||||
_, _ = sb.WriteString(r[:startIndex])
|
||||
endIndex = strings.Index(r, "}}")
|
||||
if endIndex < 0 {
|
||||
return "", errors.New("missed value ending")
|
||||
}
|
||||
subVal := strings.ToLower(strings.TrimSpace(r[startIndex+2 : endIndex]))
|
||||
if val := values[subVal]; val != nil {
|
||||
if err := val.Calculate(values); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sb.WriteString(val.Get())
|
||||
} else {
|
||||
return "", fmt.Errorf("unknown value name %v", subVal)
|
||||
}
|
||||
endIndex += 2
|
||||
r = r[endIndex:]
|
||||
}
|
||||
_, _ = sb.WriteString(r)
|
||||
return sb.String(), nil
|
||||
}
|
||||
|
||||
type ConstValue struct {
|
||||
RawValue string
|
||||
}
|
||||
|
||||
func (c *ConstValue) Calculate(values map[string]Value) error {
|
||||
v, err := calculateValue(c, values)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.RawValue = v
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ConstValue) Get() string {
|
||||
return c.RawValue
|
||||
}
|
||||
|
||||
func (c *ConstValue) Read(s Reader) Issue {
|
||||
l := s.Location()
|
||||
p := s.Position()
|
||||
for _, ch := range c.Get() {
|
||||
if ch != s.Peek() {
|
||||
s.SetPosition(p)
|
||||
f := s.ReadWhile(func(r rune) bool {
|
||||
return r != '\n'
|
||||
})
|
||||
return NewIssueWithLocation(fmt.Sprintf("Expected:%v, Actual: %v", c.Get(), f), l)
|
||||
}
|
||||
s.Next()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type RegexpValue struct {
|
||||
RawValue string
|
||||
}
|
||||
|
||||
func (r *RegexpValue) Calculate(values map[string]Value) error {
|
||||
v, err := calculateValue(r, values)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.RawValue = v
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RegexpValue) Get() string {
|
||||
return r.RawValue
|
||||
}
|
||||
|
||||
func (r *RegexpValue) Read(s Reader) Issue {
|
||||
l := s.Location()
|
||||
p := regexp.MustCompile(r.Get())
|
||||
pos := s.Position()
|
||||
str := s.Finish()
|
||||
s.SetPosition(pos)
|
||||
indexes := p.FindAllIndex([]byte(str), -1)
|
||||
if len(indexes) == 0 {
|
||||
return NewIssueWithLocation(fmt.Sprintf("Pattern %v doesn't match.", p.String()), l)
|
||||
}
|
||||
s.SetPosition(pos + indexes[0][1])
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ Value = &ConstValue{}
|
||||
var _ Value = &RegexpValue{}
|
|
@ -1,5 +0,0 @@
|
|||
language: go
|
||||
go:
|
||||
- 1.8.x
|
||||
- tip
|
||||
|
|
@ -1,27 +0,0 @@
|
|||
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
|
||||
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/mattn/go-colorable"
|
||||
packages = ["."]
|
||||
revision = "167de6bfdfba052fa6b2d3664c8f5272e23c9072"
|
||||
version = "v0.0.9"
|
||||
|
||||
[[projects]]
|
||||
name = "github.com/mattn/go-isatty"
|
||||
packages = ["."]
|
||||
revision = "0360b2af4f38e8d38c7fce2a9f4e702702d73a39"
|
||||
version = "v0.0.3"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
name = "golang.org/x/sys"
|
||||
packages = ["unix"]
|
||||
revision = "37707fdb30a5b38865cfb95e5aab41707daec7fd"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
inputs-digest = "e8a50671c3cb93ea935bf210b1cd20702876b9d9226129be581ef646d1565cdc"
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
|
@ -1,14 +1,11 @@
|
|||
# Color [![GoDoc](https://godoc.org/github.com/fatih/color?status.svg)](https://godoc.org/github.com/fatih/color) [![Build Status](https://img.shields.io/travis/fatih/color.svg?style=flat-square)](https://travis-ci.org/fatih/color)
|
||||
|
||||
|
||||
# color [![](https://github.com/fatih/color/workflows/build/badge.svg)](https://github.com/fatih/color/actions) [![PkgGoDev](https://pkg.go.dev/badge/github.com/fatih/color)](https://pkg.go.dev/github.com/fatih/color)
|
||||
|
||||
Color lets you use colorized outputs in terms of [ANSI Escape
|
||||
Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It
|
||||
has support for Windows too! The API can be used in several ways, pick one that
|
||||
suits you.
|
||||
|
||||
|
||||
![Color](https://i.imgur.com/c1JI0lA.png)
|
||||
![Color](https://user-images.githubusercontent.com/438920/96832689-03b3e000-13f4-11eb-9803-46f4c4de3406.jpg)
|
||||
|
||||
|
||||
## Install
|
||||
|
@ -17,9 +14,6 @@ suits you.
|
|||
go get github.com/fatih/color
|
||||
```
|
||||
|
||||
Note that the `vendor` folder is here for stability. Remove the folder if you
|
||||
already have the dependencies in your GOPATH.
|
||||
|
||||
## Examples
|
||||
|
||||
### Standard colors
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
module github.com/fatih/color
|
||||
|
||||
go 1.13
|
||||
|
||||
require (
|
||||
github.com/mattn/go-colorable v0.1.8
|
||||
github.com/mattn/go-isatty v0.0.12
|
||||
)
|
|
@ -0,0 +1,7 @@
|
|||
github.com/mattn/go-colorable v0.1.8 h1:c1ghPdyEDarC70ftn0y+A/Ee++9zz8ljHG1b13eJ0s8=
|
||||
github.com/mattn/go-colorable v0.1.8/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
|
||||
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
|
||||
golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae h1:/WDfKMnPU+m5M4xB+6x4kaepxRw6jWvR5iDRdvjHgy8=
|
||||
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
@ -0,0 +1,22 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2018-2019 Alekseev Artem
|
||||
Copyright (c) 2018-2019 Ravil Bikbulatov
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
102
vendor/github.com/go-critic/go-critic/checkers/appendAssign_checker.go
сгенерированный
поставляемый
Normal file
102
vendor/github.com/go-critic/go-critic/checkers/appendAssign_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,102 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"go/types"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
"github.com/go-toolsmith/astp"
|
||||
"golang.org/x/tools/go/ast/astutil"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "appendAssign"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects suspicious append result assignments"
|
||||
info.Before = `
|
||||
p.positives = append(p.negatives, x)
|
||||
p.negatives = append(p.negatives, y)`
|
||||
info.After = `
|
||||
p.positives = append(p.positives, x)
|
||||
p.negatives = append(p.negatives, y)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&appendAssignChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type appendAssignChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *appendAssignChecker) VisitStmt(stmt ast.Stmt) {
|
||||
assign, ok := stmt.(*ast.AssignStmt)
|
||||
if !ok || assign.Tok != token.ASSIGN || len(assign.Lhs) != len(assign.Rhs) {
|
||||
return
|
||||
}
|
||||
for i, rhs := range assign.Rhs {
|
||||
call, ok := rhs.(*ast.CallExpr)
|
||||
if !ok || qualifiedName(call.Fun) != "append" {
|
||||
continue
|
||||
}
|
||||
c.checkAppend(assign.Lhs[i], call)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *appendAssignChecker) checkAppend(x ast.Expr, call *ast.CallExpr) {
|
||||
if call.Ellipsis != token.NoPos {
|
||||
// Try to detect `xs = append(ys, xs...)` idiom.
|
||||
for _, arg := range call.Args[1:] {
|
||||
y := arg
|
||||
if arg, ok := arg.(*ast.SliceExpr); ok {
|
||||
y = arg.X
|
||||
}
|
||||
if astequal.Expr(x, y) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
switch x := x.(type) {
|
||||
case *ast.Ident:
|
||||
if x.Name == "_" {
|
||||
return // Don't check assignments to blank ident
|
||||
}
|
||||
case *ast.IndexExpr:
|
||||
if !astp.IsIndexExpr(call.Args[0]) {
|
||||
// Most likely `m[k] = append(x, ...)`
|
||||
// pattern, where x was retrieved by m[k] before.
|
||||
//
|
||||
// TODO: it's possible to record such map/slice reads
|
||||
// and check whether it was done before this call.
|
||||
// But for now, treat it like x belongs to m[k].
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
switch y := call.Args[0].(type) {
|
||||
case *ast.SliceExpr:
|
||||
if _, ok := c.ctx.TypesInfo.TypeOf(y.X).(*types.Array); ok {
|
||||
// Arrays are frequently used as scratch storages.
|
||||
return
|
||||
}
|
||||
c.matchSlices(call, x, y.X)
|
||||
case *ast.IndexExpr, *ast.Ident, *ast.SelectorExpr:
|
||||
c.matchSlices(call, x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *appendAssignChecker) matchSlices(cause ast.Node, x, y ast.Expr) {
|
||||
if !astequal.Expr(x, astutil.Unparen(y)) {
|
||||
c.warn(cause)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *appendAssignChecker) warn(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "append result not assigned to the same slice")
|
||||
}
|
102
vendor/github.com/go-critic/go-critic/checkers/appendCombine_checker.go
сгенерированный
поставляемый
Normal file
102
vendor/github.com/go-critic/go-critic/checkers/appendCombine_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,102 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "appendCombine"
|
||||
info.Tags = []string{"performance"}
|
||||
info.Summary = "Detects `append` chains to the same slice that can be done in a single `append` call"
|
||||
info.Before = `
|
||||
xs = append(xs, 1)
|
||||
xs = append(xs, 2)`
|
||||
info.After = `xs = append(xs, 1, 2)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmtList(&appendCombineChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type appendCombineChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *appendCombineChecker) VisitStmtList(list []ast.Stmt) {
|
||||
var cause ast.Node // First append
|
||||
var slice ast.Expr // Slice being appended to
|
||||
chain := 0 // How much appends in a row we've seen
|
||||
|
||||
// Break the chain.
|
||||
// If enough appends are in chain, print warning.
|
||||
flush := func() {
|
||||
if chain > 1 {
|
||||
c.warn(cause, chain)
|
||||
}
|
||||
chain = 0
|
||||
slice = nil
|
||||
}
|
||||
|
||||
for _, stmt := range list {
|
||||
call := c.matchAppend(stmt, slice)
|
||||
if call == nil {
|
||||
flush()
|
||||
continue
|
||||
}
|
||||
|
||||
if chain == 0 {
|
||||
// First append in a chain.
|
||||
chain = 1
|
||||
slice = call.Args[0]
|
||||
cause = stmt
|
||||
} else {
|
||||
chain++
|
||||
}
|
||||
}
|
||||
|
||||
// Required for printing chains that consist of trailing
|
||||
// statements from the list.
|
||||
flush()
|
||||
}
|
||||
|
||||
func (c *appendCombineChecker) matchAppend(stmt ast.Stmt, slice ast.Expr) *ast.CallExpr {
|
||||
// Seeking for:
|
||||
// slice = append(slice, xs...)
|
||||
// xs are 0-N append arguments, but not variadic argument,
|
||||
// because it makes append combining impossible.
|
||||
|
||||
assign := astcast.ToAssignStmt(stmt)
|
||||
if len(assign.Lhs) != 1 || len(assign.Rhs) != 1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
call, ok := assign.Rhs[0].(*ast.CallExpr)
|
||||
{
|
||||
cond := ok &&
|
||||
qualifiedName(call.Fun) == "append" &&
|
||||
call.Ellipsis == token.NoPos &&
|
||||
astequal.Expr(assign.Lhs[0], call.Args[0])
|
||||
if !cond {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// Check that current append slice match previous append slice.
|
||||
// Otherwise we should break the chain.
|
||||
if slice == nil || astequal.Expr(slice, call.Args[0]) {
|
||||
return call
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *appendCombineChecker) warn(cause ast.Node, chain int) {
|
||||
c.ctx.Warn(cause, "can combine chain of %d appends into one", chain)
|
||||
}
|
98
vendor/github.com/go-critic/go-critic/checkers/argOrder_checker.go
сгенерированный
поставляемый
Normal file
98
vendor/github.com/go-critic/go-critic/checkers/argOrder_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,98 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/types"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astcopy"
|
||||
"github.com/go-toolsmith/astp"
|
||||
"github.com/go-toolsmith/typep"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "argOrder"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects suspicious arguments order"
|
||||
info.Before = `strings.HasPrefix("#", userpass)`
|
||||
info.After = `strings.HasPrefix(userpass, "#")`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&argOrderChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type argOrderChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *argOrderChecker) VisitExpr(expr ast.Expr) {
|
||||
call := astcast.ToCallExpr(expr)
|
||||
|
||||
// For now only handle functions of 2 args.
|
||||
// TODO(Quasilyte): generalize the algorithm and add more patterns.
|
||||
if len(call.Args) != 2 {
|
||||
return
|
||||
}
|
||||
|
||||
calledExpr := astcast.ToSelectorExpr(call.Fun)
|
||||
obj, ok := c.ctx.TypesInfo.ObjectOf(astcast.ToIdent(calledExpr.X)).(*types.PkgName)
|
||||
if !ok || !isStdlibPkg(obj.Imported()) {
|
||||
return
|
||||
}
|
||||
|
||||
x := call.Args[0]
|
||||
y := call.Args[1]
|
||||
switch calledExpr.Sel.Name {
|
||||
case "HasPrefix", "HasSuffix", "Contains", "TrimPrefix", "TrimSuffix", "Split":
|
||||
if obj.Name() != "bytes" && obj.Name() != "strings" {
|
||||
return
|
||||
}
|
||||
if c.isConstLiteral(x) && !c.isConstLiteral(y) {
|
||||
c.warn(call)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *argOrderChecker) isConstLiteral(x ast.Expr) bool {
|
||||
if c.ctx.TypesInfo.Types[x].Value != nil {
|
||||
return true
|
||||
}
|
||||
|
||||
// Also permit byte slices.
|
||||
switch x := x.(type) {
|
||||
case *ast.CallExpr:
|
||||
// Handle `[]byte("abc")` as well.
|
||||
if len(x.Args) != 1 || !astp.IsBasicLit(x.Args[0]) {
|
||||
return false
|
||||
}
|
||||
typ, ok := c.ctx.TypesInfo.TypeOf(x.Fun).(*types.Slice)
|
||||
return ok && typep.HasUint8Kind(typ.Elem())
|
||||
|
||||
case *ast.CompositeLit:
|
||||
// Check if it's a const byte slice.
|
||||
typ, ok := c.ctx.TypesInfo.TypeOf(x).(*types.Slice)
|
||||
if !ok || !typep.HasUint8Kind(typ.Elem()) {
|
||||
return false
|
||||
}
|
||||
for _, elt := range x.Elts {
|
||||
if !astp.IsBasicLit(elt) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *argOrderChecker) warn(call *ast.CallExpr) {
|
||||
fixed := astcopy.CallExpr(call)
|
||||
fixed.Args[0], fixed.Args[1] = fixed.Args[1], fixed.Args[0]
|
||||
c.ctx.Warn(call, "probably meant `%s`", fixed)
|
||||
}
|
102
vendor/github.com/go-critic/go-critic/checkers/assignOp_checker.go
сгенерированный
поставляемый
Normal file
102
vendor/github.com/go-critic/go-critic/checkers/assignOp_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,102 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcopy"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
"github.com/go-toolsmith/typep"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "assignOp"
|
||||
info.Tags = []string{"style"}
|
||||
info.Summary = "Detects assignments that can be simplified by using assignment operators"
|
||||
info.Before = `x = x * 2`
|
||||
info.After = `x *= 2`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&assignOpChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type assignOpChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *assignOpChecker) VisitStmt(stmt ast.Stmt) {
|
||||
assign, ok := stmt.(*ast.AssignStmt)
|
||||
cond := ok &&
|
||||
assign.Tok == token.ASSIGN &&
|
||||
len(assign.Lhs) == 1 &&
|
||||
len(assign.Rhs) == 1 &&
|
||||
typep.SideEffectFree(c.ctx.TypesInfo, assign.Lhs[0])
|
||||
if !cond {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO(quasilyte): can take commutativity into account.
|
||||
expr, ok := assign.Rhs[0].(*ast.BinaryExpr)
|
||||
if !ok || !astequal.Expr(assign.Lhs[0], expr.X) {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO(quasilyte): perform unparen?
|
||||
switch expr.Op {
|
||||
case token.MUL:
|
||||
c.warn(assign, token.MUL_ASSIGN, expr.Y)
|
||||
case token.QUO:
|
||||
c.warn(assign, token.QUO_ASSIGN, expr.Y)
|
||||
case token.REM:
|
||||
c.warn(assign, token.REM_ASSIGN, expr.Y)
|
||||
case token.ADD:
|
||||
c.warn(assign, token.ADD_ASSIGN, expr.Y)
|
||||
case token.SUB:
|
||||
c.warn(assign, token.SUB_ASSIGN, expr.Y)
|
||||
case token.AND:
|
||||
c.warn(assign, token.AND_ASSIGN, expr.Y)
|
||||
case token.OR:
|
||||
c.warn(assign, token.OR_ASSIGN, expr.Y)
|
||||
case token.XOR:
|
||||
c.warn(assign, token.XOR_ASSIGN, expr.Y)
|
||||
case token.SHL:
|
||||
c.warn(assign, token.SHL_ASSIGN, expr.Y)
|
||||
case token.SHR:
|
||||
c.warn(assign, token.SHR_ASSIGN, expr.Y)
|
||||
case token.AND_NOT:
|
||||
c.warn(assign, token.AND_NOT_ASSIGN, expr.Y)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *assignOpChecker) warn(cause *ast.AssignStmt, op token.Token, rhs ast.Expr) {
|
||||
suggestion := c.simplify(cause, op, rhs)
|
||||
c.ctx.Warn(cause, "replace `%s` with `%s`", cause, suggestion)
|
||||
}
|
||||
|
||||
func (c *assignOpChecker) simplify(cause *ast.AssignStmt, op token.Token, rhs ast.Expr) ast.Stmt {
|
||||
if lit, ok := rhs.(*ast.BasicLit); ok && lit.Kind == token.INT && lit.Value == "1" {
|
||||
switch op {
|
||||
case token.ADD_ASSIGN:
|
||||
return &ast.IncDecStmt{
|
||||
X: cause.Lhs[0],
|
||||
TokPos: cause.TokPos,
|
||||
Tok: token.INC,
|
||||
}
|
||||
case token.SUB_ASSIGN:
|
||||
return &ast.IncDecStmt{
|
||||
X: cause.Lhs[0],
|
||||
TokPos: cause.TokPos,
|
||||
Tok: token.DEC,
|
||||
}
|
||||
}
|
||||
}
|
||||
suggestion := astcopy.AssignStmt(cause)
|
||||
suggestion.Tok = op
|
||||
suggestion.Rhs[0] = rhs
|
||||
return suggestion
|
||||
}
|
63
vendor/github.com/go-critic/go-critic/checkers/badCall_checker.go
сгенерированный
поставляемый
Normal file
63
vendor/github.com/go-critic/go-critic/checkers/badCall_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,63 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astcopy"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "badCall"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects suspicious function calls"
|
||||
info.Before = `strings.Replace(s, from, to, 0)`
|
||||
info.After = `strings.Replace(s, from, to, -1)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&badCallChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type badCallChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *badCallChecker) VisitExpr(expr ast.Expr) {
|
||||
call := astcast.ToCallExpr(expr)
|
||||
if len(call.Args) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO(quasilyte): handle methods.
|
||||
|
||||
switch qualifiedName(call.Fun) {
|
||||
case "strings.Replace", "bytes.Replace":
|
||||
if n := astcast.ToBasicLit(call.Args[3]); n.Value == "0" {
|
||||
c.warnBadArg(n, "-1")
|
||||
}
|
||||
case "strings.SplitN", "bytes.SplitN":
|
||||
if n := astcast.ToBasicLit(call.Args[2]); n.Value == "0" {
|
||||
c.warnBadArg(n, "-1")
|
||||
}
|
||||
case "append":
|
||||
if len(call.Args) == 1 {
|
||||
c.warnAppend(call)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badCallChecker) warnBadArg(badArg *ast.BasicLit, correction string) {
|
||||
goodArg := astcopy.BasicLit(badArg)
|
||||
goodArg.Value = correction
|
||||
c.ctx.Warn(badArg, "suspicious arg %s, probably meant %s",
|
||||
badArg, goodArg)
|
||||
}
|
||||
|
||||
func (c *badCallChecker) warnAppend(call *ast.CallExpr) {
|
||||
c.ctx.Warn(call, "no-op append call, probably missing arguments")
|
||||
}
|
147
vendor/github.com/go-critic/go-critic/checkers/badCond_checker.go
сгенерированный
поставляемый
Normal file
147
vendor/github.com/go-critic/go-critic/checkers/badCond_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,147 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/constant"
|
||||
"go/token"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/checkers/internal/lintutil"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astcopy"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
"github.com/go-toolsmith/typep"
|
||||
"golang.org/x/tools/go/ast/astutil"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "badCond"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects suspicious condition expressions"
|
||||
info.Before = `
|
||||
for i := 0; i > n; i++ {
|
||||
xs[i] = 0
|
||||
}`
|
||||
info.After = `
|
||||
for i := 0; i < n; i++ {
|
||||
xs[i] = 0
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForFuncDecl(&badCondChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type badCondChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *badCondChecker) VisitFuncDecl(decl *ast.FuncDecl) {
|
||||
ast.Inspect(decl.Body, func(n ast.Node) bool {
|
||||
switch n := n.(type) {
|
||||
case *ast.ForStmt:
|
||||
c.checkForStmt(n)
|
||||
case ast.Expr:
|
||||
c.checkExpr(n)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (c *badCondChecker) checkExpr(expr ast.Expr) {
|
||||
// TODO(Quasilyte): recognize more patterns.
|
||||
|
||||
cond := astcast.ToBinaryExpr(expr)
|
||||
lhs := astcast.ToBinaryExpr(astutil.Unparen(cond.X))
|
||||
rhs := astcast.ToBinaryExpr(astutil.Unparen(cond.Y))
|
||||
|
||||
if cond.Op != token.LAND {
|
||||
return
|
||||
}
|
||||
|
||||
// Notes:
|
||||
// `x != a || x != b` handled by go vet.
|
||||
|
||||
// Pattern 1.
|
||||
// `x < a && x > b`; Where `a` is less than `b`.
|
||||
if c.lessAndGreater(lhs, rhs) {
|
||||
c.warnCond(cond, "always false")
|
||||
return
|
||||
}
|
||||
|
||||
// Pattern 2.
|
||||
// `x == a && x == b`
|
||||
//
|
||||
// Valid when `b == a` is intended, but still reported.
|
||||
// We can disable "just suspicious" warnings by default
|
||||
// is users are upset with the current behavior.
|
||||
if c.equalToBoth(lhs, rhs) {
|
||||
c.warnCond(cond, "suspicious")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badCondChecker) equalToBoth(lhs, rhs *ast.BinaryExpr) bool {
|
||||
return lhs.Op == token.EQL && rhs.Op == token.EQL &&
|
||||
astequal.Expr(lhs.X, rhs.X)
|
||||
}
|
||||
|
||||
func (c *badCondChecker) lessAndGreater(lhs, rhs *ast.BinaryExpr) bool {
|
||||
if lhs.Op != token.LSS || rhs.Op != token.GTR {
|
||||
return false
|
||||
}
|
||||
if !astequal.Expr(lhs.X, rhs.X) {
|
||||
return false
|
||||
}
|
||||
a := c.ctx.TypesInfo.Types[lhs.Y].Value
|
||||
b := c.ctx.TypesInfo.Types[rhs.Y].Value
|
||||
return a != nil && b != nil && constant.Compare(a, token.LSS, b)
|
||||
}
|
||||
|
||||
func (c *badCondChecker) checkForStmt(stmt *ast.ForStmt) {
|
||||
// TODO(Quasilyte): handle other kinds of bad conditionals.
|
||||
|
||||
init := astcast.ToAssignStmt(stmt.Init)
|
||||
if init.Tok != token.DEFINE || len(init.Lhs) != 1 || len(init.Rhs) != 1 {
|
||||
return
|
||||
}
|
||||
if astcast.ToBasicLit(init.Rhs[0]).Value != "0" {
|
||||
return
|
||||
}
|
||||
|
||||
iter := astcast.ToIdent(init.Lhs[0])
|
||||
cond := astcast.ToBinaryExpr(stmt.Cond)
|
||||
if cond.Op != token.GTR || !astequal.Expr(iter, cond.X) {
|
||||
return
|
||||
}
|
||||
if !typep.SideEffectFree(c.ctx.TypesInfo, cond.Y) {
|
||||
return
|
||||
}
|
||||
|
||||
post := astcast.ToIncDecStmt(stmt.Post)
|
||||
if post.Tok != token.INC || !astequal.Expr(iter, post.X) {
|
||||
return
|
||||
}
|
||||
|
||||
mutated := lintutil.CouldBeMutated(c.ctx.TypesInfo, stmt.Body, cond.Y) ||
|
||||
lintutil.CouldBeMutated(c.ctx.TypesInfo, stmt.Body, iter)
|
||||
if mutated {
|
||||
return
|
||||
}
|
||||
|
||||
c.warnForStmt(stmt, cond)
|
||||
}
|
||||
|
||||
func (c *badCondChecker) warnForStmt(cause ast.Node, cond *ast.BinaryExpr) {
|
||||
suggest := astcopy.BinaryExpr(cond)
|
||||
suggest.Op = token.LSS
|
||||
c.ctx.Warn(cause, "`%s` in loop; probably meant `%s`?",
|
||||
cond, suggest)
|
||||
}
|
||||
|
||||
func (c *badCondChecker) warnCond(cond *ast.BinaryExpr, tag string) {
|
||||
c.ctx.Warn(cond, "`%s` condition is %s", cond, tag)
|
||||
}
|
445
vendor/github.com/go-critic/go-critic/checkers/badRegexp_checker.go
сгенерированный
поставляемый
Normal file
445
vendor/github.com/go-critic/go-critic/checkers/badRegexp_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,445 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/constant"
|
||||
"sort"
|
||||
"strconv"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/quasilyte/regex/syntax"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "badRegexp"
|
||||
info.Tags = []string{"diagnostic", "experimental"}
|
||||
info.Summary = "Detects suspicious regexp patterns"
|
||||
info.Before = "regexp.MustCompile(`(?:^aa|bb|cc)foo[aba]`)"
|
||||
info.After = "regexp.MustCompile(`^(?:aa|bb|cc)foo[ab]`)"
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
opts := &syntax.ParserOptions{}
|
||||
c := &badRegexpChecker{
|
||||
ctx: ctx,
|
||||
parser: syntax.NewParser(opts),
|
||||
}
|
||||
return astwalk.WalkerForExpr(c)
|
||||
})
|
||||
}
|
||||
|
||||
type badRegexpChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
parser *syntax.Parser
|
||||
cause ast.Expr
|
||||
|
||||
flagStates []regexpFlagState
|
||||
goodAnchors []syntax.Position
|
||||
}
|
||||
|
||||
type regexpFlagState [utf8.RuneSelf]bool
|
||||
|
||||
func (c *badRegexpChecker) VisitExpr(x ast.Expr) {
|
||||
call, ok := x.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
switch qualifiedName(call.Fun) {
|
||||
case "regexp.Compile", "regexp.MustCompile":
|
||||
cv := c.ctx.TypesInfo.Types[call.Args[0]].Value
|
||||
if cv == nil || cv.Kind() != constant.String {
|
||||
return
|
||||
}
|
||||
pat := constant.StringVal(cv)
|
||||
c.cause = call.Args[0]
|
||||
c.checkPattern(pat)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) checkPattern(pat string) {
|
||||
re, err := c.parser.Parse(pat)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
c.flagStates = c.flagStates[:0]
|
||||
c.goodAnchors = c.goodAnchors[:0]
|
||||
|
||||
// In Go all flags (modifiers) are set to false by default,
|
||||
// so we start from the empty flag set.
|
||||
c.flagStates = append(c.flagStates, regexpFlagState{})
|
||||
|
||||
c.markGoodCarets(re.Expr)
|
||||
c.walk(re.Expr)
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) markGoodCarets(e syntax.Expr) {
|
||||
canSkip := func(e syntax.Expr) bool {
|
||||
switch e.Op {
|
||||
case syntax.OpFlagOnlyGroup:
|
||||
return true
|
||||
case syntax.OpGroup:
|
||||
x := e.Args[0]
|
||||
return x.Op == syntax.OpConcat && len(x.Args) == 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if e.Op == syntax.OpConcat && len(e.Args) > 1 {
|
||||
i := 0
|
||||
for i < len(e.Args) && canSkip(e.Args[i]) {
|
||||
i++
|
||||
}
|
||||
if i < len(e.Args) {
|
||||
c.markGoodCarets(e.Args[i])
|
||||
}
|
||||
return
|
||||
}
|
||||
if e.Op == syntax.OpCaret {
|
||||
c.addGoodAnchor(e.Pos)
|
||||
}
|
||||
for _, a := range e.Args {
|
||||
c.markGoodCarets(a)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) walk(e syntax.Expr) {
|
||||
switch e.Op {
|
||||
case syntax.OpAlt:
|
||||
c.checkAltAnchor(e)
|
||||
c.checkAltDups(e)
|
||||
for _, a := range e.Args {
|
||||
c.walk(a)
|
||||
}
|
||||
|
||||
case syntax.OpCharClass, syntax.OpNegCharClass:
|
||||
if c.checkCharClassRanges(e) {
|
||||
c.checkCharClassDups(e)
|
||||
}
|
||||
|
||||
case syntax.OpStar, syntax.OpPlus:
|
||||
c.checkNestedQuantifier(e)
|
||||
c.walk(e.Args[0])
|
||||
|
||||
case syntax.OpFlagOnlyGroup:
|
||||
c.updateFlagState(c.currentFlagState(), e, e.Args[0].Value)
|
||||
case syntax.OpGroupWithFlags:
|
||||
// Creates a new context using the current context copy.
|
||||
// New flags are evaluated inside a new context.
|
||||
// After nested expressions are processed, previous context is restored.
|
||||
nflags := len(c.flagStates)
|
||||
c.flagStates = append(c.flagStates, *c.currentFlagState())
|
||||
c.updateFlagState(c.currentFlagState(), e, e.Args[1].Value)
|
||||
c.walk(e.Args[0])
|
||||
c.flagStates = c.flagStates[:nflags]
|
||||
case syntax.OpGroup, syntax.OpCapture, syntax.OpNamedCapture:
|
||||
// Like with OpGroupWithFlags, but doesn't evaluate any new flags.
|
||||
nflags := len(c.flagStates)
|
||||
c.flagStates = append(c.flagStates, *c.currentFlagState())
|
||||
c.walk(e.Args[0])
|
||||
c.flagStates = c.flagStates[:nflags]
|
||||
|
||||
case syntax.OpCaret:
|
||||
if !c.isGoodAnchor(e) {
|
||||
c.warn("dangling or redundant ^, maybe \\^ is intended?")
|
||||
}
|
||||
|
||||
default:
|
||||
for _, a := range e.Args {
|
||||
c.walk(a)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) currentFlagState() *regexpFlagState {
|
||||
return &c.flagStates[len(c.flagStates)-1]
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) updateFlagState(state *regexpFlagState, e syntax.Expr, flagString string) {
|
||||
clearing := false
|
||||
for i := 0; i < len(flagString); i++ {
|
||||
ch := flagString[i]
|
||||
if ch == '-' {
|
||||
clearing = true
|
||||
continue
|
||||
}
|
||||
if int(ch) >= len(state) {
|
||||
continue // Should never happen in practice, but we don't want a panic
|
||||
}
|
||||
|
||||
if clearing {
|
||||
if !state[ch] {
|
||||
c.warn("clearing unset flag %c in %s", ch, e.Value)
|
||||
}
|
||||
} else {
|
||||
if state[ch] {
|
||||
c.warn("redundant flag %c in %s", ch, e.Value)
|
||||
}
|
||||
}
|
||||
state[ch] = !clearing
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) checkNestedQuantifier(e syntax.Expr) {
|
||||
x := e.Args[0]
|
||||
switch x.Op {
|
||||
case syntax.OpGroup, syntax.OpCapture, syntax.OpGroupWithFlags:
|
||||
if len(e.Args) == 1 {
|
||||
x = x.Args[0]
|
||||
}
|
||||
}
|
||||
|
||||
switch x.Op {
|
||||
case syntax.OpPlus, syntax.OpStar:
|
||||
c.warn("repeated greedy quantifier in %s", e.Value)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) checkAltDups(alt syntax.Expr) {
|
||||
// Seek duplicated alternation expressions.
|
||||
|
||||
set := make(map[string]struct{}, len(alt.Args))
|
||||
for _, a := range alt.Args {
|
||||
if _, ok := set[a.Value]; ok {
|
||||
c.warn("`%s` is duplicated in %s", a.Value, alt.Value)
|
||||
}
|
||||
set[a.Value] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) isCharOrLit(e syntax.Expr) bool {
|
||||
return e.Op == syntax.OpChar || e.Op == syntax.OpLiteral
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) checkAltAnchor(alt syntax.Expr) {
|
||||
// Seek suspicious anchors.
|
||||
|
||||
// Case 1: an alternation of literals where 1st expr begins with ^ anchor.
|
||||
first := alt.Args[0]
|
||||
if first.Op == syntax.OpConcat && len(first.Args) == 2 && first.Args[0].Op == syntax.OpCaret && c.isCharOrLit(first.Args[1]) {
|
||||
matched := true
|
||||
for _, a := range alt.Args[1:] {
|
||||
if !c.isCharOrLit(a) {
|
||||
matched = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
c.warn("^ applied only to `%s` in %s", first.Value[len(`^`):], alt.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// Case 2: an alternation of literals where last expr ends with $ anchor.
|
||||
last := alt.Args[len(alt.Args)-1]
|
||||
if last.Op == syntax.OpConcat && len(last.Args) == 2 && last.Args[1].Op == syntax.OpDollar && c.isCharOrLit(last.Args[0]) {
|
||||
matched := true
|
||||
for _, a := range alt.Args[:len(alt.Args)-1] {
|
||||
if !c.isCharOrLit(a) {
|
||||
matched = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
c.warn("$ applied only to `%s` in %s", last.Value[:len(last.Value)-len(`$`)], alt.Value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) checkCharClassRanges(cc syntax.Expr) bool {
|
||||
// Seek for suspicious ranges like `!-_`.
|
||||
//
|
||||
// We permit numerical ranges (0-9, hex and octal literals)
|
||||
// and simple ascii letter ranges.
|
||||
|
||||
for _, e := range cc.Args {
|
||||
if e.Op != syntax.OpCharRange {
|
||||
continue
|
||||
}
|
||||
switch e.Args[0].Op {
|
||||
case syntax.OpEscapeOctal, syntax.OpEscapeHex:
|
||||
continue
|
||||
}
|
||||
ch := c.charClassBoundRune(e.Args[0])
|
||||
if ch == 0 {
|
||||
return false
|
||||
}
|
||||
good := unicode.IsLetter(ch) || (ch >= '0' && ch <= '9')
|
||||
if !good {
|
||||
c.warnSloppyCharRange(e.Value, cc.Value)
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) checkCharClassDups(cc syntax.Expr) {
|
||||
// Seek for excessive elements inside a character class.
|
||||
// Report them as intersections.
|
||||
|
||||
if len(cc.Args) == 1 {
|
||||
return // Can't had duplicates.
|
||||
}
|
||||
|
||||
type charRange struct {
|
||||
low rune
|
||||
high rune
|
||||
source string
|
||||
}
|
||||
ranges := make([]charRange, 0, 8)
|
||||
addRange := func(source string, low, high rune) {
|
||||
ranges = append(ranges, charRange{source: source, low: low, high: high})
|
||||
}
|
||||
addRange1 := func(source string, ch rune) {
|
||||
addRange(source, ch, ch)
|
||||
}
|
||||
|
||||
// 1. Collect ranges, O(n).
|
||||
for _, e := range cc.Args {
|
||||
switch e.Op {
|
||||
case syntax.OpEscapeOctal:
|
||||
addRange1(e.Value, c.octalToRune(e))
|
||||
case syntax.OpEscapeHex:
|
||||
addRange1(e.Value, c.hexToRune(e))
|
||||
case syntax.OpChar:
|
||||
addRange1(e.Value, c.stringToRune(e.Value))
|
||||
case syntax.OpCharRange:
|
||||
addRange(e.Value, c.charClassBoundRune(e.Args[0]), c.charClassBoundRune(e.Args[1]))
|
||||
case syntax.OpEscapeMeta:
|
||||
addRange1(e.Value, rune(e.Value[1]))
|
||||
case syntax.OpEscapeChar:
|
||||
ch := c.stringToRune(e.Value[len(`\`):])
|
||||
if unicode.IsPunct(ch) {
|
||||
addRange1(e.Value, ch)
|
||||
break
|
||||
}
|
||||
switch e.Value {
|
||||
case `\|`, `\<`, `\>`, `\+`, `\=`: // How to cover all symbols?
|
||||
addRange1(e.Value, c.stringToRune(e.Value[len(`\`):]))
|
||||
case `\t`:
|
||||
addRange1(e.Value, '\t')
|
||||
case `\n`:
|
||||
addRange1(e.Value, '\n')
|
||||
case `\r`:
|
||||
addRange1(e.Value, '\r')
|
||||
case `\v`:
|
||||
addRange1(e.Value, '\v')
|
||||
case `\d`:
|
||||
addRange(e.Value, '0', '9')
|
||||
case `\D`:
|
||||
addRange(e.Value, 0, '0'-1)
|
||||
addRange(e.Value, '9'+1, utf8.MaxRune)
|
||||
case `\s`:
|
||||
addRange(e.Value, '\t', '\n') // 9-10
|
||||
addRange(e.Value, '\f', '\r') // 12-13
|
||||
addRange1(e.Value, ' ') // 32
|
||||
case `\S`:
|
||||
addRange(e.Value, 0, '\t'-1)
|
||||
addRange(e.Value, '\n'+1, '\f'-1)
|
||||
addRange(e.Value, '\r'+1, ' '-1)
|
||||
addRange(e.Value, ' '+1, utf8.MaxRune)
|
||||
case `\w`:
|
||||
addRange(e.Value, '0', '9') // 48-57
|
||||
addRange(e.Value, 'A', 'Z') // 65-90
|
||||
addRange1(e.Value, '_') // 95
|
||||
addRange(e.Value, 'a', 'z') // 97-122
|
||||
case `\W`:
|
||||
addRange(e.Value, 0, '0'-1)
|
||||
addRange(e.Value, '9'+1, 'A'-1)
|
||||
addRange(e.Value, 'Z'+1, '_'-1)
|
||||
addRange(e.Value, '_'+1, 'a'-1)
|
||||
addRange(e.Value, 'z'+1, utf8.MaxRune)
|
||||
default:
|
||||
// Give up: unknown escape sequence.
|
||||
return
|
||||
}
|
||||
default:
|
||||
// Give up: unexpected operation inside char class.
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Sort ranges, O(nlogn).
|
||||
sort.Slice(ranges, func(i, j int) bool {
|
||||
return ranges[i].low < ranges[j].low
|
||||
})
|
||||
|
||||
// 3. Search for duplicates, O(n).
|
||||
for i := 0; i < len(ranges)-1; i++ {
|
||||
x := ranges[i+0]
|
||||
y := ranges[i+1]
|
||||
if x.high >= y.low {
|
||||
c.warnCharClassDup(x.source, y.source, cc.Value)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) charClassBoundRune(e syntax.Expr) rune {
|
||||
switch e.Op {
|
||||
case syntax.OpChar:
|
||||
return c.stringToRune(e.Value)
|
||||
case syntax.OpEscapeHex:
|
||||
return c.hexToRune(e)
|
||||
case syntax.OpEscapeOctal:
|
||||
return c.octalToRune(e)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) octalToRune(e syntax.Expr) rune {
|
||||
v, _ := strconv.ParseInt(e.Value[len(`\`):], 8, 32)
|
||||
return rune(v)
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) hexToRune(e syntax.Expr) rune {
|
||||
var s string
|
||||
switch e.Form {
|
||||
case syntax.FormEscapeHexFull:
|
||||
s = e.Value[len(`\x{`) : len(e.Value)-len(`}`)]
|
||||
default:
|
||||
s = e.Value[len(`\x`):]
|
||||
}
|
||||
v, _ := strconv.ParseInt(s, 16, 32)
|
||||
return rune(v)
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) stringToRune(s string) rune {
|
||||
ch, _ := utf8.DecodeRuneInString(s)
|
||||
return ch
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) addGoodAnchor(pos syntax.Position) {
|
||||
c.goodAnchors = append(c.goodAnchors, pos)
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) isGoodAnchor(e syntax.Expr) bool {
|
||||
for _, pos := range c.goodAnchors {
|
||||
if e.Pos == pos {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) warn(format string, args ...interface{}) {
|
||||
c.ctx.Warn(c.cause, format, args...)
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) warnSloppyCharRange(rng, charClass string) {
|
||||
c.ctx.Warn(c.cause, "suspicious char range `%s` in %s", rng, charClass)
|
||||
}
|
||||
|
||||
func (c *badRegexpChecker) warnCharClassDup(x, y, charClass string) {
|
||||
if x == y {
|
||||
c.ctx.Warn(c.cause, "`%s` is duplicated in %s", x, charClass)
|
||||
} else {
|
||||
c.ctx.Warn(c.cause, "`%s` intersects with `%s` in %s", x, y, charClass)
|
||||
}
|
||||
}
|
344
vendor/github.com/go-critic/go-critic/checkers/boolExprSimplify_checker.go
сгенерированный
поставляемый
Normal file
344
vendor/github.com/go-critic/go-critic/checkers/boolExprSimplify_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,344 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"strconv"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/checkers/internal/lintutil"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astcopy"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
"github.com/go-toolsmith/astp"
|
||||
"github.com/go-toolsmith/typep"
|
||||
"golang.org/x/tools/go/ast/astutil"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "boolExprSimplify"
|
||||
info.Tags = []string{"style", "experimental"}
|
||||
info.Summary = "Detects bool expressions that can be simplified"
|
||||
info.Before = `
|
||||
a := !(elapsed >= expectElapsedMin)
|
||||
b := !(x) == !(y)`
|
||||
info.After = `
|
||||
a := elapsed < expectElapsedMin
|
||||
b := (x) == (y)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&boolExprSimplifyChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type boolExprSimplifyChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
hasFloats bool
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) VisitExpr(x ast.Expr) {
|
||||
if !astp.IsBinaryExpr(x) && !astp.IsUnaryExpr(x) {
|
||||
return
|
||||
}
|
||||
|
||||
// Throw away non-bool expressions and avoid redundant
|
||||
// AST copying below.
|
||||
if typ := c.ctx.TypesInfo.TypeOf(x); typ == nil || !typep.HasBoolKind(typ.Underlying()) {
|
||||
return
|
||||
}
|
||||
|
||||
// We'll loose all types info after a copy,
|
||||
// this is why we record valuable info before doing it.
|
||||
c.hasFloats = lintutil.ContainsNode(x, func(n ast.Node) bool {
|
||||
if x, ok := n.(*ast.BinaryExpr); ok {
|
||||
return typep.HasFloatProp(c.ctx.TypesInfo.TypeOf(x.X).Underlying()) ||
|
||||
typep.HasFloatProp(c.ctx.TypesInfo.TypeOf(x.Y).Underlying())
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
y := c.simplifyBool(astcopy.Expr(x))
|
||||
if !astequal.Expr(x, y) {
|
||||
c.warn(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) simplifyBool(x ast.Expr) ast.Expr {
|
||||
return astutil.Apply(x, nil, func(cur *astutil.Cursor) bool {
|
||||
return c.doubleNegation(cur) ||
|
||||
c.negatedEquals(cur) ||
|
||||
c.invertComparison(cur) ||
|
||||
c.combineChecks(cur) ||
|
||||
c.removeIncDec(cur) ||
|
||||
c.foldRanges(cur) ||
|
||||
true
|
||||
}).(ast.Expr)
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) doubleNegation(cur *astutil.Cursor) bool {
|
||||
neg1 := astcast.ToUnaryExpr(cur.Node())
|
||||
neg2 := astcast.ToUnaryExpr(astutil.Unparen(neg1.X))
|
||||
if neg1.Op == token.NOT && neg2.Op == token.NOT {
|
||||
cur.Replace(astutil.Unparen(neg2.X))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) negatedEquals(cur *astutil.Cursor) bool {
|
||||
x, ok := cur.Node().(*ast.BinaryExpr)
|
||||
if !ok || x.Op != token.EQL {
|
||||
return false
|
||||
}
|
||||
neg1 := astcast.ToUnaryExpr(x.X)
|
||||
neg2 := astcast.ToUnaryExpr(x.Y)
|
||||
if neg1.Op == token.NOT && neg2.Op == token.NOT {
|
||||
x.X = neg1.X
|
||||
x.Y = neg2.X
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) invertComparison(cur *astutil.Cursor) bool {
|
||||
if c.hasFloats { // See #673
|
||||
return false
|
||||
}
|
||||
|
||||
neg := astcast.ToUnaryExpr(cur.Node())
|
||||
cmp := astcast.ToBinaryExpr(astutil.Unparen(neg.X))
|
||||
if neg.Op != token.NOT {
|
||||
return false
|
||||
}
|
||||
|
||||
// Replace operator to its negated form.
|
||||
switch cmp.Op {
|
||||
case token.EQL:
|
||||
cmp.Op = token.NEQ
|
||||
case token.NEQ:
|
||||
cmp.Op = token.EQL
|
||||
case token.LSS:
|
||||
cmp.Op = token.GEQ
|
||||
case token.GTR:
|
||||
cmp.Op = token.LEQ
|
||||
case token.LEQ:
|
||||
cmp.Op = token.GTR
|
||||
case token.GEQ:
|
||||
cmp.Op = token.LSS
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
cur.Replace(cmp)
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) isSafe(x ast.Expr) bool {
|
||||
return typep.SideEffectFree(c.ctx.TypesInfo, x)
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) combineChecks(cur *astutil.Cursor) bool {
|
||||
or, ok := cur.Node().(*ast.BinaryExpr)
|
||||
if !ok || or.Op != token.LOR {
|
||||
return false
|
||||
}
|
||||
|
||||
lhs := astcast.ToBinaryExpr(astutil.Unparen(or.X))
|
||||
rhs := astcast.ToBinaryExpr(astutil.Unparen(or.Y))
|
||||
|
||||
if !astequal.Expr(lhs.X, rhs.X) || !astequal.Expr(lhs.Y, rhs.Y) {
|
||||
return false
|
||||
}
|
||||
if !c.isSafe(lhs.X) || !c.isSafe(lhs.Y) {
|
||||
return false
|
||||
}
|
||||
|
||||
combTable := [...]struct {
|
||||
x token.Token
|
||||
y token.Token
|
||||
result token.Token
|
||||
}{
|
||||
{token.GTR, token.EQL, token.GEQ},
|
||||
{token.EQL, token.GTR, token.GEQ},
|
||||
{token.LSS, token.EQL, token.LEQ},
|
||||
{token.EQL, token.LSS, token.LEQ},
|
||||
}
|
||||
for _, comb := range &combTable {
|
||||
if comb.x == lhs.Op && comb.y == rhs.Op {
|
||||
lhs.Op = comb.result
|
||||
cur.Replace(lhs)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) removeIncDec(cur *astutil.Cursor) bool {
|
||||
cmp := astcast.ToBinaryExpr(cur.Node())
|
||||
|
||||
matchOneWay := func(op token.Token, x, y *ast.BinaryExpr) bool {
|
||||
if x.Op != op || astcast.ToBasicLit(x.Y).Value != "1" {
|
||||
return false
|
||||
}
|
||||
if y.Op == op && astcast.ToBasicLit(y.Y).Value == "1" {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
replace := func(lhsOp, rhsOp, replacement token.Token) bool {
|
||||
lhs := astcast.ToBinaryExpr(cmp.X)
|
||||
rhs := astcast.ToBinaryExpr(cmp.Y)
|
||||
switch {
|
||||
case matchOneWay(lhsOp, lhs, rhs):
|
||||
cmp.X = lhs.X
|
||||
cmp.Op = replacement
|
||||
cur.Replace(cmp)
|
||||
return true
|
||||
case matchOneWay(rhsOp, rhs, lhs):
|
||||
cmp.Y = rhs.X
|
||||
cmp.Op = replacement
|
||||
cur.Replace(cmp)
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
switch cmp.Op {
|
||||
case token.GTR:
|
||||
// `x > y-1` => `x >= y`
|
||||
// `x+1 > y` => `x >= y`
|
||||
return replace(token.ADD, token.SUB, token.GEQ)
|
||||
|
||||
case token.GEQ:
|
||||
// `x >= y+1` => `x > y`
|
||||
// `x-1 >= y` => `x > y`
|
||||
return replace(token.SUB, token.ADD, token.GTR)
|
||||
|
||||
case token.LSS:
|
||||
// `x < y+1` => `x <= y`
|
||||
// `x-1 < y` => `x <= y`
|
||||
return replace(token.SUB, token.ADD, token.LEQ)
|
||||
|
||||
case token.LEQ:
|
||||
// `x <= y-1` => `x < y`
|
||||
// `x+1 <= y` => `x < y`
|
||||
return replace(token.ADD, token.SUB, token.LSS)
|
||||
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) foldRanges(cur *astutil.Cursor) bool {
|
||||
if c.hasFloats { // See #848
|
||||
return false
|
||||
}
|
||||
|
||||
e, ok := cur.Node().(*ast.BinaryExpr)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
lhs := astcast.ToBinaryExpr(e.X)
|
||||
rhs := astcast.ToBinaryExpr(e.Y)
|
||||
if !c.isSafe(lhs.X) || !c.isSafe(rhs.X) {
|
||||
return false
|
||||
}
|
||||
if !astequal.Expr(lhs.X, rhs.X) {
|
||||
return false
|
||||
}
|
||||
|
||||
c1, ok := c.int64val(lhs.Y)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
c2, ok := c.int64val(rhs.Y)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
type combination struct {
|
||||
lhsOp token.Token
|
||||
rhsOp token.Token
|
||||
rhsDiff int64
|
||||
resDelta int64
|
||||
}
|
||||
match := func(comb *combination) bool {
|
||||
if lhs.Op != comb.lhsOp || rhs.Op != comb.rhsOp {
|
||||
return false
|
||||
}
|
||||
if c2-c1 != comb.rhsDiff {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
switch e.Op {
|
||||
case token.LAND:
|
||||
combTable := [...]combination{
|
||||
// `x > c && x < c+2` => `x == c+1`
|
||||
{token.GTR, token.LSS, 2, 1},
|
||||
// `x >= c && x < c+1` => `x == c`
|
||||
{token.GEQ, token.LSS, 1, 0},
|
||||
// `x > c && x <= c+1` => `x == c+1`
|
||||
{token.GTR, token.LEQ, 1, 1},
|
||||
// `x >= c && x <= c` => `x == c`
|
||||
{token.GEQ, token.LEQ, 0, 0},
|
||||
}
|
||||
for _, comb := range combTable {
|
||||
if match(&comb) {
|
||||
lhs.Op = token.EQL
|
||||
v := c1 + comb.resDelta
|
||||
lhs.Y.(*ast.BasicLit).Value = fmt.Sprint(v)
|
||||
cur.Replace(lhs)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
case token.LOR:
|
||||
combTable := [...]combination{
|
||||
// `x < c || x > c` => `x != c`
|
||||
{token.LSS, token.GTR, 0, 0},
|
||||
// `x <= c || x > c+1` => `x != c+1`
|
||||
{token.LEQ, token.GTR, 1, 1},
|
||||
// `x < c || x >= c+1` => `x != c`
|
||||
{token.LSS, token.GEQ, 1, 0},
|
||||
// `x <= c || x >= c+2` => `x != c+1`
|
||||
{token.LEQ, token.GEQ, 2, 1},
|
||||
}
|
||||
for _, comb := range combTable {
|
||||
if match(&comb) {
|
||||
lhs.Op = token.NEQ
|
||||
v := c1 + comb.resDelta
|
||||
lhs.Y.(*ast.BasicLit).Value = fmt.Sprint(v)
|
||||
cur.Replace(lhs)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) int64val(x ast.Expr) (int64, bool) {
|
||||
// TODO(Quasilyte): if we had types info, we could use TypesInfo.Types[x].Value,
|
||||
// but since copying erases leaves us without it, only basic literals are handled.
|
||||
lit, ok := x.(*ast.BasicLit)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
v, err := strconv.ParseInt(lit.Value, 10, 64)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
return v, true
|
||||
}
|
||||
|
||||
func (c *boolExprSimplifyChecker) warn(cause, suggestion ast.Expr) {
|
||||
c.SkipChilds = true
|
||||
c.ctx.Warn(cause, "can simplify `%s` to `%s`", cause, suggestion)
|
||||
}
|
36
vendor/github.com/go-critic/go-critic/checkers/builtinShadow_checker.go
сгенерированный
поставляемый
Normal file
36
vendor/github.com/go-critic/go-critic/checkers/builtinShadow_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,36 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "builtinShadow"
|
||||
info.Tags = []string{"style", "opinionated"}
|
||||
info.Summary = "Detects when predeclared identifiers shadowed in assignments"
|
||||
info.Before = `len := 10`
|
||||
info.After = `length := 10`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForLocalDef(&builtinShadowChecker{ctx: ctx}, ctx.TypesInfo)
|
||||
})
|
||||
}
|
||||
|
||||
type builtinShadowChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *builtinShadowChecker) VisitLocalDef(name astwalk.Name, _ ast.Expr) {
|
||||
if isBuiltin(name.ID.Name) {
|
||||
c.warn(name.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *builtinShadowChecker) warn(ident *ast.Ident) {
|
||||
c.ctx.Warn(ident, "shadowing of predeclared identifier: %s", ident)
|
||||
}
|
49
vendor/github.com/go-critic/go-critic/checkers/captLocal_checker.go
сгенерированный
поставляемый
Normal file
49
vendor/github.com/go-critic/go-critic/checkers/captLocal_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,49 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "captLocal"
|
||||
info.Tags = []string{"style"}
|
||||
info.Params = linter.CheckerParams{
|
||||
"paramsOnly": {
|
||||
Value: true,
|
||||
Usage: "whether to restrict checker to params only",
|
||||
},
|
||||
}
|
||||
info.Summary = "Detects capitalized names for local variables"
|
||||
info.Before = `func f(IN int, OUT *int) (ERR error) {}`
|
||||
info.After = `func f(in int, out *int) (err error) {}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
c := &captLocalChecker{ctx: ctx}
|
||||
c.paramsOnly = info.Params.Bool("paramsOnly")
|
||||
return astwalk.WalkerForLocalDef(c, ctx.TypesInfo)
|
||||
})
|
||||
}
|
||||
|
||||
type captLocalChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
paramsOnly bool
|
||||
}
|
||||
|
||||
func (c *captLocalChecker) VisitLocalDef(def astwalk.Name, _ ast.Expr) {
|
||||
if c.paramsOnly && def.Kind != astwalk.NameParam {
|
||||
return
|
||||
}
|
||||
if ast.IsExported(def.ID.Name) {
|
||||
c.warn(def.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *captLocalChecker) warn(id ast.Node) {
|
||||
c.ctx.Warn(id, "`%s' should not be capitalized", id)
|
||||
}
|
88
vendor/github.com/go-critic/go-critic/checkers/caseOrder_checker.go
сгенерированный
поставляемый
Normal file
88
vendor/github.com/go-critic/go-critic/checkers/caseOrder_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,88 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/types"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "caseOrder"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects erroneous case order inside switch statements"
|
||||
info.Before = `
|
||||
switch x.(type) {
|
||||
case ast.Expr:
|
||||
fmt.Println("expr")
|
||||
case *ast.BasicLit:
|
||||
fmt.Println("basic lit") // Never executed
|
||||
}`
|
||||
info.After = `
|
||||
switch x.(type) {
|
||||
case *ast.BasicLit:
|
||||
fmt.Println("basic lit") // Now reachable
|
||||
case ast.Expr:
|
||||
fmt.Println("expr")
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&caseOrderChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type caseOrderChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *caseOrderChecker) VisitStmt(stmt ast.Stmt) {
|
||||
switch stmt := stmt.(type) {
|
||||
case *ast.TypeSwitchStmt:
|
||||
c.checkTypeSwitch(stmt)
|
||||
case *ast.SwitchStmt:
|
||||
c.checkSwitch(stmt)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *caseOrderChecker) checkTypeSwitch(s *ast.TypeSwitchStmt) {
|
||||
type ifaceType struct {
|
||||
node ast.Node
|
||||
typ *types.Interface
|
||||
}
|
||||
var ifaces []ifaceType // Interfaces seen so far
|
||||
for _, cc := range s.Body.List {
|
||||
cc := cc.(*ast.CaseClause)
|
||||
for _, x := range cc.List {
|
||||
typ := c.ctx.TypesInfo.TypeOf(x)
|
||||
if typ == nil {
|
||||
c.warnTypeImpl(cc, x)
|
||||
return
|
||||
}
|
||||
for _, iface := range ifaces {
|
||||
if types.Implements(typ, iface.typ) {
|
||||
c.warnTypeSwitch(cc, x, iface.node)
|
||||
break
|
||||
}
|
||||
}
|
||||
if iface, ok := typ.Underlying().(*types.Interface); ok {
|
||||
ifaces = append(ifaces, ifaceType{node: x, typ: iface})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *caseOrderChecker) warnTypeSwitch(cause, concrete, iface ast.Node) {
|
||||
c.ctx.Warn(cause, "case %s must go before the %s case", concrete, iface)
|
||||
}
|
||||
|
||||
func (c *caseOrderChecker) warnTypeImpl(cause, concrete ast.Node) {
|
||||
c.ctx.Warn(cause, "type is not defined %s", concrete)
|
||||
}
|
||||
|
||||
func (c *caseOrderChecker) checkSwitch(s *ast.SwitchStmt) {
|
||||
// TODO(Quasilyte): can handle expression cases that overlap.
|
||||
// Cases that have narrower value range should go before wider ones.
|
||||
}
|
19
vendor/github.com/go-critic/go-critic/checkers/checkers.go
сгенерированный
поставляемый
Normal file
19
vendor/github.com/go-critic/go-critic/checkers/checkers.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,19 @@
|
|||
// Package checkers is a gocritic linter main checkers collection.
|
||||
package checkers
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
var collection = &linter.CheckerCollection{
|
||||
URL: "https://github.com/go-critic/go-critic/checkers",
|
||||
}
|
||||
|
||||
var debug = func() func() bool {
|
||||
v := os.Getenv("DEBUG") != ""
|
||||
return func() bool {
|
||||
return v
|
||||
}
|
||||
}()
|
61
vendor/github.com/go-critic/go-critic/checkers/codegenComment_checker.go
сгенерированный
поставляемый
Normal file
61
vendor/github.com/go-critic/go-critic/checkers/codegenComment_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,61 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "codegenComment"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects malformed 'code generated' file comments"
|
||||
info.Before = `// This file was automatically generated by foogen`
|
||||
info.After = `// Code generated by foogen. DO NOT EDIT.`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
patterns := []string{
|
||||
"this (?:file|code) (?:was|is) auto(?:matically)? generated",
|
||||
"this (?:file|code) (?:was|is) generated automatically",
|
||||
"this (?:file|code) (?:was|is) generated by",
|
||||
"this (?:file|code) (?:was|is) (?:auto(?:matically)? )?generated",
|
||||
"this (?:file|code) (?:was|is) generated",
|
||||
"code in this file (?:was|is) auto(?:matically)? generated",
|
||||
"generated (?:file|code) - do not edit",
|
||||
// TODO(Quasilyte): more of these.
|
||||
}
|
||||
re := regexp.MustCompile("(?i)" + strings.Join(patterns, "|"))
|
||||
return &codegenCommentChecker{
|
||||
ctx: ctx,
|
||||
badCommentRE: re,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type codegenCommentChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
badCommentRE *regexp.Regexp
|
||||
}
|
||||
|
||||
func (c *codegenCommentChecker) WalkFile(f *ast.File) {
|
||||
if f.Doc == nil {
|
||||
return
|
||||
}
|
||||
|
||||
for _, comment := range f.Doc.List {
|
||||
if c.badCommentRE.MatchString(comment.Text) {
|
||||
c.warn(comment)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *codegenCommentChecker) warn(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "comment should match `Code generated .* DO NOT EDIT.` regexp")
|
||||
}
|
79
vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go
сгенерированный
поставляемый
Normal file
79
vendor/github.com/go-critic/go-critic/checkers/commentFormatting_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,79 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "commentFormatting"
|
||||
info.Tags = []string{"style"}
|
||||
info.Summary = "Detects comments with non-idiomatic formatting"
|
||||
info.Before = `//This is a comment`
|
||||
info.After = `// This is a comment`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
parts := []string{
|
||||
`^//go:generate .*$`, // e.g.: go:generate value
|
||||
`^//\w+:.*$`, // e.g.: key: value
|
||||
`^//nolint$`, // e.g.: nolint
|
||||
`^//line /.*:\d+`, // e.g.: line /path/to/file:123
|
||||
`^//export \w+$`, // e.g.: export Foo
|
||||
}
|
||||
pat := "(?m)" + strings.Join(parts, "|")
|
||||
pragmaRE := regexp.MustCompile(pat)
|
||||
return astwalk.WalkerForComment(&commentFormattingChecker{
|
||||
ctx: ctx,
|
||||
pragmaRE: pragmaRE,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
type commentFormattingChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
pragmaRE *regexp.Regexp
|
||||
}
|
||||
|
||||
func (c *commentFormattingChecker) VisitComment(cg *ast.CommentGroup) {
|
||||
if strings.HasPrefix(cg.List[0].Text, "/*") {
|
||||
return
|
||||
}
|
||||
for _, comment := range cg.List {
|
||||
if len(comment.Text) <= len("// ") {
|
||||
continue
|
||||
}
|
||||
if c.pragmaRE.MatchString(comment.Text) {
|
||||
continue
|
||||
}
|
||||
|
||||
// Make a decision based on a first comment text rune.
|
||||
r, _ := utf8.DecodeRuneInString(comment.Text[len("//"):])
|
||||
if !c.specialChar(r) && !unicode.IsSpace(r) {
|
||||
c.warn(cg)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *commentFormattingChecker) specialChar(r rune) bool {
|
||||
// Permitted list to avoid false-positives.
|
||||
switch r {
|
||||
case '+', '-', '#', '!':
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *commentFormattingChecker) warn(cg *ast.CommentGroup) {
|
||||
c.ctx.Warn(cg, "put a space between `//` and comment text")
|
||||
}
|
157
vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go
сгенерированный
поставляемый
Normal file
157
vendor/github.com/go-critic/go-critic/checkers/commentedOutCode_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,157 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/strparse"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "commentedOutCode"
|
||||
info.Tags = []string{"diagnostic", "experimental"}
|
||||
info.Summary = "Detects commented-out code inside function bodies"
|
||||
info.Before = `
|
||||
// fmt.Println("Debugging hard")
|
||||
foo(1, 2)`
|
||||
info.After = `foo(1, 2)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForLocalComment(&commentedOutCodeChecker{
|
||||
ctx: ctx,
|
||||
notQuiteFuncCall: regexp.MustCompile(`\w+\s+\([^)]*\)\s*$`),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
type commentedOutCodeChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
fn *ast.FuncDecl
|
||||
|
||||
notQuiteFuncCall *regexp.Regexp
|
||||
}
|
||||
|
||||
func (c *commentedOutCodeChecker) EnterFunc(fn *ast.FuncDecl) bool {
|
||||
c.fn = fn // Need to store current function inside checker context
|
||||
return fn.Body != nil
|
||||
}
|
||||
|
||||
func (c *commentedOutCodeChecker) VisitLocalComment(cg *ast.CommentGroup) {
|
||||
s := cg.Text() // Collect text once
|
||||
|
||||
// We do multiple heuristics to avoid false positives.
|
||||
// Many things can be improved here.
|
||||
|
||||
markers := []string{
|
||||
"TODO", // TODO comments with code are permitted.
|
||||
|
||||
// "http://" is interpreted as a label with comment.
|
||||
// There are other protocols we might want to include.
|
||||
"http://",
|
||||
"https://",
|
||||
|
||||
"e.g. ", // Clearly not a "selector expr" (mostly due to extra space)
|
||||
}
|
||||
for _, m := range markers {
|
||||
if strings.Contains(s, m) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Some very short comment that can be skipped.
|
||||
// Usually triggering on these results in false positive.
|
||||
// Unless there is a very popular call like print/println.
|
||||
cond := len(s) < len("quite too short") &&
|
||||
!strings.Contains(s, "print") &&
|
||||
!strings.Contains(s, "fmt.") &&
|
||||
!strings.Contains(s, "log.")
|
||||
if cond {
|
||||
return
|
||||
}
|
||||
|
||||
// Almost looks like a commented-out function call,
|
||||
// but there is a whitespace between function name and
|
||||
// parameters list. Skip these to avoid false positives.
|
||||
if c.notQuiteFuncCall.MatchString(s) {
|
||||
return
|
||||
}
|
||||
|
||||
stmt := strparse.Stmt(s)
|
||||
|
||||
if c.isPermittedStmt(stmt) {
|
||||
return
|
||||
}
|
||||
|
||||
if stmt != strparse.BadStmt {
|
||||
c.warn(cg)
|
||||
return
|
||||
}
|
||||
|
||||
// Don't try to parse one-liner as block statement
|
||||
if len(cg.List) == 1 && !strings.Contains(s, "\n") {
|
||||
return
|
||||
}
|
||||
|
||||
// Some attempts to avoid false positives.
|
||||
if c.skipBlock(s) {
|
||||
return
|
||||
}
|
||||
|
||||
// Add braces to make block statement from
|
||||
// multiple statements.
|
||||
stmt = strparse.Stmt(fmt.Sprintf("{ %s }", s))
|
||||
|
||||
if stmt, ok := stmt.(*ast.BlockStmt); ok && len(stmt.List) != 0 {
|
||||
c.warn(cg)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *commentedOutCodeChecker) skipBlock(s string) bool {
|
||||
lines := strings.Split(s, "\n") // There is at least 1 line, that's invariant
|
||||
|
||||
// Special example test block.
|
||||
if isExampleTestFunc(c.fn) && strings.Contains(lines[0], "Output:") {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *commentedOutCodeChecker) isPermittedStmt(stmt ast.Stmt) bool {
|
||||
switch stmt := stmt.(type) {
|
||||
case *ast.ExprStmt:
|
||||
return c.isPermittedExpr(stmt.X)
|
||||
case *ast.LabeledStmt:
|
||||
return c.isPermittedStmt(stmt.Stmt)
|
||||
case *ast.DeclStmt:
|
||||
decl := stmt.Decl.(*ast.GenDecl)
|
||||
return decl.Tok == token.TYPE
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *commentedOutCodeChecker) isPermittedExpr(x ast.Expr) bool {
|
||||
// Permit anything except expressions that can be used
|
||||
// with complete result discarding.
|
||||
switch x := x.(type) {
|
||||
case *ast.CallExpr:
|
||||
return false
|
||||
case *ast.UnaryExpr:
|
||||
// "<-" channel receive is not permitted.
|
||||
return x.Op != token.ARROW
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (c *commentedOutCodeChecker) warn(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "may want to remove commented-out code")
|
||||
}
|
76
vendor/github.com/go-critic/go-critic/checkers/commentedOutImport_checker.go
сгенерированный
поставляемый
Normal file
76
vendor/github.com/go-critic/go-critic/checkers/commentedOutImport_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,76 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"regexp"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "commentedOutImport"
|
||||
info.Tags = []string{"style", "experimental"}
|
||||
info.Summary = "Detects commented-out imports"
|
||||
info.Before = `
|
||||
import (
|
||||
"fmt"
|
||||
//"os"
|
||||
)`
|
||||
info.After = `
|
||||
import (
|
||||
"fmt"
|
||||
)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
const pattern = `(?m)^(?://|/\*)?\s*"([a-zA-Z0-9_/]+)"\s*(?:\*/)?$`
|
||||
return &commentedOutImportChecker{
|
||||
ctx: ctx,
|
||||
importStringRE: regexp.MustCompile(pattern),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
type commentedOutImportChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
importStringRE *regexp.Regexp
|
||||
}
|
||||
|
||||
func (c *commentedOutImportChecker) WalkFile(f *ast.File) {
|
||||
// TODO(Quasilyte): handle commented-out import spec,
|
||||
// for example: // import "errors".
|
||||
|
||||
for _, decl := range f.Decls {
|
||||
decl, ok := decl.(*ast.GenDecl)
|
||||
if !ok || decl.Tok != token.IMPORT {
|
||||
// Import decls can only be in the beginning of the file.
|
||||
// If we've met some other decl, there will be no more
|
||||
// import decls.
|
||||
break
|
||||
}
|
||||
|
||||
// Find comments inside this import decl span.
|
||||
for _, cg := range f.Comments {
|
||||
if cg.Pos() > decl.Rparen {
|
||||
break // Below the decl, stop.
|
||||
}
|
||||
if cg.Pos() < decl.Lparen {
|
||||
continue // Before the decl, skip.
|
||||
}
|
||||
|
||||
for _, comment := range cg.List {
|
||||
for _, m := range c.importStringRE.FindAllStringSubmatch(comment.Text, -1) {
|
||||
c.warn(comment, m[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *commentedOutImportChecker) warn(cause ast.Node, path string) {
|
||||
c.ctx.Warn(cause, "remove commented-out %q import", path)
|
||||
}
|
65
vendor/github.com/go-critic/go-critic/checkers/defaultCaseOrder_checker.go
сгенерированный
поставляемый
Normal file
65
vendor/github.com/go-critic/go-critic/checkers/defaultCaseOrder_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,65 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "defaultCaseOrder"
|
||||
info.Tags = []string{"style"}
|
||||
info.Summary = "Detects when default case in switch isn't on 1st or last position"
|
||||
info.Before = `
|
||||
switch {
|
||||
case x > y:
|
||||
// ...
|
||||
default: // <- not the best position
|
||||
// ...
|
||||
case x == 10:
|
||||
// ...
|
||||
}`
|
||||
info.After = `
|
||||
switch {
|
||||
case x > y:
|
||||
// ...
|
||||
case x == 10:
|
||||
// ...
|
||||
default: // <- last case (could also be the first one)
|
||||
// ...
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&defaultCaseOrderChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type defaultCaseOrderChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *defaultCaseOrderChecker) VisitStmt(stmt ast.Stmt) {
|
||||
swtch, ok := stmt.(*ast.SwitchStmt)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
for i, stmt := range swtch.Body.List {
|
||||
caseStmt, ok := stmt.(*ast.CaseClause)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
// is `default` case
|
||||
if caseStmt.List == nil {
|
||||
if i != 0 && i != len(swtch.Body.List)-1 {
|
||||
c.warn(caseStmt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *defaultCaseOrderChecker) warn(cause *ast.CaseClause) {
|
||||
c.ctx.Warn(cause, "consider to make `default` case as first or as last case")
|
||||
}
|
94
vendor/github.com/go-critic/go-critic/checkers/deferUnlambda_checker.go
сгенерированный
поставляемый
Normal file
94
vendor/github.com/go-critic/go-critic/checkers/deferUnlambda_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,94 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/types"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "deferUnlambda"
|
||||
info.Tags = []string{"style", "experimental"}
|
||||
info.Summary = "Detects deferred function literals that can be simplified"
|
||||
info.Before = `defer func() { f() }()`
|
||||
info.After = `f()`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&deferUnlambdaChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type deferUnlambdaChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *deferUnlambdaChecker) VisitStmt(x ast.Stmt) {
|
||||
def, ok := x.(*ast.DeferStmt)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// We don't analyze deferred function args.
|
||||
// Most deferred calls don't have them, so it's not a big deal to skip them.
|
||||
if len(def.Call.Args) != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
fn, ok := def.Call.Fun.(*ast.FuncLit)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if len(fn.Body.List) != 1 {
|
||||
return
|
||||
}
|
||||
|
||||
call, ok := astcast.ToExprStmt(fn.Body.List[0]).X.(*ast.CallExpr)
|
||||
if !ok || !c.isFunctionCall(call) {
|
||||
return
|
||||
}
|
||||
|
||||
// Skip recover() as it can't be moved outside of the lambda.
|
||||
// Skip panic() to avoid affecting the stack trace.
|
||||
switch qualifiedName(call.Fun) {
|
||||
case "recover", "panic":
|
||||
return
|
||||
}
|
||||
|
||||
for _, arg := range call.Args {
|
||||
if !c.isConstExpr(arg) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.warn(def, call)
|
||||
}
|
||||
|
||||
func (c *deferUnlambdaChecker) isFunctionCall(e *ast.CallExpr) bool {
|
||||
switch fnExpr := e.Fun.(type) {
|
||||
case *ast.Ident:
|
||||
return true
|
||||
case *ast.SelectorExpr:
|
||||
x, ok := fnExpr.X.(*ast.Ident)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
_, ok = c.ctx.TypesInfo.ObjectOf(x).(*types.PkgName)
|
||||
return ok
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *deferUnlambdaChecker) isConstExpr(e ast.Expr) bool {
|
||||
return c.ctx.TypesInfo.Types[e].Value != nil
|
||||
}
|
||||
|
||||
func (c *deferUnlambdaChecker) warn(cause, suggestion ast.Node) {
|
||||
c.ctx.Warn(cause, "can rewrite as `defer %s`", suggestion)
|
||||
}
|
149
vendor/github.com/go-critic/go-critic/checkers/deprecatedComment_checker.go
сгенерированный
поставляемый
Normal file
149
vendor/github.com/go-critic/go-critic/checkers/deprecatedComment_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,149 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "deprecatedComment"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects malformed 'deprecated' doc-comments"
|
||||
info.Before = `
|
||||
// deprecated, use FuncNew instead
|
||||
func FuncOld() int`
|
||||
info.After = `
|
||||
// Deprecated: use FuncNew instead
|
||||
func FuncOld() int`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
c := &deprecatedCommentChecker{ctx: ctx}
|
||||
|
||||
c.commonPatterns = []*regexp.Regexp{
|
||||
regexp.MustCompile(`(?i)this (?:function|type) is deprecated`),
|
||||
regexp.MustCompile(`(?i)deprecated[.!]? use \S* instead`),
|
||||
regexp.MustCompile(`(?i)\[\[deprecated\]\].*`),
|
||||
regexp.MustCompile(`(?i)note: deprecated\b.*`),
|
||||
regexp.MustCompile(`(?i)deprecated in.*`),
|
||||
// TODO(quasilyte): more of these?
|
||||
}
|
||||
|
||||
// TODO(quasilyte): may want to generate this list programmatically.
|
||||
//
|
||||
// TODO(quasilyte): currently it only handles a single missing letter.
|
||||
// Might want to handle other kinds of common misspell/typo kinds.
|
||||
c.commonTypos = []string{
|
||||
"Dprecated: ",
|
||||
"Derecated: ",
|
||||
"Depecated: ",
|
||||
"Deprcated: ",
|
||||
"Depreated: ",
|
||||
"Deprected: ",
|
||||
"Deprecaed: ",
|
||||
"Deprecatd: ",
|
||||
"Deprecate: ",
|
||||
"Derpecate: ",
|
||||
"Derpecated: ",
|
||||
"Depreacted: ",
|
||||
}
|
||||
for i := range c.commonTypos {
|
||||
c.commonTypos[i] = strings.ToUpper(c.commonTypos[i])
|
||||
}
|
||||
|
||||
return astwalk.WalkerForDocComment(c)
|
||||
})
|
||||
}
|
||||
|
||||
type deprecatedCommentChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
commonPatterns []*regexp.Regexp
|
||||
commonTypos []string
|
||||
}
|
||||
|
||||
func (c *deprecatedCommentChecker) VisitDocComment(doc *ast.CommentGroup) {
|
||||
// There are 3 accepted forms of deprecation comments:
|
||||
//
|
||||
// 1. inline, that can't be handled with a DocCommentVisitor.
|
||||
// Note that "Deprecated: " may not even be the comment prefix there.
|
||||
// Example: "The line number in the input. Deprecated: Kept for compatibility."
|
||||
// TODO(quasilyte): fix it.
|
||||
//
|
||||
// 2. Longer form-1. It's a doc-comment that only contains "deprecation" notice.
|
||||
//
|
||||
// 3. Like form-2, but may also include doc-comment text.
|
||||
// Distinguished by an empty line.
|
||||
//
|
||||
// See https://github.com/golang/go/issues/10909#issuecomment-136492606.
|
||||
//
|
||||
// It's desirable to see how people make mistakes with the format,
|
||||
// this is why there is currently no special treatment for these cases.
|
||||
// TODO(quasilyte): do more audits and grow the negative tests suite.
|
||||
//
|
||||
// TODO(quasilyte): there are also multi-line deprecation comments.
|
||||
|
||||
for _, comment := range doc.List {
|
||||
if strings.HasPrefix(comment.Text, "/*") {
|
||||
// TODO(quasilyte): handle multi-line doc comments.
|
||||
continue
|
||||
}
|
||||
l := comment.Text[len("//"):]
|
||||
if len(l) < len("Deprecated: ") {
|
||||
continue
|
||||
}
|
||||
l = strings.TrimSpace(l)
|
||||
|
||||
// Check whether someone messed up with a prefix casing.
|
||||
upcase := strings.ToUpper(l)
|
||||
if strings.HasPrefix(upcase, "DEPRECATED: ") && !strings.HasPrefix(l, "Deprecated: ") {
|
||||
c.warnCasing(comment, l)
|
||||
return
|
||||
}
|
||||
|
||||
// Check is someone used comma instead of a colon.
|
||||
if strings.HasPrefix(l, "Deprecated, ") {
|
||||
c.warnComma(comment)
|
||||
return
|
||||
}
|
||||
|
||||
// Check for other commonly used patterns.
|
||||
for _, pat := range c.commonPatterns {
|
||||
if pat.MatchString(l) {
|
||||
c.warnPattern(comment)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Detect some simple typos.
|
||||
for _, prefixWithTypo := range c.commonTypos {
|
||||
if strings.HasPrefix(upcase, prefixWithTypo) {
|
||||
c.warnTypo(comment, l)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *deprecatedCommentChecker) warnCasing(cause ast.Node, line string) {
|
||||
prefix := line[:len("DEPRECATED: ")]
|
||||
c.ctx.Warn(cause, "use `Deprecated: ` (note the casing) instead of `%s`", prefix)
|
||||
}
|
||||
|
||||
func (c *deprecatedCommentChecker) warnPattern(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "the proper format is `Deprecated: <text>`")
|
||||
}
|
||||
|
||||
func (c *deprecatedCommentChecker) warnComma(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "use `:` instead of `,` in `Deprecated, `")
|
||||
}
|
||||
|
||||
func (c *deprecatedCommentChecker) warnTypo(cause ast.Node, line string) {
|
||||
word := strings.Split(line, ":")[0]
|
||||
c.ctx.Warn(cause, "typo in `%s`; should be `Deprecated`", word)
|
||||
}
|
95
vendor/github.com/go-critic/go-critic/checkers/docStub_checker.go
сгенерированный
поставляемый
Normal file
95
vendor/github.com/go-critic/go-critic/checkers/docStub_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,95 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "docStub"
|
||||
info.Tags = []string{"style", "experimental"}
|
||||
info.Summary = "Detects comments that silence go lint complaints about doc-comment"
|
||||
info.Before = `
|
||||
// Foo ...
|
||||
func Foo() {
|
||||
}`
|
||||
info.After = `
|
||||
// (A) - remove the doc-comment stub
|
||||
func Foo() {}
|
||||
// (B) - replace it with meaningful comment
|
||||
// Foo is a demonstration-only function.
|
||||
func Foo() {}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
re := `(?i)^\.\.\.$|^\.$|^xxx\.?$|^whatever\.?$`
|
||||
c := &docStubChecker{
|
||||
ctx: ctx,
|
||||
stubCommentRE: regexp.MustCompile(re),
|
||||
}
|
||||
return c
|
||||
})
|
||||
}
|
||||
|
||||
type docStubChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
stubCommentRE *regexp.Regexp
|
||||
}
|
||||
|
||||
func (c *docStubChecker) WalkFile(f *ast.File) {
|
||||
for _, decl := range f.Decls {
|
||||
switch decl := decl.(type) {
|
||||
case *ast.FuncDecl:
|
||||
c.visitDoc(decl, decl.Name, decl.Doc, false)
|
||||
case *ast.GenDecl:
|
||||
if decl.Tok != token.TYPE {
|
||||
continue
|
||||
}
|
||||
if len(decl.Specs) == 1 {
|
||||
spec := decl.Specs[0].(*ast.TypeSpec)
|
||||
// Only 1 spec, use doc from the decl itself.
|
||||
c.visitDoc(spec, spec.Name, decl.Doc, true)
|
||||
}
|
||||
// N specs, use per-spec doc.
|
||||
for _, spec := range decl.Specs {
|
||||
spec := spec.(*ast.TypeSpec)
|
||||
c.visitDoc(spec, spec.Name, spec.Doc, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *docStubChecker) visitDoc(decl ast.Node, sym *ast.Ident, doc *ast.CommentGroup, article bool) {
|
||||
if !sym.IsExported() || doc == nil {
|
||||
return
|
||||
}
|
||||
line := strings.TrimSpace(doc.List[0].Text[len("//"):])
|
||||
if article {
|
||||
// Skip optional article.
|
||||
for _, a := range []string{"The ", "An ", "A "} {
|
||||
if strings.HasPrefix(line, a) {
|
||||
line = line[len(a):]
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if !strings.HasPrefix(line, sym.Name) {
|
||||
return
|
||||
}
|
||||
line = strings.TrimSpace(line[len(sym.Name):])
|
||||
// Now try to detect the "stub" part.
|
||||
if c.stubCommentRE.MatchString(line) {
|
||||
c.warn(decl)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *docStubChecker) warn(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "silencing go lint doc-comment warnings is unadvised")
|
||||
}
|
133
vendor/github.com/go-critic/go-critic/checkers/dupArg_checker.go
сгенерированный
поставляемый
Normal file
133
vendor/github.com/go-critic/go-critic/checkers/dupArg_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,133 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/types"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "dupArg"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects suspicious duplicated arguments"
|
||||
info.Before = `copy(dst, dst)`
|
||||
info.After = `copy(dst, src)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
c := &dupArgChecker{ctx: ctx}
|
||||
// newMatcherFunc returns a function that matches a call if
|
||||
// args[xIndex] and args[yIndex] are equal.
|
||||
newMatcherFunc := func(xIndex, yIndex int) func(*ast.CallExpr) bool {
|
||||
return func(call *ast.CallExpr) bool {
|
||||
if len(call.Args) <= xIndex || len(call.Args) <= yIndex {
|
||||
return false
|
||||
}
|
||||
x := call.Args[xIndex]
|
||||
y := call.Args[yIndex]
|
||||
return astequal.Expr(x, y)
|
||||
}
|
||||
}
|
||||
|
||||
// m maps pattern string to a matching function.
|
||||
// String patterns are used for documentation purposes (readability).
|
||||
m := map[string]func(*ast.CallExpr) bool{
|
||||
"(x, x, ...)": newMatcherFunc(0, 1),
|
||||
"(x, _, x, ...)": newMatcherFunc(0, 2),
|
||||
"(_, x, x, ...)": newMatcherFunc(1, 2),
|
||||
}
|
||||
|
||||
// TODO(quasilyte): handle x.Equal(x) cases.
|
||||
// Example: *math/Big.Int.Cmp method.
|
||||
|
||||
// TODO(quasilyte): more perky mode that will also
|
||||
// report things like io.Copy(x, x).
|
||||
// Probably safe thing to do even without that option
|
||||
// if `x` is not interface (requires type checks
|
||||
// that are not incorporated into this checker yet).
|
||||
|
||||
c.matchers = map[string]func(*ast.CallExpr) bool{
|
||||
"copy": m["(x, x, ...)"],
|
||||
|
||||
"math.Max": m["(x, x, ...)"],
|
||||
"math.Min": m["(x, x, ...)"],
|
||||
|
||||
"reflect.Copy": m["(x, x, ...)"],
|
||||
"reflect.DeepEqual": m["(x, x, ...)"],
|
||||
|
||||
"strings.Contains": m["(x, x, ...)"],
|
||||
"strings.Compare": m["(x, x, ...)"],
|
||||
"strings.EqualFold": m["(x, x, ...)"],
|
||||
"strings.HasPrefix": m["(x, x, ...)"],
|
||||
"strings.HasSuffix": m["(x, x, ...)"],
|
||||
"strings.Index": m["(x, x, ...)"],
|
||||
"strings.LastIndex": m["(x, x, ...)"],
|
||||
"strings.Split": m["(x, x, ...)"],
|
||||
"strings.SplitAfter": m["(x, x, ...)"],
|
||||
"strings.SplitAfterN": m["(x, x, ...)"],
|
||||
"strings.SplitN": m["(x, x, ...)"],
|
||||
"strings.Replace": m["(_, x, x, ...)"],
|
||||
"strings.ReplaceAll": m["(_, x, x, ...)"],
|
||||
|
||||
"bytes.Contains": m["(x, x, ...)"],
|
||||
"bytes.Compare": m["(x, x, ...)"],
|
||||
"bytes.Equal": m["(x, x, ...)"],
|
||||
"bytes.EqualFold": m["(x, x, ...)"],
|
||||
"bytes.HasPrefix": m["(x, x, ...)"],
|
||||
"bytes.HasSuffix": m["(x, x, ...)"],
|
||||
"bytes.Index": m["(x, x, ...)"],
|
||||
"bytes.LastIndex": m["(x, x, ...)"],
|
||||
"bytes.Split": m["(x, x, ...)"],
|
||||
"bytes.SplitAfter": m["(x, x, ...)"],
|
||||
"bytes.SplitAfterN": m["(x, x, ...)"],
|
||||
"bytes.SplitN": m["(x, x, ...)"],
|
||||
"bytes.Replace": m["(_, x, x, ...)"],
|
||||
"bytes.ReplaceAll": m["(_, x, x, ...)"],
|
||||
|
||||
"types.Identical": m["(x, x, ...)"],
|
||||
"types.IdenticalIgnoreTags": m["(x, x, ...)"],
|
||||
|
||||
"draw.Draw": m["(x, _, x, ...)"],
|
||||
|
||||
// TODO(quasilyte): more of these.
|
||||
}
|
||||
return astwalk.WalkerForExpr(c)
|
||||
})
|
||||
}
|
||||
|
||||
type dupArgChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
matchers map[string]func(*ast.CallExpr) bool
|
||||
}
|
||||
|
||||
func (c *dupArgChecker) VisitExpr(expr ast.Expr) {
|
||||
call, ok := expr.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO(quasilyte): this kind of check is needed in multiple
|
||||
// places and the code is somewhat duplicated around.
|
||||
// We probably need to stop using qualifiedName for non-experimental checkers.
|
||||
if calledExpr, ok := call.Fun.(*ast.SelectorExpr); ok {
|
||||
obj, ok := c.ctx.TypesInfo.ObjectOf(astcast.ToIdent(calledExpr.X)).(*types.PkgName)
|
||||
if !ok || !isStdlibPkg(obj.Imported()) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
m := c.matchers[qualifiedName(call.Fun)]
|
||||
if m != nil && m(call) {
|
||||
c.warn(call)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dupArgChecker) warn(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "suspicious duplicated args in `%s`", cause)
|
||||
}
|
58
vendor/github.com/go-critic/go-critic/checkers/dupBranchBody_checker.go
сгенерированный
поставляемый
Normal file
58
vendor/github.com/go-critic/go-critic/checkers/dupBranchBody_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,58 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "dupBranchBody"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects duplicated branch bodies inside conditional statements"
|
||||
info.Before = `
|
||||
if cond {
|
||||
println("cond=true")
|
||||
} else {
|
||||
println("cond=true")
|
||||
}`
|
||||
info.After = `
|
||||
if cond {
|
||||
println("cond=true")
|
||||
} else {
|
||||
println("cond=false")
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&dupBranchBodyChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type dupBranchBodyChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *dupBranchBodyChecker) VisitStmt(stmt ast.Stmt) {
|
||||
// TODO(quasilyte): extend to check switch statements as well.
|
||||
// Should be very careful with type switches.
|
||||
|
||||
if stmt, ok := stmt.(*ast.IfStmt); ok {
|
||||
c.checkIf(stmt)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dupBranchBodyChecker) checkIf(stmt *ast.IfStmt) {
|
||||
thenBody := stmt.Body
|
||||
elseBody, ok := stmt.Else.(*ast.BlockStmt)
|
||||
if ok && astequal.Stmt(thenBody, elseBody) {
|
||||
c.warnIf(stmt)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dupBranchBodyChecker) warnIf(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "both branches in if statement has same body")
|
||||
}
|
57
vendor/github.com/go-critic/go-critic/checkers/dupCase_checker.go
сгенерированный
поставляемый
Normal file
57
vendor/github.com/go-critic/go-critic/checkers/dupCase_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,57 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/checkers/internal/lintutil"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "dupCase"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects duplicated case clauses inside switch statements"
|
||||
info.Before = `
|
||||
switch x {
|
||||
case ys[0], ys[1], ys[2], ys[0], ys[4]:
|
||||
}`
|
||||
info.After = `
|
||||
switch x {
|
||||
case ys[0], ys[1], ys[2], ys[3], ys[4]:
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&dupCaseChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type dupCaseChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
astSet lintutil.AstSet
|
||||
}
|
||||
|
||||
func (c *dupCaseChecker) VisitStmt(stmt ast.Stmt) {
|
||||
if stmt, ok := stmt.(*ast.SwitchStmt); ok {
|
||||
c.checkSwitch(stmt)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dupCaseChecker) checkSwitch(stmt *ast.SwitchStmt) {
|
||||
c.astSet.Clear()
|
||||
for i := range stmt.Body.List {
|
||||
cc := stmt.Body.List[i].(*ast.CaseClause)
|
||||
for _, x := range cc.List {
|
||||
if !c.astSet.Insert(x) {
|
||||
c.warn(x)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dupCaseChecker) warn(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "'case %s' is duplicated", cause)
|
||||
}
|
63
vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go
сгенерированный
поставляемый
Normal file
63
vendor/github.com/go-critic/go-critic/checkers/dupImports_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,63 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "dupImport"
|
||||
info.Tags = []string{"style", "experimental"}
|
||||
info.Summary = "Detects multiple imports of the same package under different aliases"
|
||||
info.Before = `
|
||||
import (
|
||||
"fmt"
|
||||
priting "fmt" // Imported the second time
|
||||
)`
|
||||
info.After = `
|
||||
import(
|
||||
"fmt"
|
||||
)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return &dupImportChecker{ctx: ctx}
|
||||
})
|
||||
}
|
||||
|
||||
type dupImportChecker struct {
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *dupImportChecker) WalkFile(f *ast.File) {
|
||||
imports := make(map[string][]*ast.ImportSpec)
|
||||
for _, importDcl := range f.Imports {
|
||||
pkg := importDcl.Path.Value
|
||||
imports[pkg] = append(imports[pkg], importDcl)
|
||||
}
|
||||
|
||||
for _, importList := range imports {
|
||||
if len(importList) == 1 {
|
||||
continue
|
||||
}
|
||||
c.warn(importList)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dupImportChecker) warn(importList []*ast.ImportSpec) {
|
||||
msg := fmt.Sprintf("package is imported %d times under different aliases on lines", len(importList))
|
||||
for idx, importDcl := range importList {
|
||||
switch {
|
||||
case idx == len(importList)-1:
|
||||
msg += " and"
|
||||
case idx > 0:
|
||||
msg += ","
|
||||
}
|
||||
msg += fmt.Sprintf(" %d", c.ctx.FileSet.Position(importDcl.Pos()).Line)
|
||||
}
|
||||
for _, importDcl := range importList {
|
||||
c.ctx.Warn(importDcl, msg)
|
||||
}
|
||||
}
|
102
vendor/github.com/go-critic/go-critic/checkers/dupSubExpr_checker.go
сгенерированный
поставляемый
Normal file
102
vendor/github.com/go-critic/go-critic/checkers/dupSubExpr_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,102 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"go/types"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
"github.com/go-toolsmith/typep"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "dupSubExpr"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects suspicious duplicated sub-expressions"
|
||||
info.Before = `
|
||||
sort.Slice(xs, func(i, j int) bool {
|
||||
return xs[i].v < xs[i].v // Duplicated index
|
||||
})`
|
||||
info.After = `
|
||||
sort.Slice(xs, func(i, j int) bool {
|
||||
return xs[i].v < xs[j].v
|
||||
})`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
c := &dupSubExprChecker{ctx: ctx}
|
||||
|
||||
ops := []struct {
|
||||
op token.Token
|
||||
float bool // Whether float args require special care
|
||||
}{
|
||||
{op: token.LOR}, // x || x
|
||||
{op: token.LAND}, // x && x
|
||||
{op: token.OR}, // x | x
|
||||
{op: token.AND}, // x & x
|
||||
{op: token.XOR}, // x ^ x
|
||||
{op: token.LSS}, // x < x
|
||||
{op: token.GTR}, // x > x
|
||||
{op: token.AND_NOT}, // x &^ x
|
||||
{op: token.REM}, // x % x
|
||||
|
||||
{op: token.EQL, float: true}, // x == x
|
||||
{op: token.NEQ, float: true}, // x != x
|
||||
{op: token.LEQ, float: true}, // x <= x
|
||||
{op: token.GEQ, float: true}, // x >= x
|
||||
{op: token.QUO, float: true}, // x / x
|
||||
{op: token.SUB, float: true}, // x - x
|
||||
}
|
||||
|
||||
c.opSet = make(map[token.Token]bool)
|
||||
c.floatOpsSet = make(map[token.Token]bool)
|
||||
for _, opInfo := range ops {
|
||||
c.opSet[opInfo.op] = true
|
||||
if opInfo.float {
|
||||
c.floatOpsSet[opInfo.op] = true
|
||||
}
|
||||
}
|
||||
|
||||
return astwalk.WalkerForExpr(c)
|
||||
})
|
||||
}
|
||||
|
||||
type dupSubExprChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
// opSet is a set of binary operations that do not make
|
||||
// sense with duplicated (same) RHS and LHS.
|
||||
opSet map[token.Token]bool
|
||||
|
||||
floatOpsSet map[token.Token]bool
|
||||
}
|
||||
|
||||
func (c *dupSubExprChecker) VisitExpr(expr ast.Expr) {
|
||||
if expr, ok := expr.(*ast.BinaryExpr); ok {
|
||||
c.checkBinaryExpr(expr)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dupSubExprChecker) checkBinaryExpr(expr *ast.BinaryExpr) {
|
||||
if !c.opSet[expr.Op] {
|
||||
return
|
||||
}
|
||||
if c.resultIsFloat(expr.X) && c.floatOpsSet[expr.Op] {
|
||||
return
|
||||
}
|
||||
if typep.SideEffectFree(c.ctx.TypesInfo, expr) && c.opSet[expr.Op] && astequal.Expr(expr.X, expr.Y) {
|
||||
c.warn(expr)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *dupSubExprChecker) resultIsFloat(expr ast.Expr) bool {
|
||||
typ, ok := c.ctx.TypesInfo.TypeOf(expr).(*types.Basic)
|
||||
return ok && typ.Info()&types.IsFloat != 0
|
||||
}
|
||||
|
||||
func (c *dupSubExprChecker) warn(cause *ast.BinaryExpr) {
|
||||
c.ctx.Warn(cause, "suspicious identical LHS and RHS for `%s` operator", cause.Op)
|
||||
}
|
71
vendor/github.com/go-critic/go-critic/checkers/elseif_checker.go
сгенерированный
поставляемый
Normal file
71
vendor/github.com/go-critic/go-critic/checkers/elseif_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,71 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astp"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "elseif"
|
||||
info.Tags = []string{"style"}
|
||||
info.Params = linter.CheckerParams{
|
||||
"skipBalanced": {
|
||||
Value: true,
|
||||
Usage: "whether to skip balanced if-else pairs",
|
||||
},
|
||||
}
|
||||
info.Summary = "Detects else with nested if statement that can be replaced with else-if"
|
||||
info.Before = `
|
||||
if cond1 {
|
||||
} else {
|
||||
if x := cond2; x {
|
||||
}
|
||||
}`
|
||||
info.After = `
|
||||
if cond1 {
|
||||
} else if x := cond2; x {
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
c := &elseifChecker{ctx: ctx}
|
||||
c.skipBalanced = info.Params.Bool("skipBalanced")
|
||||
return astwalk.WalkerForStmt(c)
|
||||
})
|
||||
}
|
||||
|
||||
type elseifChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
skipBalanced bool
|
||||
}
|
||||
|
||||
func (c *elseifChecker) VisitStmt(stmt ast.Stmt) {
|
||||
if stmt, ok := stmt.(*ast.IfStmt); ok {
|
||||
elseBody, ok := stmt.Else.(*ast.BlockStmt)
|
||||
if !ok || len(elseBody.List) != 1 {
|
||||
return
|
||||
}
|
||||
innerIfStmt, ok := elseBody.List[0].(*ast.IfStmt)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
balanced := len(stmt.Body.List) == 1 &&
|
||||
astp.IsIfStmt(stmt.Body.List[0])
|
||||
if balanced && c.skipBalanced {
|
||||
return // Configured to skip balanced statements
|
||||
}
|
||||
if innerIfStmt.Else != nil {
|
||||
return
|
||||
}
|
||||
c.warn(stmt.Else)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *elseifChecker) warn(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "can replace 'else {if cond {}}' with 'else if cond {}'")
|
||||
}
|
70
vendor/github.com/go-critic/go-critic/checkers/emptyFallthrough_checker.go
сгенерированный
поставляемый
Normal file
70
vendor/github.com/go-critic/go-critic/checkers/emptyFallthrough_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,70 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "emptyFallthrough"
|
||||
info.Tags = []string{"style", "experimental"}
|
||||
info.Summary = "Detects fallthrough that can be avoided by using multi case values"
|
||||
info.Before = `switch kind {
|
||||
case reflect.Int:
|
||||
fallthrough
|
||||
case reflect.Int32:
|
||||
return Int
|
||||
}`
|
||||
info.After = `switch kind {
|
||||
case reflect.Int, reflect.Int32:
|
||||
return Int
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&emptyFallthroughChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type emptyFallthroughChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *emptyFallthroughChecker) VisitStmt(stmt ast.Stmt) {
|
||||
ss, ok := stmt.(*ast.SwitchStmt)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
prevCaseDefault := false
|
||||
for i := len(ss.Body.List) - 1; i >= 0; i-- {
|
||||
if cc, ok := ss.Body.List[i].(*ast.CaseClause); ok {
|
||||
warn := false
|
||||
if len(cc.Body) == 1 {
|
||||
if bs, ok := cc.Body[0].(*ast.BranchStmt); ok && bs.Tok == token.FALLTHROUGH {
|
||||
warn = true
|
||||
if prevCaseDefault {
|
||||
c.warnDefault(bs)
|
||||
} else {
|
||||
c.warn(bs)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !warn {
|
||||
prevCaseDefault = cc.List == nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *emptyFallthroughChecker) warnDefault(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "remove empty case containing only fallthrough to default case")
|
||||
}
|
||||
|
||||
func (c *emptyFallthroughChecker) warn(cause ast.Node) {
|
||||
c.ctx.Warn(cause, "replace empty case containing only fallthrough with expression list")
|
||||
}
|
58
vendor/github.com/go-critic/go-critic/checkers/emptyStringTest_checker.go
сгенерированный
поставляемый
Normal file
58
vendor/github.com/go-critic/go-critic/checkers/emptyStringTest_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,58 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astcopy"
|
||||
"github.com/go-toolsmith/typep"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "emptyStringTest"
|
||||
info.Tags = []string{"style", "experimental"}
|
||||
info.Summary = "Detects empty string checks that can be written more idiomatically"
|
||||
info.Before = `len(s) == 0`
|
||||
info.After = `s == ""`
|
||||
info.Note = "See https://dmitri.shuralyov.com/idiomatic-go#empty-string-check."
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&emptyStringTestChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type emptyStringTestChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *emptyStringTestChecker) VisitExpr(e ast.Expr) {
|
||||
cmp := astcast.ToBinaryExpr(e)
|
||||
if cmp.Op != token.EQL && cmp.Op != token.NEQ {
|
||||
return
|
||||
}
|
||||
lenCall := astcast.ToCallExpr(cmp.X)
|
||||
if astcast.ToIdent(lenCall.Fun).Name != "len" {
|
||||
return
|
||||
}
|
||||
s := lenCall.Args[0]
|
||||
if !typep.HasStringProp(c.ctx.TypesInfo.TypeOf(s)) {
|
||||
return
|
||||
}
|
||||
zero := astcast.ToBasicLit(cmp.Y)
|
||||
if zero.Value != "0" {
|
||||
return
|
||||
}
|
||||
c.warn(cmp, s)
|
||||
}
|
||||
|
||||
func (c *emptyStringTestChecker) warn(cmp *ast.BinaryExpr, s ast.Expr) {
|
||||
suggest := astcopy.BinaryExpr(cmp)
|
||||
suggest.X = s
|
||||
suggest.Y = &ast.BasicLit{Value: `""`}
|
||||
c.ctx.Warn(cmp, "replace `%s` with `%s`", cmp, suggest)
|
||||
}
|
87
vendor/github.com/go-critic/go-critic/checkers/equalFold_checker.go
сгенерированный
поставляемый
Normal file
87
vendor/github.com/go-critic/go-critic/checkers/equalFold_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,87 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "equalFold"
|
||||
info.Tags = []string{"performance", "experimental"}
|
||||
info.Summary = "Detects unoptimal strings/bytes case-insensitive comparison"
|
||||
info.Before = `strings.ToLower(x) == strings.ToLower(y)`
|
||||
info.After = `strings.EqualFold(x, y)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&equalFoldChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type equalFoldChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *equalFoldChecker) VisitExpr(e ast.Expr) {
|
||||
switch e := e.(type) {
|
||||
case *ast.CallExpr:
|
||||
c.checkBytes(e)
|
||||
case *ast.BinaryExpr:
|
||||
c.checkStrings(e)
|
||||
}
|
||||
}
|
||||
|
||||
// uncaseCall simplifies lower(x) or upper(x) to x.
|
||||
// If no simplification is applied, second return value is false.
|
||||
func (c *equalFoldChecker) uncaseCall(x ast.Expr, lower, upper string) (ast.Expr, bool) {
|
||||
call := astcast.ToCallExpr(x)
|
||||
name := qualifiedName(call.Fun)
|
||||
if name != lower && name != upper {
|
||||
return x, false
|
||||
}
|
||||
return call.Args[0], true
|
||||
}
|
||||
|
||||
func (c *equalFoldChecker) checkBytes(expr *ast.CallExpr) {
|
||||
if qualifiedName(expr.Fun) != "bytes.Equal" {
|
||||
return
|
||||
}
|
||||
|
||||
x, ok1 := c.uncaseCall(expr.Args[0], "bytes.ToLower", "bytes.ToUpper")
|
||||
y, ok2 := c.uncaseCall(expr.Args[1], "bytes.ToLower", "bytes.ToUpper")
|
||||
if !ok1 && !ok2 {
|
||||
return
|
||||
}
|
||||
if !astequal.Expr(x, y) {
|
||||
c.warnBytes(expr, x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *equalFoldChecker) checkStrings(expr *ast.BinaryExpr) {
|
||||
if expr.Op != token.EQL && expr.Op != token.NEQ {
|
||||
return
|
||||
}
|
||||
|
||||
x, ok1 := c.uncaseCall(expr.X, "strings.ToLower", "strings.ToUpper")
|
||||
y, ok2 := c.uncaseCall(expr.Y, "strings.ToLower", "strings.ToUpper")
|
||||
if !ok1 && !ok2 {
|
||||
return
|
||||
}
|
||||
if !astequal.Expr(x, y) {
|
||||
c.warnStrings(expr, x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *equalFoldChecker) warnStrings(cause ast.Node, x, y ast.Expr) {
|
||||
c.ctx.Warn(cause, "consider replacing with strings.EqualFold(%s, %s)", x, y)
|
||||
}
|
||||
|
||||
func (c *equalFoldChecker) warnBytes(cause ast.Node, x, y ast.Expr) {
|
||||
c.ctx.Warn(cause, "consider replacing with bytes.EqualFold(%s, %s)", x, y)
|
||||
}
|
87
vendor/github.com/go-critic/go-critic/checkers/evalOrder_checker.go
сгенерированный
поставляемый
Normal file
87
vendor/github.com/go-critic/go-critic/checkers/evalOrder_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,87 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"go/types"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/checkers/internal/lintutil"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/astequal"
|
||||
"github.com/go-toolsmith/typep"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "evalOrder"
|
||||
info.Tags = []string{"diagnostic", "experimental"}
|
||||
info.Summary = "Detects unwanted dependencies on the evaluation order"
|
||||
info.Before = `return x, f(&x)`
|
||||
info.After = `
|
||||
err := f(&x)
|
||||
return x, err
|
||||
`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&evalOrderChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type evalOrderChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *evalOrderChecker) VisitStmt(stmt ast.Stmt) {
|
||||
ret := astcast.ToReturnStmt(stmt)
|
||||
if len(ret.Results) < 2 {
|
||||
return
|
||||
}
|
||||
|
||||
// TODO(quasilyte): handle selector expressions like o.val in addition
|
||||
// to bare identifiers.
|
||||
addrTake := &ast.UnaryExpr{Op: token.AND}
|
||||
for _, res := range ret.Results {
|
||||
id, ok := res.(*ast.Ident)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
addrTake.X = id // addrTake is &id now
|
||||
for _, res := range ret.Results {
|
||||
call, ok := res.(*ast.CallExpr)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
// 1. Check if there is a call in form of id.method() where
|
||||
// method takes id by a pointer.
|
||||
if sel, ok := call.Fun.(*ast.SelectorExpr); ok {
|
||||
if astequal.Node(sel.X, id) && c.hasPtrRecv(sel.Sel) {
|
||||
c.warn(call)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Check that there is no call that uses &id as an argument.
|
||||
dependency := lintutil.ContainsNode(call, func(n ast.Node) bool {
|
||||
return astequal.Node(addrTake, n)
|
||||
})
|
||||
if dependency {
|
||||
c.warn(call)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *evalOrderChecker) hasPtrRecv(fn *ast.Ident) bool {
|
||||
sig, ok := c.ctx.TypesInfo.TypeOf(fn).(*types.Signature)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return typep.IsPointer(sig.Recv().Type())
|
||||
}
|
||||
|
||||
func (c *evalOrderChecker) warn(call *ast.CallExpr) {
|
||||
c.ctx.Warn(call, "may want to evaluate %s before the return statement", call)
|
||||
}
|
76
vendor/github.com/go-critic/go-critic/checkers/exitAfterDefer_checker.go
сгенерированный
поставляемый
Normal file
76
vendor/github.com/go-critic/go-critic/checkers/exitAfterDefer_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,76 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astfmt"
|
||||
"github.com/go-toolsmith/astp"
|
||||
"golang.org/x/tools/go/ast/astutil"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "exitAfterDefer"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects calls to exit/fatal inside functions that use defer"
|
||||
info.Before = `
|
||||
defer os.Remove(filename)
|
||||
if bad {
|
||||
log.Fatalf("something bad happened")
|
||||
}`
|
||||
info.After = `
|
||||
defer os.Remove(filename)
|
||||
if bad {
|
||||
log.Printf("something bad happened")
|
||||
return
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForFuncDecl(&exitAfterDeferChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type exitAfterDeferChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *exitAfterDeferChecker) VisitFuncDecl(fn *ast.FuncDecl) {
|
||||
// TODO(Quasilyte): handle goto and other kinds of flow that break
|
||||
// the algorithm below that expects the latter statement to be
|
||||
// executed after the ones that come before it.
|
||||
|
||||
var deferStmt *ast.DeferStmt
|
||||
pre := func(cur *astutil.Cursor) bool {
|
||||
// Don't recurse into local anonymous functions.
|
||||
return !astp.IsFuncLit(cur.Node())
|
||||
}
|
||||
post := func(cur *astutil.Cursor) bool {
|
||||
switch n := cur.Node().(type) {
|
||||
case *ast.DeferStmt:
|
||||
deferStmt = n
|
||||
case *ast.CallExpr:
|
||||
if deferStmt != nil {
|
||||
switch qualifiedName(n.Fun) {
|
||||
case "log.Fatal", "log.Fatalf", "log.Fatalln", "os.Exit":
|
||||
c.warn(n, deferStmt)
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
astutil.Apply(fn.Body, pre, post)
|
||||
}
|
||||
|
||||
func (c *exitAfterDeferChecker) warn(cause *ast.CallExpr, deferStmt *ast.DeferStmt) {
|
||||
s := astfmt.Sprint(deferStmt)
|
||||
if fnlit, ok := deferStmt.Call.Fun.(*ast.FuncLit); ok {
|
||||
// To avoid long and multi-line warning messages,
|
||||
// collapse the function literals.
|
||||
s = "defer " + astfmt.Sprint(fnlit.Type) + "{...}(...)"
|
||||
}
|
||||
c.ctx.Warn(cause, "%s clutters `%s`", cause.Fun, s)
|
||||
}
|
50
vendor/github.com/go-critic/go-critic/checkers/filepathJoin_checker.go
сгенерированный
поставляемый
Normal file
50
vendor/github.com/go-critic/go-critic/checkers/filepathJoin_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,50 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"strings"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "filepathJoin"
|
||||
info.Tags = []string{"diagnostic", "experimental"}
|
||||
info.Summary = "Detects problems in filepath.Join() function calls"
|
||||
info.Before = `filepath.Join("dir/", filename)`
|
||||
info.After = `filepath.Join("dir", filename)`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&filepathJoinChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type filepathJoinChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *filepathJoinChecker) VisitExpr(expr ast.Expr) {
|
||||
call := astcast.ToCallExpr(expr)
|
||||
if qualifiedName(call.Fun) != "filepath.Join" {
|
||||
return
|
||||
}
|
||||
|
||||
for _, arg := range call.Args {
|
||||
arg, ok := arg.(*ast.BasicLit)
|
||||
if ok && c.hasSeparator(arg) {
|
||||
c.warnSeparator(arg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *filepathJoinChecker) hasSeparator(v *ast.BasicLit) bool {
|
||||
return strings.ContainsAny(v.Value, `/\`)
|
||||
}
|
||||
|
||||
func (c *filepathJoinChecker) warnSeparator(sep ast.Expr) {
|
||||
c.ctx.Warn(sep, "%s contains a path separator", sep)
|
||||
}
|
65
vendor/github.com/go-critic/go-critic/checkers/flagDeref_checker.go
сгенерированный
поставляемый
Normal file
65
vendor/github.com/go-critic/go-critic/checkers/flagDeref_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,65 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "flagDeref"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects immediate dereferencing of `flag` package pointers"
|
||||
info.Details = "Suggests to use pointer to array to avoid the copy using `&` on range expression."
|
||||
info.Before = `b := *flag.Bool("b", false, "b docs")`
|
||||
info.After = `
|
||||
var b bool
|
||||
flag.BoolVar(&b, "b", false, "b docs")`
|
||||
info.Note = `
|
||||
Dereferencing returned pointers will lead to hard to find errors
|
||||
where flag values are not updated after flag.Parse().`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
c := &flagDerefChecker{
|
||||
ctx: ctx,
|
||||
flagPtrFuncs: map[string]bool{
|
||||
"flag.Bool": true,
|
||||
"flag.Duration": true,
|
||||
"flag.Float64": true,
|
||||
"flag.Int": true,
|
||||
"flag.Int64": true,
|
||||
"flag.String": true,
|
||||
"flag.Uint": true,
|
||||
"flag.Uint64": true,
|
||||
},
|
||||
}
|
||||
return astwalk.WalkerForExpr(c)
|
||||
})
|
||||
}
|
||||
|
||||
type flagDerefChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
flagPtrFuncs map[string]bool
|
||||
}
|
||||
|
||||
func (c *flagDerefChecker) VisitExpr(expr ast.Expr) {
|
||||
if expr, ok := expr.(*ast.StarExpr); ok {
|
||||
call, ok := expr.X.(*ast.CallExpr)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
called := qualifiedName(call.Fun)
|
||||
if c.flagPtrFuncs[called] {
|
||||
c.warn(expr, called+"Var")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *flagDerefChecker) warn(x ast.Node, suggestion string) {
|
||||
c.ctx.Warn(x, "immediate deref in %s is most likely an error; consider using %s",
|
||||
x, suggestion)
|
||||
}
|
68
vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go
сгенерированный
поставляемый
Normal file
68
vendor/github.com/go-critic/go-critic/checkers/flagName_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,68 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/constant"
|
||||
"go/types"
|
||||
"strings"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "flagName"
|
||||
info.Tags = []string{"diagnostic"}
|
||||
info.Summary = "Detects flag names with whitespace"
|
||||
info.Before = `b := flag.Bool(" foo ", false, "description")`
|
||||
info.After = `b := flag.Bool("foo", false, "description")`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&flagNameChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type flagNameChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *flagNameChecker) VisitExpr(expr ast.Expr) {
|
||||
call := astcast.ToCallExpr(expr)
|
||||
calledExpr := astcast.ToSelectorExpr(call.Fun)
|
||||
obj, ok := c.ctx.TypesInfo.ObjectOf(astcast.ToIdent(calledExpr.X)).(*types.PkgName)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
sym := calledExpr.Sel
|
||||
pkg := obj.Imported()
|
||||
if pkg.Path() != "flag" {
|
||||
return
|
||||
}
|
||||
|
||||
switch sym.Name {
|
||||
case "Bool", "Duration", "Float64", "String",
|
||||
"Int", "Int64", "Uint", "Uint64":
|
||||
c.checkFlagName(call, call.Args[0])
|
||||
case "BoolVar", "DurationVar", "Float64Var", "StringVar",
|
||||
"IntVar", "Int64Var", "UintVar", "Uint64Var":
|
||||
c.checkFlagName(call, call.Args[1])
|
||||
}
|
||||
}
|
||||
|
||||
func (c *flagNameChecker) checkFlagName(call *ast.CallExpr, arg ast.Expr) {
|
||||
cv := c.ctx.TypesInfo.Types[arg].Value
|
||||
if cv == nil {
|
||||
return // Non-constant name
|
||||
}
|
||||
name := constant.StringVal(cv)
|
||||
if strings.Contains(name, " ") {
|
||||
c.warnWhitespace(call, name)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *flagNameChecker) warnWhitespace(cause ast.Node, name string) {
|
||||
c.ctx.Warn(cause, "flag name %q contains whitespace", name)
|
||||
}
|
60
vendor/github.com/go-critic/go-critic/checkers/hexLiteral_checker.go
сгенерированный
поставляемый
Normal file
60
vendor/github.com/go-critic/go-critic/checkers/hexLiteral_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,60 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/token"
|
||||
"strings"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "hexLiteral"
|
||||
info.Tags = []string{"style", "experimental"}
|
||||
info.Summary = "Detects hex literals that have mixed case letter digits"
|
||||
info.Before = `
|
||||
x := 0X12
|
||||
y := 0xfF`
|
||||
info.After = `
|
||||
x := 0x12
|
||||
// (A)
|
||||
y := 0xff
|
||||
// (B)
|
||||
y := 0xFF`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&hexLiteralChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type hexLiteralChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *hexLiteralChecker) warn0X(lit *ast.BasicLit) {
|
||||
suggest := "0x" + lit.Value[len("0X"):]
|
||||
c.ctx.Warn(lit, "prefer 0x over 0X, s/%s/%s/", lit.Value, suggest)
|
||||
}
|
||||
|
||||
func (c *hexLiteralChecker) warnMixedDigits(lit *ast.BasicLit) {
|
||||
c.ctx.Warn(lit, "don't mix hex literal letter digits casing")
|
||||
}
|
||||
|
||||
func (c *hexLiteralChecker) VisitExpr(expr ast.Expr) {
|
||||
lit := astcast.ToBasicLit(expr)
|
||||
if lit.Kind != token.INT || len(lit.Value) < 3 {
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(lit.Value, "0X") {
|
||||
c.warn0X(lit)
|
||||
return
|
||||
}
|
||||
digits := lit.Value[len("0x"):]
|
||||
if strings.ToLower(digits) != digits && strings.ToUpper(digits) != digits {
|
||||
c.warnMixedDigits(lit)
|
||||
}
|
||||
}
|
63
vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go
сгенерированный
поставляемый
Normal file
63
vendor/github.com/go-critic/go-critic/checkers/hugeParam_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,63 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "hugeParam"
|
||||
info.Tags = []string{"performance"}
|
||||
info.Params = linter.CheckerParams{
|
||||
"sizeThreshold": {
|
||||
Value: 80,
|
||||
Usage: "size in bytes that makes the warning trigger",
|
||||
},
|
||||
}
|
||||
info.Summary = "Detects params that incur excessive amount of copying"
|
||||
info.Before = `func f(x [1024]int) {}`
|
||||
info.After = `func f(x *[1024]int) {}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForFuncDecl(&hugeParamChecker{
|
||||
ctx: ctx,
|
||||
sizeThreshold: int64(info.Params.Int("sizeThreshold")),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
type hugeParamChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
sizeThreshold int64
|
||||
}
|
||||
|
||||
func (c *hugeParamChecker) VisitFuncDecl(decl *ast.FuncDecl) {
|
||||
// TODO(quasilyte): maybe it's worthwhile to permit skipping
|
||||
// test files for this checker?
|
||||
if decl.Recv != nil {
|
||||
c.checkParams(decl.Recv.List)
|
||||
}
|
||||
c.checkParams(decl.Type.Params.List)
|
||||
}
|
||||
|
||||
func (c *hugeParamChecker) checkParams(params []*ast.Field) {
|
||||
for _, p := range params {
|
||||
for _, id := range p.Names {
|
||||
typ := c.ctx.TypesInfo.TypeOf(id)
|
||||
size := c.ctx.SizesInfo.Sizeof(typ)
|
||||
if size >= c.sizeThreshold {
|
||||
c.warn(id, size)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *hugeParamChecker) warn(cause *ast.Ident, size int64) {
|
||||
c.ctx.Warn(cause, "%s is heavy (%d bytes); consider passing it by pointer",
|
||||
cause, size)
|
||||
}
|
99
vendor/github.com/go-critic/go-critic/checkers/ifElseChain_checker.go
сгенерированный
поставляемый
Normal file
99
vendor/github.com/go-critic/go-critic/checkers/ifElseChain_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,99 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "ifElseChain"
|
||||
info.Tags = []string{"style"}
|
||||
info.Summary = "Detects repeated if-else statements and suggests to replace them with switch statement"
|
||||
info.Before = `
|
||||
if cond1 {
|
||||
// Code A.
|
||||
} else if cond2 {
|
||||
// Code B.
|
||||
} else {
|
||||
// Code C.
|
||||
}`
|
||||
info.After = `
|
||||
switch {
|
||||
case cond1:
|
||||
// Code A.
|
||||
case cond2:
|
||||
// Code B.
|
||||
default:
|
||||
// Code C.
|
||||
}`
|
||||
info.Note = `
|
||||
Permits single else or else-if; repeated else-if or else + else-if
|
||||
will trigger suggestion to use switch statement.
|
||||
See [EffectiveGo#switch](https://golang.org/doc/effective_go.html#switch).`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&ifElseChainChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type ifElseChainChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
|
||||
cause *ast.IfStmt
|
||||
visited map[*ast.IfStmt]bool
|
||||
}
|
||||
|
||||
func (c *ifElseChainChecker) EnterFunc(fn *ast.FuncDecl) bool {
|
||||
if fn.Body == nil {
|
||||
return false
|
||||
}
|
||||
c.visited = make(map[*ast.IfStmt]bool)
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *ifElseChainChecker) VisitStmt(stmt ast.Stmt) {
|
||||
if stmt, ok := stmt.(*ast.IfStmt); ok {
|
||||
if c.visited[stmt] {
|
||||
return
|
||||
}
|
||||
c.cause = stmt
|
||||
c.checkIfStmt(stmt)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ifElseChainChecker) checkIfStmt(stmt *ast.IfStmt) {
|
||||
const minThreshold = 2
|
||||
if c.countIfelseLen(stmt) >= minThreshold {
|
||||
c.warn()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ifElseChainChecker) countIfelseLen(stmt *ast.IfStmt) int {
|
||||
count := 0
|
||||
for {
|
||||
switch e := stmt.Else.(type) {
|
||||
case *ast.IfStmt:
|
||||
if e.Init != nil {
|
||||
return 0 // Give up
|
||||
}
|
||||
// Else if.
|
||||
stmt = e
|
||||
count++
|
||||
c.visited[e] = true
|
||||
case *ast.BlockStmt:
|
||||
// Else branch.
|
||||
return count + 1
|
||||
default:
|
||||
// No else or else if.
|
||||
return count
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *ifElseChainChecker) warn() {
|
||||
c.ctx.Warn(c.cause, "rewrite if-else to switch statement")
|
||||
}
|
47
vendor/github.com/go-critic/go-critic/checkers/importShadow_checker.go
сгенерированный
поставляемый
Normal file
47
vendor/github.com/go-critic/go-critic/checkers/importShadow_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,47 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"go/types"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "importShadow"
|
||||
info.Tags = []string{"style", "opinionated"}
|
||||
info.Summary = "Detects when imported package names shadowed in the assignments"
|
||||
info.Before = `
|
||||
// "path/filepath" is imported.
|
||||
filepath := "foo.txt"`
|
||||
info.After = `
|
||||
filename := "foo.txt"`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
ctx.Require.PkgObjects = true
|
||||
return astwalk.WalkerForLocalDef(&importShadowChecker{ctx: ctx}, ctx.TypesInfo)
|
||||
})
|
||||
}
|
||||
|
||||
type importShadowChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *importShadowChecker) VisitLocalDef(def astwalk.Name, _ ast.Expr) {
|
||||
for pkgObj, name := range c.ctx.PkgObjects {
|
||||
if name == def.ID.Name && name != "_" {
|
||||
c.warn(def.ID, name, pkgObj.Imported())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *importShadowChecker) warn(id ast.Node, importedName string, pkg *types.Package) {
|
||||
if isStdlibPkg(pkg) {
|
||||
c.ctx.Warn(id, "shadow of imported package '%s'", importedName)
|
||||
} else {
|
||||
c.ctx.Warn(id, "shadow of imported from '%s' package '%s'", pkg.Path(), importedName)
|
||||
}
|
||||
}
|
50
vendor/github.com/go-critic/go-critic/checkers/indexAlloc_checker.go
сгенерированный
поставляемый
Normal file
50
vendor/github.com/go-critic/go-critic/checkers/indexAlloc_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,50 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astcast"
|
||||
"github.com/go-toolsmith/typep"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "indexAlloc"
|
||||
info.Tags = []string{"performance"}
|
||||
info.Summary = "Detects strings.Index calls that may cause unwanted allocs"
|
||||
info.Before = `strings.Index(string(x), y)`
|
||||
info.After = `bytes.Index(x, []byte(y))`
|
||||
info.Note = `See Go issue for details: https://github.com/golang/go/issues/25864`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForExpr(&indexAllocChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type indexAllocChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *indexAllocChecker) VisitExpr(e ast.Expr) {
|
||||
call := astcast.ToCallExpr(e)
|
||||
if qualifiedName(call.Fun) != "strings.Index" {
|
||||
return
|
||||
}
|
||||
stringConv := astcast.ToCallExpr(call.Args[0])
|
||||
if qualifiedName(stringConv.Fun) != "string" {
|
||||
return
|
||||
}
|
||||
x := stringConv.Args[0]
|
||||
y := call.Args[1]
|
||||
if typep.SideEffectFree(c.ctx.TypesInfo, x) && typep.SideEffectFree(c.ctx.TypesInfo, y) {
|
||||
c.warn(e, x, y)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *indexAllocChecker) warn(cause ast.Node, x, y ast.Expr) {
|
||||
c.ctx.Warn(cause, "consider replacing %s with bytes.Index(%s, []byte(%s))",
|
||||
cause, x, y)
|
||||
}
|
56
vendor/github.com/go-critic/go-critic/checkers/initClause_checker.go
сгенерированный
поставляемый
Normal file
56
vendor/github.com/go-critic/go-critic/checkers/initClause_checker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,56 @@
|
|||
package checkers
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
|
||||
"github.com/go-critic/go-critic/checkers/internal/astwalk"
|
||||
"github.com/go-critic/go-critic/framework/linter"
|
||||
"github.com/go-toolsmith/astp"
|
||||
)
|
||||
|
||||
func init() {
|
||||
var info linter.CheckerInfo
|
||||
info.Name = "initClause"
|
||||
info.Tags = []string{"style", "opinionated", "experimental"}
|
||||
info.Summary = "Detects non-assignment statements inside if/switch init clause"
|
||||
info.Before = `if sideEffect(); cond {
|
||||
}`
|
||||
info.After = `sideEffect()
|
||||
if cond {
|
||||
}`
|
||||
|
||||
collection.AddChecker(&info, func(ctx *linter.CheckerContext) linter.FileWalker {
|
||||
return astwalk.WalkerForStmt(&initClauseChecker{ctx: ctx})
|
||||
})
|
||||
}
|
||||
|
||||
type initClauseChecker struct {
|
||||
astwalk.WalkHandler
|
||||
ctx *linter.CheckerContext
|
||||
}
|
||||
|
||||
func (c *initClauseChecker) VisitStmt(stmt ast.Stmt) {
|
||||
initClause := c.getInitClause(stmt)
|
||||
if initClause != nil && !astp.IsAssignStmt(initClause) {
|
||||
c.warn(stmt, initClause)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *initClauseChecker) getInitClause(x ast.Stmt) ast.Stmt {
|
||||
switch x := x.(type) {
|
||||
case *ast.IfStmt:
|
||||
return x.Init
|
||||
case *ast.SwitchStmt:
|
||||
return x.Init
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c *initClauseChecker) warn(stmt, clause ast.Stmt) {
|
||||
name := "if"
|
||||
if astp.IsSwitchStmt(stmt) {
|
||||
name = "switch"
|
||||
}
|
||||
c.ctx.Warn(stmt, "consider to move `%s` before %s", clause, name)
|
||||
}
|
41
vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/comment_walker.go
сгенерированный
поставляемый
Normal file
41
vendor/github.com/go-critic/go-critic/checkers/internal/astwalk/comment_walker.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,41 @@
|
|||
package astwalk
|
||||
|
||||
import (
|
||||
"go/ast"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type commentWalker struct {
|
||||
visitor CommentVisitor
|
||||
}
|
||||
|
||||
func (w *commentWalker) WalkFile(f *ast.File) {
|
||||
if !w.visitor.EnterFile(f) {
|
||||
return
|
||||
}
|
||||
|
||||
for _, cg := range f.Comments {
|
||||
visitCommentGroups(cg, w.visitor.VisitComment)
|
||||
}
|
||||
}
|
||||
|
||||
func visitCommentGroups(cg *ast.CommentGroup, visit func(*ast.CommentGroup)) {
|
||||
var group []*ast.Comment
|
||||
visitGroup := func(list []*ast.Comment) {
|
||||
if len(list) == 0 {
|
||||
return
|
||||
}
|
||||
cg := &ast.CommentGroup{List: list}
|
||||
visit(cg)
|
||||
}
|
||||
for _, comment := range cg.List {
|
||||
if strings.HasPrefix(comment.Text, "/*") {
|
||||
visitGroup(group)
|
||||
group = group[:0]
|
||||
visitGroup([]*ast.Comment{comment})
|
||||
} else {
|
||||
group = append(group, comment)
|
||||
}
|
||||
}
|
||||
visitGroup(group)
|
||||
}
|
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Загрузка…
Ссылка в новой задаче