Update deps

This commit is contained in:
Frank Denis 2023-03-23 12:54:45 +01:00
parent beb002335f
commit a47f7fe750
1943 changed files with 7896 additions and 330590 deletions

152
go.mod
View File

@ -8,7 +8,7 @@ require (
github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf
github.com/dchest/safefile v0.0.0-20151022103144-855e8d98f185
github.com/hashicorp/go-immutable-radix v1.3.1
github.com/hashicorp/golang-lru v0.5.4
github.com/hashicorp/golang-lru v0.5.0
github.com/hectane/go-acl v0.0.0-20230122075934-ca0b05cb1adb
github.com/jedisct1/dlog v0.0.0-20230211133026-0338add8743f
github.com/jedisct1/go-clocksmith v0.0.0-20230211133011-392c1afea73e
@ -18,161 +18,35 @@ require (
github.com/jedisct1/xsecretbox v0.0.0-20230211185120-2025cdbb9f0f
github.com/k-sone/critbitgo v1.4.0
github.com/kardianos/service v1.2.2
github.com/miekg/dns v1.1.50
github.com/powerman/check v1.6.0
github.com/miekg/dns v1.1.52
github.com/powerman/check v1.7.0
github.com/quic-go/quic-go v0.33.0
golang.org/x/crypto v0.6.0
golang.org/x/net v0.7.0
golang.org/x/sys v0.5.0
golang.org/x/crypto v0.7.0
golang.org/x/net v0.8.0
golang.org/x/sys v0.6.0
gopkg.in/natefinch/lumberjack.v2 v2.2.1
)
require (
4d63.com/gochecknoglobals v0.0.0-20201008074935-acfc0b28355a // indirect
github.com/Djarvur/go-err113 v0.0.0-20210108212216-aea10b59be24 // indirect
github.com/Masterminds/semver v1.5.0 // indirect
github.com/OpenPeeDeeP/depguard v1.0.1 // indirect
github.com/alexkohler/prealloc v1.0.0 // indirect
github.com/ashanbrown/forbidigo v1.2.0 // indirect
github.com/ashanbrown/makezero v0.0.0-20210520155254-b6261585ddde // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/bkielbasa/cyclop v1.2.0 // indirect
github.com/bombsimon/wsl/v3 v3.3.0 // indirect
github.com/cespare/xxhash/v2 v2.1.1 // indirect
github.com/charithe/durationcheck v0.0.8 // indirect
github.com/chavacava/garif v0.0.0-20210405164556-e8a0a408d6af // indirect
github.com/daixiang0/gci v0.2.8 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/denis-tingajkin/go-header v0.4.2 // indirect
github.com/esimonov/ifshort v1.0.2 // indirect
github.com/ettle/strcase v0.1.1 // indirect
github.com/fatih/color v1.12.0 // indirect
github.com/fatih/structtag v1.2.0 // indirect
github.com/fsnotify/fsnotify v1.4.9 // indirect
github.com/fzipp/gocyclo v0.3.1 // indirect
github.com/go-critic/go-critic v0.5.6 // indirect
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 // indirect
github.com/go-toolsmith/astcast v1.0.0 // indirect
github.com/go-toolsmith/astcopy v1.0.0 // indirect
github.com/go-toolsmith/astequal v1.0.0 // indirect
github.com/go-toolsmith/astfmt v1.0.0 // indirect
github.com/go-toolsmith/astp v1.0.0 // indirect
github.com/go-toolsmith/strparse v1.0.0 // indirect
github.com/go-toolsmith/typep v1.0.2 // indirect
github.com/go-xmlfmt/xmlfmt v0.0.0-20191208150333-d5b6f63a941b // indirect
github.com/gobwas/glob v0.2.3 // indirect
github.com/gofrs/flock v0.8.0 // indirect
github.com/golang/mock v1.6.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/golangci/check v0.0.0-20180506172741-cfe4005ccda2 // indirect
github.com/golangci/dupl v0.0.0-20180902072040-3e9179ac440a // indirect
github.com/golangci/go-misc v0.0.0-20180628070357-927a3d87b613 // indirect
github.com/golangci/gofmt v0.0.0-20190930125516-244bba706f1a // indirect
github.com/golangci/golangci-lint v1.41.1 // indirect
github.com/golangci/lint-1 v0.0.0-20191013205115-297bf364a8e0 // indirect
github.com/golangci/maligned v0.0.0-20180506175553-b1d89398deca // indirect
github.com/golangci/misspell v0.3.5 // indirect
github.com/golangci/revgrep v0.0.0-20210208091834-cd28932614b5 // indirect
github.com/golangci/unconvert v0.0.0-20180507085042-28b1c447d1f4 // indirect
github.com/google/go-cmp v0.5.8 // indirect
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect
github.com/gordonklaus/ineffassign v0.0.0-20210225214923-2e10b2664254 // indirect
github.com/gostaticanalysis/analysisutil v0.4.1 // indirect
github.com/gostaticanalysis/comment v1.4.1 // indirect
github.com/gostaticanalysis/forcetypeassert v0.0.0-20200621232751-01d4955beaa5 // indirect
github.com/gostaticanalysis/nilerr v0.1.1 // indirect
github.com/hashicorp/errwrap v1.0.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/hashicorp/go-syslog v1.0.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jgautheron/goconst v1.5.1 // indirect
github.com/jingyugao/rowserrcheck v1.1.0 // indirect
github.com/jirfag/go-printf-func-name v0.0.0-20200119135958-7558a9eaa5af // indirect
github.com/julz/importas v0.0.0-20210419104244-841f0c0fe66d // indirect
github.com/kisielk/errcheck v1.6.0 // indirect
github.com/kisielk/gotool v1.0.0 // indirect
github.com/kulti/thelper v0.4.0 // indirect
github.com/kunwardeep/paralleltest v1.0.2 // indirect
github.com/kyoh86/exportloopref v0.1.8 // indirect
github.com/ldez/gomoddirectives v0.2.1 // indirect
github.com/ldez/tagliatelle v0.2.0 // indirect
github.com/magiconair/properties v1.8.1 // indirect
github.com/maratori/testpackage v1.0.1 // indirect
github.com/matoous/godox v0.0.0-20210227103229-6504466cf951 // indirect
github.com/mattn/go-colorable v0.1.8 // indirect
github.com/mattn/go-isatty v0.0.12 // indirect
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/mattn/goveralls v0.0.9 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
github.com/mbilski/exhaustivestruct v1.2.0 // indirect
github.com/mgechev/dots v0.0.0-20190921121421-c36f7dcfbb81 // indirect
github.com/mgechev/revive v1.0.7 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/mapstructure v1.1.2 // indirect
github.com/moricho/tparallel v0.2.1 // indirect
github.com/nakabonne/nestif v0.3.0 // indirect
github.com/nbutton23/zxcvbn-go v0.0.0-20210217022336-fa2cb2858354 // indirect
github.com/nishanths/exhaustive v0.1.0 // indirect
github.com/nishanths/predeclared v0.2.1 // indirect
github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/onsi/ginkgo/v2 v2.2.0 // indirect
github.com/pelletier/go-toml v1.2.0 // indirect
github.com/phayes/checkstyle v0.0.0-20170904204023-bfd46e6a821d // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/polyfloyd/go-errorlint v0.0.0-20210510181950-ab96adb96fea // indirect
github.com/powerman/deepequal v0.1.0 // indirect
github.com/prometheus/client_golang v1.7.1 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
github.com/prometheus/common v0.10.0 // indirect
github.com/prometheus/procfs v0.1.3 // indirect
github.com/quasilyte/go-ruleguard v0.3.4 // indirect
github.com/quasilyte/regex/syntax v0.0.0-20200407221936-30656e2c4a95 // indirect
github.com/quic-go/qpack v0.4.0 // indirect
github.com/quic-go/qtls-go1-19 v0.2.1 // indirect
github.com/quic-go/qtls-go1-20 v0.1.1 // indirect
github.com/ryancurrah/gomodguard v1.2.2 // indirect
github.com/ryanrolds/sqlclosecheck v0.3.0 // indirect
github.com/sanposhiho/wastedassign/v2 v2.0.6 // indirect
github.com/securego/gosec/v2 v2.8.0 // indirect
github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c // indirect
github.com/sirupsen/logrus v1.8.1 // indirect
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/sonatard/noctx v0.0.1 // indirect
github.com/sourcegraph/go-diff v0.6.1 // indirect
github.com/spf13/afero v1.1.2 // indirect
github.com/spf13/cast v1.3.0 // indirect
github.com/spf13/cobra v1.1.3 // indirect
github.com/spf13/jwalterweatherman v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.7.1 // indirect
github.com/ssgreg/nlreturn/v2 v2.1.0 // indirect
github.com/stretchr/objx v0.1.1 // indirect
github.com/stretchr/testify v1.7.0 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/tdakkota/asciicheck v0.0.0-20200416200610-e657995f937b // indirect
github.com/tetafro/godot v1.4.7 // indirect
github.com/timakin/bodyclose v0.0.0-20200424151742-cb6215831a94 // indirect
github.com/tomarrell/wrapcheck/v2 v2.1.0 // indirect
github.com/tommy-muehle/go-mnd/v2 v2.4.0 // indirect
github.com/ultraware/funlen v0.0.3 // indirect
github.com/ultraware/whitespace v0.0.4 // indirect
github.com/uudashr/gocognit v1.0.1 // indirect
github.com/yeya24/promlinter v0.1.0 // indirect
github.com/smartystreets/goconvey v1.7.2 // indirect
golang.org/x/exp v0.0.0-20221205204356-47842c84f3db // indirect
golang.org/x/mod v0.6.0 // indirect
golang.org/x/text v0.7.0 // indirect
golang.org/x/tools v0.2.0 // indirect
google.golang.org/genproto v0.0.0-20200707001353-8e8330bf89df // indirect
google.golang.org/grpc v1.38.0 // indirect
google.golang.org/protobuf v1.28.0 // indirect
gopkg.in/ini.v1 v1.51.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
honnef.co/go/tools v0.2.0 // indirect
mvdan.cc/gofumpt v0.1.1 // indirect
mvdan.cc/interfacer v0.0.0-20180901003855-c20040233aed // indirect
mvdan.cc/lint v0.0.0-20170908181259-adc824a0674b // indirect
mvdan.cc/unparam v0.0.0-20210104141923-aac4ce9116a7 // indirect
golang.org/x/mod v0.8.0 // indirect
golang.org/x/text v0.8.0 // indirect
golang.org/x/tools v0.6.0 // indirect
google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect
google.golang.org/grpc v1.53.0 // indirect
google.golang.org/protobuf v1.30.0 // indirect
)

1068
go.sum

File diff suppressed because it is too large Load Diff

View File

@ -1,21 +0,0 @@
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.

View File

@ -1,154 +0,0 @@
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
}

View File

@ -1,15 +0,0 @@
# 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/

View File

@ -1,150 +0,0 @@
# 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

View File

@ -1,24 +0,0 @@
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

View File

@ -1,21 +0,0 @@
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.

View File

@ -1,75 +0,0 @@
= 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.

View File

@ -1,123 +0,0 @@
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
}
if !areBothErrors(be.X, 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", rawString(be.X), rawString(be.Y))
pass.Report(
analysis.Diagnostic{
Pos: be.Pos(),
Message: fmt.Sprintf("do not compare errors directly %q, use %q instead", oldExpr, newExpr),
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
}
func areBothErrors(x, y ast.Expr, typesInfo *types.Info) bool {
// check that both left and right hand side are not nil
if typesInfo.Types[x].IsNil() || typesInfo.Types[y].IsNil() {
return false
}
// check that both left and right hand side are not io.EOF
if isEOF(x, typesInfo) || isEOF(y, typesInfo) {
return false
}
// check that both left and right hand side are errors
if !isError(x, typesInfo) && !isError(y, typesInfo) {
return false
}
return true
}
func rawString(x ast.Expr) string {
switch t := x.(type) {
case *ast.Ident:
return t.Name
case *ast.SelectorExpr:
return fmt.Sprintf("%s.%s", rawString(t.X), t.Sel.Name)
case *ast.CallExpr:
return fmt.Sprintf("%s()", rawString(t.Fun))
}
return fmt.Sprintf("%s", x)
}

View File

@ -1,74 +0,0 @@
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.ExactString()
}
return ""
}

View File

@ -1,90 +0,0 @@
// 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
}

View File

@ -1,29 +0,0 @@
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

View File

@ -1,109 +0,0 @@
# 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

View File

@ -1,19 +0,0 @@
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.

View File

@ -1,36 +0,0 @@
.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 \
./... || :

View File

@ -1,194 +0,0 @@
# 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).

View File

@ -1,44 +0,0 @@
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

View File

@ -1,24 +0,0 @@
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]
}

View File

@ -1,423 +0,0 @@
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
}

View File

@ -1,115 +0,0 @@
/*
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

View File

@ -1,425 +0,0 @@
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
}

View File

@ -1,10 +0,0 @@
// +build gofuzz
package semver
func Fuzz(data []byte) int {
if _, err := NewVersion(string(data)); err != nil {
return 0
}
return 1
}

View File

@ -1,14 +0,0 @@
# 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

View File

@ -1,674 +0,0 @@
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>.

View File

@ -1,77 +0,0 @@
# 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.

View File

@ -1,241 +0,0 @@
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
}

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017 Alex Kohler
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.

View File

@ -1,267 +0,0 @@
package pkg
import (
"fmt"
"go/ast"
"go/token"
)
type sliceDeclaration struct {
name string
// sType string
genD *ast.GenDecl
}
type returnsVisitor struct {
// flags
simple bool
includeRangeLoops bool
includeForLoops bool
// visitor fields
sliceDeclarations []*sliceDeclaration
preallocHints []Hint
returnsInsideOfLoop bool
arrayTypes []string
}
func Check(files []*ast.File, simple, includeRangeLoops, includeForLoops bool) []Hint {
hints := []Hint{}
for _, f := range files {
retVis := &returnsVisitor{
simple: simple,
includeRangeLoops: includeRangeLoops,
includeForLoops: includeForLoops,
}
ast.Walk(retVis, f)
// if simple is true, then we actually have to check if we had returns
// inside of our loop. Otherwise, we can just report all messages.
if !retVis.simple || !retVis.returnsInsideOfLoop {
hints = append(hints, retVis.preallocHints...)
}
}
return hints
}
func contains(slice []string, item string) bool {
for _, s := range slice {
if s == item {
return true
}
}
return false
}
func (v *returnsVisitor) Visit(node ast.Node) ast.Visitor {
v.sliceDeclarations = nil
v.returnsInsideOfLoop = false
switch n := node.(type) {
case *ast.TypeSpec:
if _, ok := n.Type.(*ast.ArrayType); ok {
if n.Name != nil {
v.arrayTypes = append(v.arrayTypes, n.Name.Name)
}
}
case *ast.FuncDecl:
if n.Body != nil {
for _, stmt := range n.Body.List {
switch s := stmt.(type) {
// Find non pre-allocated slices
case *ast.DeclStmt:
genD, ok := s.Decl.(*ast.GenDecl)
if !ok {
continue
}
if genD.Tok == token.TYPE {
for _, spec := range genD.Specs {
tSpec, ok := spec.(*ast.TypeSpec)
if !ok {
continue
}
if _, ok := tSpec.Type.(*ast.ArrayType); ok {
if tSpec.Name != nil {
v.arrayTypes = append(v.arrayTypes, tSpec.Name.Name)
}
}
}
} else if genD.Tok == token.VAR {
for _, spec := range genD.Specs {
vSpec, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
var isArrType bool
switch val := vSpec.Type.(type) {
case *ast.ArrayType:
isArrType = true
case *ast.Ident:
isArrType = contains(v.arrayTypes, val.Name)
}
if isArrType {
if vSpec.Names != nil {
/*atID, ok := arrayType.Elt.(*ast.Ident)
if !ok {
continue
}*/
// We should handle multiple slices declared on same line e.g. var mySlice1, mySlice2 []uint32
for _, vName := range vSpec.Names {
v.sliceDeclarations = append(v.sliceDeclarations, &sliceDeclaration{name: vName.Name /*sType: atID.Name,*/, genD: genD})
}
}
}
}
}
case *ast.RangeStmt:
if v.includeRangeLoops {
if len(v.sliceDeclarations) == 0 {
continue
}
// Check the value being ranged over and ensure it's not a channel (we cannot offer any recommendations on channel ranges).
rangeIdent, ok := s.X.(*ast.Ident)
if ok && rangeIdent.Obj != nil {
valueSpec, ok := rangeIdent.Obj.Decl.(*ast.ValueSpec)
if ok {
if _, rangeTargetIsChannel := valueSpec.Type.(*ast.ChanType); rangeTargetIsChannel {
continue
}
}
}
if s.Body != nil {
v.handleLoops(s.Body)
}
}
case *ast.ForStmt:
if v.includeForLoops {
if len(v.sliceDeclarations) == 0 {
continue
}
if s.Body != nil {
v.handleLoops(s.Body)
}
}
default:
}
}
}
}
return v
}
// handleLoops is a helper function to share the logic required for both *ast.RangeLoops and *ast.ForLoops
func (v *returnsVisitor) handleLoops(blockStmt *ast.BlockStmt) {
for _, stmt := range blockStmt.List {
switch bodyStmt := stmt.(type) {
case *ast.AssignStmt:
asgnStmt := bodyStmt
for index, expr := range asgnStmt.Rhs {
if index >= len(asgnStmt.Lhs) {
continue
}
lhsIdent, ok := asgnStmt.Lhs[index].(*ast.Ident)
if !ok {
continue
}
callExpr, ok := expr.(*ast.CallExpr)
if !ok {
continue
}
rhsFuncIdent, ok := callExpr.Fun.(*ast.Ident)
if !ok {
continue
}
if rhsFuncIdent.Name != "append" {
continue
}
// e.g., `x = append(x)`
// Pointless, but pre-allocation will not help.
if len(callExpr.Args) < 2 {
continue
}
rhsIdent, ok := callExpr.Args[0].(*ast.Ident)
if !ok {
continue
}
// e.g., `x = append(y, a)`
// This is weird (and maybe a logic error),
// but we cannot recommend pre-allocation.
if lhsIdent.Name != rhsIdent.Name {
continue
}
// e.g., `x = append(x, y...)`
// we should ignore this. Pre-allocating in this case
// is confusing, and is not possible in general.
if callExpr.Ellipsis.IsValid() {
continue
}
for _, sliceDecl := range v.sliceDeclarations {
if sliceDecl.name == lhsIdent.Name {
// This is a potential mark, we just need to make sure there are no returns/continues in the
// range loop.
// now we just need to grab whatever we're ranging over
/*sxIdent, ok := s.X.(*ast.Ident)
if !ok {
continue
}*/
v.preallocHints = append(v.preallocHints, Hint{
Pos: sliceDecl.genD.Pos(),
DeclaredSliceName: sliceDecl.name,
})
}
}
}
case *ast.IfStmt:
ifStmt := bodyStmt
if ifStmt.Body != nil {
for _, ifBodyStmt := range ifStmt.Body.List {
// TODO should probably handle embedded ifs here
switch /*ift :=*/ ifBodyStmt.(type) {
case *ast.BranchStmt, *ast.ReturnStmt:
v.returnsInsideOfLoop = true
default:
}
}
}
default:
}
}
}
// Hint stores the information about an occurrence of a slice that could be
// preallocated.
type Hint struct {
Pos token.Pos
DeclaredSliceName string
}
func (h Hint) String() string {
return fmt.Sprintf("%v: Consider preallocating %v", h.Pos, h.DeclaredSliceName)
}
func (h Hint) StringFromFS(f *token.FileSet) string {
file := f.File(h.Pos)
lineNumber := file.Position(h.Pos).Line
return fmt.Sprintf("%v:%v Consider preallocating %v", file.Name(), lineNumber, h.DeclaredSliceName)
}

View File

@ -1,13 +0,0 @@
Copyright 2019 Andrew Shannon Brown
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.

View File

@ -1,45 +0,0 @@
package forbidigo
// Code generated by github.com/launchdarkly/go-options. DO NOT EDIT.
type ApplyOptionFunc func(c *config) error
func (f ApplyOptionFunc) apply(c *config) error {
return f(c)
}
func newConfig(options ...Option) (config, error) {
var c config
err := applyConfigOptions(&c, options...)
return c, err
}
func applyConfigOptions(c *config, options ...Option) error {
c.ExcludeGodocExamples = true
for _, o := range options {
if err := o.apply(c); err != nil {
return err
}
}
return nil
}
type Option interface {
apply(*config) error
}
// OptionExcludeGodocExamples don't check inside Godoc examples (see https://blog.golang.org/examples)
func OptionExcludeGodocExamples(o bool) ApplyOptionFunc {
return func(c *config) error {
c.ExcludeGodocExamples = o
return nil
}
}
// OptionIgnorePermitDirectives don't check for `permit` directives(for example, in favor of `nolint`)
func OptionIgnorePermitDirectives(o bool) ApplyOptionFunc {
return func(c *config) error {
c.IgnorePermitDirectives = o
return nil
}
}

View File

@ -1,193 +0,0 @@
// forbidigo provides a linter for forbidding the use of specific identifiers
package forbidigo
import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
"log"
"regexp"
"strings"
"github.com/pkg/errors"
)
type Issue interface {
Details() string
Position() token.Position
String() string
}
type UsedIssue struct {
identifier string
pattern string
position token.Position
}
func (a UsedIssue) Details() string {
return fmt.Sprintf("use of `%s` forbidden by pattern `%s`", a.identifier, a.pattern)
}
func (a UsedIssue) Position() token.Position {
return a.position
}
func (a UsedIssue) String() string { return toString(a) }
func toString(i Issue) string {
return fmt.Sprintf("%s at %s", i.Details(), i.Position())
}
type Linter struct {
cfg config
patterns []*regexp.Regexp
}
func DefaultPatterns() []string {
return []string{`^(fmt\.Print(|f|ln)|print|println)$`}
}
//go:generate go-options config
type config struct {
// don't check inside Godoc examples (see https://blog.golang.org/examples)
ExcludeGodocExamples bool `options:",true"`
IgnorePermitDirectives bool // don't check for `permit` directives(for example, in favor of `nolint`)
}
func NewLinter(patterns []string, options ...Option) (*Linter, error) {
cfg, err := newConfig(options...)
if err != nil {
return nil, errors.Wrapf(err, "failed to process options")
}
if len(patterns) == 0 {
patterns = DefaultPatterns()
}
compiledPatterns := make([]*regexp.Regexp, 0, len(patterns))
for _, p := range patterns {
re, err := regexp.Compile(p)
if err != nil {
return nil, fmt.Errorf("unable to compile pattern `%s`: %s", p, err)
}
compiledPatterns = append(compiledPatterns, re)
}
return &Linter{
cfg: cfg,
patterns: compiledPatterns,
}, nil
}
type visitor struct {
cfg config
isTestFile bool // godoc only runs on test files
linter *Linter
comments []*ast.CommentGroup
fset *token.FileSet
issues []Issue
}
func (l *Linter) Run(fset *token.FileSet, nodes ...ast.Node) ([]Issue, error) {
var issues []Issue //nolint:prealloc // we don't know how many there will be
for _, node := range nodes {
var comments []*ast.CommentGroup
isTestFile := false
isWholeFileExample := false
if file, ok := node.(*ast.File); ok {
comments = file.Comments
fileName := fset.Position(file.Pos()).Filename
isTestFile = strings.HasSuffix(fileName, "_test.go")
// From https://blog.golang.org/examples, a "whole file example" is:
// a file that ends in _test.go and contains exactly one example function,
// no test or benchmark functions, and at least one other package-level declaration.
if l.cfg.ExcludeGodocExamples && isTestFile && len(file.Decls) > 1 {
numExamples := 0
numTestsAndBenchmarks := 0
for _, decl := range file.Decls {
funcDecl, isFuncDecl := decl.(*ast.FuncDecl)
// consider only functions, not methods
if !isFuncDecl || funcDecl.Recv != nil || funcDecl.Name == nil {
continue
}
funcName := funcDecl.Name.Name
if strings.HasPrefix(funcName, "Test") || strings.HasPrefix(funcName, "Benchmark") {
numTestsAndBenchmarks++
break // not a whole file example
}
if strings.HasPrefix(funcName, "Example") {
numExamples++
}
}
// if this is a whole file example, skip this node
isWholeFileExample = numExamples == 1 && numTestsAndBenchmarks == 0
}
}
if isWholeFileExample {
continue
}
visitor := visitor{
cfg: l.cfg,
isTestFile: isTestFile,
linter: l,
fset: fset,
comments: comments,
}
ast.Walk(&visitor, node)
issues = append(issues, visitor.issues...)
}
return issues, nil
}
func (v *visitor) Visit(node ast.Node) ast.Visitor {
switch node := node.(type) {
case *ast.FuncDecl:
// don't descend into godoc examples if we are ignoring them
isGodocExample := v.isTestFile && node.Recv == nil && node.Name != nil && strings.HasPrefix(node.Name.Name, "Example")
if isGodocExample && v.cfg.ExcludeGodocExamples {
return nil
}
return v
case *ast.SelectorExpr:
case *ast.Ident:
default:
return v
}
for _, p := range v.linter.patterns {
if p.MatchString(v.textFor(node)) && !v.permit(node) {
v.issues = append(v.issues, UsedIssue{
identifier: v.textFor(node),
pattern: p.String(),
position: v.fset.Position(node.Pos()),
})
}
}
return nil
}
func (v *visitor) textFor(node ast.Node) string {
buf := new(bytes.Buffer)
if err := printer.Fprint(buf, v.fset, node); err != nil {
log.Fatalf("ERROR: unable to print node at %s: %s", v.fset.Position(node.Pos()), err)
}
return buf.String()
}
func (v *visitor) permit(node ast.Node) bool {
if v.cfg.IgnorePermitDirectives {
return false
}
nodePos := v.fset.Position(node.Pos())
var nolint = regexp.MustCompile(fmt.Sprintf(`^//\s?permit:%s\b`, regexp.QuoteMeta(v.textFor(node))))
for _, c := range v.comments {
commentPos := v.fset.Position(c.Pos())
if commentPos.Line == nodePos.Line && len(c.List) > 0 && nolint.MatchString(c.List[0].Text) {
return true
}
}
return false
}

View File

@ -1,13 +0,0 @@
Copyright 2019 Andrew Shannon Brown
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.

View File

@ -1,200 +0,0 @@
// makezero provides a linter for appends to slices initialized with non-zero length.
package makezero
import (
"bytes"
"fmt"
"go/ast"
"go/printer"
"go/token"
"go/types"
"log"
"regexp"
)
type Issue interface {
Details() string
Position() token.Position
String() string
}
type AppendIssue struct {
name string
position token.Position
}
func (a AppendIssue) Details() string {
return fmt.Sprintf("append to slice `%s` with non-zero initialized length", a.name)
}
func (a AppendIssue) Position() token.Position {
return a.position
}
func (a AppendIssue) String() string { return toString(a) }
type MustHaveNonZeroInitLenIssue struct {
name string
position token.Position
}
func (i MustHaveNonZeroInitLenIssue) Details() string {
return fmt.Sprintf("slice `%s` does not have non-zero initial length", i.name)
}
func (i MustHaveNonZeroInitLenIssue) Position() token.Position {
return i.position
}
func (i MustHaveNonZeroInitLenIssue) String() string { return toString(i) }
func toString(i Issue) string {
return fmt.Sprintf("%s at %s", i.Details(), i.Position())
}
type visitor struct {
initLenMustBeZero bool
comments []*ast.CommentGroup // comments to apply during this visit
info *types.Info
nonZeroLengthSliceDecls map[interface{}]struct{}
fset *token.FileSet
issues []Issue
}
type Linter struct {
initLenMustBeZero bool
}
func NewLinter(initialLengthMustBeZero bool) *Linter {
return &Linter{
initLenMustBeZero: initialLengthMustBeZero,
}
}
func (l Linter) Run(fset *token.FileSet, info *types.Info, nodes ...ast.Node) ([]Issue, error) {
var issues []Issue // nolint:prealloc // don't know how many there will be
for _, node := range nodes {
var comments []*ast.CommentGroup
if file, ok := node.(*ast.File); ok {
comments = file.Comments
}
visitor := visitor{
nonZeroLengthSliceDecls: make(map[interface{}]struct{}),
initLenMustBeZero: l.initLenMustBeZero,
info: info,
fset: fset,
comments: comments,
}
ast.Walk(&visitor, node)
issues = append(issues, visitor.issues...)
}
return issues, nil
}
func (v *visitor) Visit(node ast.Node) ast.Visitor {
switch node := node.(type) {
case *ast.CallExpr:
fun, ok := node.Fun.(*ast.Ident)
if !ok || fun.Name != "append" {
break
}
if sliceIdent, ok := node.Args[0].(*ast.Ident); ok &&
v.hasNonZeroInitialLength(sliceIdent) &&
!v.hasNoLintOnSameLine(fun) {
v.issues = append(v.issues, AppendIssue{name: sliceIdent.Name, position: v.fset.Position(fun.Pos())})
}
case *ast.AssignStmt:
for i, right := range node.Rhs {
if right, ok := right.(*ast.CallExpr); ok {
fun, ok := right.Fun.(*ast.Ident)
if !ok || fun.Name != "make" {
continue
}
left := node.Lhs[i]
if len(right.Args) == 2 {
// ignore if not a slice or it has explicit zero length
if !v.isSlice(right.Args[0]) {
break
} else if lit, ok := right.Args[1].(*ast.BasicLit); ok && lit.Kind == token.INT && lit.Value == "0" {
break
}
if v.initLenMustBeZero && !v.hasNoLintOnSameLine(fun) {
v.issues = append(v.issues, MustHaveNonZeroInitLenIssue{
name: v.textFor(left),
position: v.fset.Position(node.Pos()),
})
}
v.recordNonZeroLengthSlices(left)
}
}
}
}
return v
}
func (v *visitor) textFor(node ast.Node) string {
typeBuf := new(bytes.Buffer)
if err := printer.Fprint(typeBuf, v.fset, node); err != nil {
log.Fatalf("ERROR: unable to print type: %s", err)
}
return typeBuf.String()
}
func (v *visitor) hasNonZeroInitialLength(ident *ast.Ident) bool {
if ident.Obj == nil {
log.Printf("WARNING: could not determine with %q at %s is a slice (missing object type)",
ident.Name, v.fset.Position(ident.Pos()).String())
return false
}
_, exists := v.nonZeroLengthSliceDecls[ident.Obj.Decl]
return exists
}
func (v *visitor) recordNonZeroLengthSlices(node ast.Node) {
ident, ok := node.(*ast.Ident)
if !ok {
return
}
if ident.Obj == nil {
return
}
v.nonZeroLengthSliceDecls[ident.Obj.Decl] = struct{}{}
}
func (v *visitor) isSlice(node ast.Node) bool {
// determine type if this is a user-defined type
if ident, ok := node.(*ast.Ident); ok {
obj := ident.Obj
if obj == nil {
if v.info != nil {
_, ok := v.info.ObjectOf(ident).Type().(*types.Slice)
return ok
}
return false
}
spec, ok := obj.Decl.(*ast.TypeSpec)
if !ok {
return false
}
node = spec.Type
}
if node, ok := node.(*ast.ArrayType); ok {
return node.Len == nil // only slices have zero length
}
return false
}
func (v *visitor) hasNoLintOnSameLine(node ast.Node) bool {
var nolint = regexp.MustCompile(`^\s*nozero\b`)
nodePos := v.fset.Position(node.Pos())
for _, c := range v.comments {
commentPos := v.fset.Position(c.Pos())
if commentPos.Line == nodePos.Line && nolint.MatchString(c.Text()) {
return true
}
}
return false
}

View File

@ -1,20 +0,0 @@
Copyright (C) 2013 Blake Mizerany
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.

File diff suppressed because it is too large Load Diff

View File

@ -1,316 +0,0 @@
// Package quantile computes approximate quantiles over an unbounded data
// stream within low memory and CPU bounds.
//
// A small amount of accuracy is traded to achieve the above properties.
//
// Multiple streams can be merged before calling Query to generate a single set
// of results. This is meaningful when the streams represent the same type of
// data. See Merge and Samples.
//
// For more detailed information about the algorithm used, see:
//
// Effective Computation of Biased Quantiles over Data Streams
//
// http://www.cs.rutgers.edu/~muthu/bquant.pdf
package quantile
import (
"math"
"sort"
)
// Sample holds an observed value and meta information for compression. JSON
// tags have been added for convenience.
type Sample struct {
Value float64 `json:",string"`
Width float64 `json:",string"`
Delta float64 `json:",string"`
}
// Samples represents a slice of samples. It implements sort.Interface.
type Samples []Sample
func (a Samples) Len() int { return len(a) }
func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value }
func (a Samples) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
type invariant func(s *stream, r float64) float64
// NewLowBiased returns an initialized Stream for low-biased quantiles
// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but
// error guarantees can still be given even for the lower ranks of the data
// distribution.
//
// The provided epsilon is a relative error, i.e. the true quantile of a value
// returned by a query is guaranteed to be within (1±Epsilon)*Quantile.
//
// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error
// properties.
func NewLowBiased(epsilon float64) *Stream {
ƒ := func(s *stream, r float64) float64 {
return 2 * epsilon * r
}
return newStream(ƒ)
}
// NewHighBiased returns an initialized Stream for high-biased quantiles
// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but
// error guarantees can still be given even for the higher ranks of the data
// distribution.
//
// The provided epsilon is a relative error, i.e. the true quantile of a value
// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile).
//
// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error
// properties.
func NewHighBiased(epsilon float64) *Stream {
ƒ := func(s *stream, r float64) float64 {
return 2 * epsilon * (s.n - r)
}
return newStream(ƒ)
}
// NewTargeted returns an initialized Stream concerned with a particular set of
// quantile values that are supplied a priori. Knowing these a priori reduces
// space and computation time. The targets map maps the desired quantiles to
// their absolute errors, i.e. the true quantile of a value returned by a query
// is guaranteed to be within (Quantile±Epsilon).
//
// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties.
func NewTargeted(targetMap map[float64]float64) *Stream {
// Convert map to slice to avoid slow iterations on a map.
// ƒ is called on the hot path, so converting the map to a slice
// beforehand results in significant CPU savings.
targets := targetMapToSlice(targetMap)
ƒ := func(s *stream, r float64) float64 {
var m = math.MaxFloat64
var f float64
for _, t := range targets {
if t.quantile*s.n <= r {
f = (2 * t.epsilon * r) / t.quantile
} else {
f = (2 * t.epsilon * (s.n - r)) / (1 - t.quantile)
}
if f < m {
m = f
}
}
return m
}
return newStream(ƒ)
}
type target struct {
quantile float64
epsilon float64
}
func targetMapToSlice(targetMap map[float64]float64) []target {
targets := make([]target, 0, len(targetMap))
for quantile, epsilon := range targetMap {
t := target{
quantile: quantile,
epsilon: epsilon,
}
targets = append(targets, t)
}
return targets
}
// Stream computes quantiles for a stream of float64s. It is not thread-safe by
// design. Take care when using across multiple goroutines.
type Stream struct {
*stream
b Samples
sorted bool
}
func newStream(ƒ invariant) *Stream {
x := &stream{ƒ: ƒ}
return &Stream{x, make(Samples, 0, 500), true}
}
// Insert inserts v into the stream.
func (s *Stream) Insert(v float64) {
s.insert(Sample{Value: v, Width: 1})
}
func (s *Stream) insert(sample Sample) {
s.b = append(s.b, sample)
s.sorted = false
if len(s.b) == cap(s.b) {
s.flush()
}
}
// Query returns the computed qth percentiles value. If s was created with
// NewTargeted, and q is not in the set of quantiles provided a priori, Query
// will return an unspecified result.
func (s *Stream) Query(q float64) float64 {
if !s.flushed() {
// Fast path when there hasn't been enough data for a flush;
// this also yields better accuracy for small sets of data.
l := len(s.b)
if l == 0 {
return 0
}
i := int(math.Ceil(float64(l) * q))
if i > 0 {
i -= 1
}
s.maybeSort()
return s.b[i].Value
}
s.flush()
return s.stream.query(q)
}
// Merge merges samples into the underlying streams samples. This is handy when
// merging multiple streams from separate threads, database shards, etc.
//
// ATTENTION: This method is broken and does not yield correct results. The
// underlying algorithm is not capable of merging streams correctly.
func (s *Stream) Merge(samples Samples) {
sort.Sort(samples)
s.stream.merge(samples)
}
// Reset reinitializes and clears the list reusing the samples buffer memory.
func (s *Stream) Reset() {
s.stream.reset()
s.b = s.b[:0]
}
// Samples returns stream samples held by s.
func (s *Stream) Samples() Samples {
if !s.flushed() {
return s.b
}
s.flush()
return s.stream.samples()
}
// Count returns the total number of samples observed in the stream
// since initialization.
func (s *Stream) Count() int {
return len(s.b) + s.stream.count()
}
func (s *Stream) flush() {
s.maybeSort()
s.stream.merge(s.b)
s.b = s.b[:0]
}
func (s *Stream) maybeSort() {
if !s.sorted {
s.sorted = true
sort.Sort(s.b)
}
}
func (s *Stream) flushed() bool {
return len(s.stream.l) > 0
}
type stream struct {
n float64
l []Sample
ƒ invariant
}
func (s *stream) reset() {
s.l = s.l[:0]
s.n = 0
}
func (s *stream) insert(v float64) {
s.merge(Samples{{v, 1, 0}})
}
func (s *stream) merge(samples Samples) {
// TODO(beorn7): This tries to merge not only individual samples, but
// whole summaries. The paper doesn't mention merging summaries at
// all. Unittests show that the merging is inaccurate. Find out how to
// do merges properly.
var r float64
i := 0
for _, sample := range samples {
for ; i < len(s.l); i++ {
c := s.l[i]
if c.Value > sample.Value {
// Insert at position i.
s.l = append(s.l, Sample{})
copy(s.l[i+1:], s.l[i:])
s.l[i] = Sample{
sample.Value,
sample.Width,
math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1),
// TODO(beorn7): How to calculate delta correctly?
}
i++
goto inserted
}
r += c.Width
}
s.l = append(s.l, Sample{sample.Value, sample.Width, 0})
i++
inserted:
s.n += sample.Width
r += sample.Width
}
s.compress()
}
func (s *stream) count() int {
return int(s.n)
}
func (s *stream) query(q float64) float64 {
t := math.Ceil(q * s.n)
t += math.Ceil(s.ƒ(s, t) / 2)
p := s.l[0]
var r float64
for _, c := range s.l[1:] {
r += p.Width
if r+c.Width+c.Delta > t {
return p.Value
}
p = c
}
return p.Value
}
func (s *stream) compress() {
if len(s.l) < 2 {
return
}
x := s.l[len(s.l)-1]
xi := len(s.l) - 1
r := s.n - 1 - x.Width
for i := len(s.l) - 2; i >= 0; i-- {
c := s.l[i]
if c.Width+x.Width+x.Delta <= s.ƒ(s, r) {
x.Width += c.Width
s.l[xi] = x
// Remove element at i.
copy(s.l[i:], s.l[i+1:])
s.l = s.l[:len(s.l)-1]
xi -= 1
} else {
x = c
xi = i
}
r -= c.Width
}
}
func (s *stream) samples() Samples {
samples := make(Samples, len(s.l))
copy(samples, s.l)
return samples
}

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 Bartłomiej Klimczak
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.

View File

@ -1,104 +0,0 @@
package analyzer
import (
"flag"
"go/ast"
"go/token"
"strings"
"golang.org/x/tools/go/analysis"
)
var (
flagSet flag.FlagSet
)
var maxComplexity int
var packageAverage float64
var skipTests bool
func NewAnalyzer() *analysis.Analyzer {
return &analysis.Analyzer{
Name: "cyclop",
Doc: "calculates cyclomatic complexity",
Run: run,
Flags: flagSet,
}
}
func init() {
flagSet.IntVar(&maxComplexity, "maxComplexity", 10, "max complexity the function can have")
flagSet.Float64Var(&packageAverage, "packageAverage", 0, "max avarage complexity in package")
flagSet.BoolVar(&skipTests, "skipTests", false, "should the linter execute on test files as well")
}
func run(pass *analysis.Pass) (interface{}, error) {
var sum, count float64
var pkgName string
var pkgPos token.Pos
for _, f := range pass.Files {
ast.Inspect(f, func(node ast.Node) bool {
f, ok := node.(*ast.FuncDecl)
if !ok {
if node == nil {
return true
}
if file, ok := node.(*ast.File); ok {
pkgName = file.Name.Name
pkgPos = node.Pos()
}
// we check function by function
return true
}
if skipTests && testFunc(f) {
return true
}
count++
comp := complexity(f)
sum += float64(comp)
if comp > maxComplexity {
pass.Reportf(node.Pos(), "calculated cyclomatic complexity for function %s is %d, max is %d", f.Name.Name, comp, maxComplexity)
}
return true
})
}
if packageAverage > 0 {
avg := sum / count
if avg > packageAverage {
pass.Reportf(pkgPos, "the avarage complexity for the package %s is %f, max is %f", pkgName, avg, packageAverage)
}
}
return nil, nil
}
func testFunc(f *ast.FuncDecl) bool {
return strings.HasPrefix(f.Name.Name, "Test")
}
func complexity(fn *ast.FuncDecl) int {
v := complexityVisitor{}
ast.Walk(&v, fn)
return v.Complexity
}
type complexityVisitor struct {
Complexity int
}
func (v *complexityVisitor) Visit(n ast.Node) ast.Visitor {
switch n := n.(type) {
case *ast.FuncDecl, *ast.IfStmt, *ast.ForStmt, *ast.RangeStmt, *ast.CaseClause, *ast.CommClause:
v.Complexity++
case *ast.BinaryExpr:
if n.Op == token.LAND || n.Op == token.LOR {
v.Complexity++
}
}
return v
}

View File

@ -1,70 +0,0 @@
# 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

View File

@ -1,25 +0,0 @@
---
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:

View File

@ -1,21 +0,0 @@
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.

View File

@ -1,126 +0,0 @@
# 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)
* [Short declarations should cuddle only with other short declarations](doc/rules.md#short-declaration-should-cuddle-only-with-other-short-declarations)
* [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)

File diff suppressed because it is too large Load Diff

View File

@ -1,8 +0,0 @@
language: go
go:
- "1.x"
- master
env:
- TAGS=""
- TAGS="-tags purego"
script: go test $TAGS -v ./...

View File

@ -1,22 +0,0 @@
Copyright (c) 2016 Caleb Spare
MIT License
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.

View File

@ -1,67 +0,0 @@
# xxhash
[![GoDoc](https://godoc.org/github.com/cespare/xxhash?status.svg)](https://godoc.org/github.com/cespare/xxhash)
[![Build Status](https://travis-ci.org/cespare/xxhash.svg?branch=master)](https://travis-ci.org/cespare/xxhash)
xxhash is a Go implementation of the 64-bit
[xxHash](http://cyan4973.github.io/xxHash/) algorithm, XXH64. This is a
high-quality hashing algorithm that is much faster than anything in the Go
standard library.
This package provides a straightforward API:
```
func Sum64(b []byte) uint64
func Sum64String(s string) uint64
type Digest struct{ ... }
func New() *Digest
```
The `Digest` type implements hash.Hash64. Its key methods are:
```
func (*Digest) Write([]byte) (int, error)
func (*Digest) WriteString(string) (int, error)
func (*Digest) Sum64() uint64
```
This implementation provides a fast pure-Go implementation and an even faster
assembly implementation for amd64.
## Compatibility
This package is in a module and the latest code is in version 2 of the module.
You need a version of Go with at least "minimal module compatibility" to use
github.com/cespare/xxhash/v2:
* 1.9.7+ for Go 1.9
* 1.10.3+ for Go 1.10
* Go 1.11 or later
I recommend using the latest release of Go.
## Benchmarks
Here are some quick benchmarks comparing the pure-Go and assembly
implementations of Sum64.
| input size | purego | asm |
| --- | --- | --- |
| 5 B | 979.66 MB/s | 1291.17 MB/s |
| 100 B | 7475.26 MB/s | 7973.40 MB/s |
| 4 KB | 17573.46 MB/s | 17602.65 MB/s |
| 10 MB | 17131.46 MB/s | 17142.16 MB/s |
These numbers were generated on Ubuntu 18.04 with an Intel i7-8700K CPU using
the following commands under Go 1.11.2:
```
$ go test -tags purego -benchtime 10s -bench '/xxhash,direct,bytes'
$ go test -benchtime 10s -bench '/xxhash,direct,bytes'
```
## Projects using this package
- [InfluxDB](https://github.com/influxdata/influxdb)
- [Prometheus](https://github.com/prometheus/prometheus)
- [FreeCache](https://github.com/coocood/freecache)

View File

@ -1,236 +0,0 @@
// Package xxhash implements the 64-bit variant of xxHash (XXH64) as described
// at http://cyan4973.github.io/xxHash/.
package xxhash
import (
"encoding/binary"
"errors"
"math/bits"
)
const (
prime1 uint64 = 11400714785074694791
prime2 uint64 = 14029467366897019727
prime3 uint64 = 1609587929392839161
prime4 uint64 = 9650029242287828579
prime5 uint64 = 2870177450012600261
)
// NOTE(caleb): I'm using both consts and vars of the primes. Using consts where
// possible in the Go code is worth a small (but measurable) performance boost
// by avoiding some MOVQs. Vars are needed for the asm and also are useful for
// convenience in the Go code in a few places where we need to intentionally
// avoid constant arithmetic (e.g., v1 := prime1 + prime2 fails because the
// result overflows a uint64).
var (
prime1v = prime1
prime2v = prime2
prime3v = prime3
prime4v = prime4
prime5v = prime5
)
// Digest implements hash.Hash64.
type Digest struct {
v1 uint64
v2 uint64
v3 uint64
v4 uint64
total uint64
mem [32]byte
n int // how much of mem is used
}
// New creates a new Digest that computes the 64-bit xxHash algorithm.
func New() *Digest {
var d Digest
d.Reset()
return &d
}
// Reset clears the Digest's state so that it can be reused.
func (d *Digest) Reset() {
d.v1 = prime1v + prime2
d.v2 = prime2
d.v3 = 0
d.v4 = -prime1v
d.total = 0
d.n = 0
}
// Size always returns 8 bytes.
func (d *Digest) Size() int { return 8 }
// BlockSize always returns 32 bytes.
func (d *Digest) BlockSize() int { return 32 }
// Write adds more data to d. It always returns len(b), nil.
func (d *Digest) Write(b []byte) (n int, err error) {
n = len(b)
d.total += uint64(n)
if d.n+n < 32 {
// This new data doesn't even fill the current block.
copy(d.mem[d.n:], b)
d.n += n
return
}
if d.n > 0 {
// Finish off the partial block.
copy(d.mem[d.n:], b)
d.v1 = round(d.v1, u64(d.mem[0:8]))
d.v2 = round(d.v2, u64(d.mem[8:16]))
d.v3 = round(d.v3, u64(d.mem[16:24]))
d.v4 = round(d.v4, u64(d.mem[24:32]))
b = b[32-d.n:]
d.n = 0
}
if len(b) >= 32 {
// One or more full blocks left.
nw := writeBlocks(d, b)
b = b[nw:]
}
// Store any remaining partial block.
copy(d.mem[:], b)
d.n = len(b)
return
}
// Sum appends the current hash to b and returns the resulting slice.
func (d *Digest) Sum(b []byte) []byte {
s := d.Sum64()
return append(
b,
byte(s>>56),
byte(s>>48),
byte(s>>40),
byte(s>>32),
byte(s>>24),
byte(s>>16),
byte(s>>8),
byte(s),
)
}
// Sum64 returns the current hash.
func (d *Digest) Sum64() uint64 {
var h uint64
if d.total >= 32 {
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
h = mergeRound(h, v1)
h = mergeRound(h, v2)
h = mergeRound(h, v3)
h = mergeRound(h, v4)
} else {
h = d.v3 + prime5
}
h += d.total
i, end := 0, d.n
for ; i+8 <= end; i += 8 {
k1 := round(0, u64(d.mem[i:i+8]))
h ^= k1
h = rol27(h)*prime1 + prime4
}
if i+4 <= end {
h ^= uint64(u32(d.mem[i:i+4])) * prime1
h = rol23(h)*prime2 + prime3
i += 4
}
for i < end {
h ^= uint64(d.mem[i]) * prime5
h = rol11(h) * prime1
i++
}
h ^= h >> 33
h *= prime2
h ^= h >> 29
h *= prime3
h ^= h >> 32
return h
}
const (
magic = "xxh\x06"
marshaledSize = len(magic) + 8*5 + 32
)
// MarshalBinary implements the encoding.BinaryMarshaler interface.
func (d *Digest) MarshalBinary() ([]byte, error) {
b := make([]byte, 0, marshaledSize)
b = append(b, magic...)
b = appendUint64(b, d.v1)
b = appendUint64(b, d.v2)
b = appendUint64(b, d.v3)
b = appendUint64(b, d.v4)
b = appendUint64(b, d.total)
b = append(b, d.mem[:d.n]...)
b = b[:len(b)+len(d.mem)-d.n]
return b, nil
}
// UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.
func (d *Digest) UnmarshalBinary(b []byte) error {
if len(b) < len(magic) || string(b[:len(magic)]) != magic {
return errors.New("xxhash: invalid hash state identifier")
}
if len(b) != marshaledSize {
return errors.New("xxhash: invalid hash state size")
}
b = b[len(magic):]
b, d.v1 = consumeUint64(b)
b, d.v2 = consumeUint64(b)
b, d.v3 = consumeUint64(b)
b, d.v4 = consumeUint64(b)
b, d.total = consumeUint64(b)
copy(d.mem[:], b)
b = b[len(d.mem):]
d.n = int(d.total % uint64(len(d.mem)))
return nil
}
func appendUint64(b []byte, x uint64) []byte {
var a [8]byte
binary.LittleEndian.PutUint64(a[:], x)
return append(b, a[:]...)
}
func consumeUint64(b []byte) ([]byte, uint64) {
x := u64(b)
return b[8:], x
}
func u64(b []byte) uint64 { return binary.LittleEndian.Uint64(b) }
func u32(b []byte) uint32 { return binary.LittleEndian.Uint32(b) }
func round(acc, input uint64) uint64 {
acc += input * prime2
acc = rol31(acc)
acc *= prime1
return acc
}
func mergeRound(acc, val uint64) uint64 {
val = round(0, val)
acc ^= val
acc = acc*prime1 + prime4
return acc
}
func rol1(x uint64) uint64 { return bits.RotateLeft64(x, 1) }
func rol7(x uint64) uint64 { return bits.RotateLeft64(x, 7) }
func rol11(x uint64) uint64 { return bits.RotateLeft64(x, 11) }
func rol12(x uint64) uint64 { return bits.RotateLeft64(x, 12) }
func rol18(x uint64) uint64 { return bits.RotateLeft64(x, 18) }
func rol23(x uint64) uint64 { return bits.RotateLeft64(x, 23) }
func rol27(x uint64) uint64 { return bits.RotateLeft64(x, 27) }
func rol31(x uint64) uint64 { return bits.RotateLeft64(x, 31) }

View File

@ -1,13 +0,0 @@
// +build !appengine
// +build gc
// +build !purego
package xxhash
// Sum64 computes the 64-bit xxHash digest of b.
//
//go:noescape
func Sum64(b []byte) uint64
//go:noescape
func writeBlocks(d *Digest, b []byte) int

View File

@ -1,215 +0,0 @@
// +build !appengine
// +build gc
// +build !purego
#include "textflag.h"
// Register allocation:
// AX h
// CX pointer to advance through b
// DX n
// BX loop end
// R8 v1, k1
// R9 v2
// R10 v3
// R11 v4
// R12 tmp
// R13 prime1v
// R14 prime2v
// R15 prime4v
// round reads from and advances the buffer pointer in CX.
// It assumes that R13 has prime1v and R14 has prime2v.
#define round(r) \
MOVQ (CX), R12 \
ADDQ $8, CX \
IMULQ R14, R12 \
ADDQ R12, r \
ROLQ $31, r \
IMULQ R13, r
// mergeRound applies a merge round on the two registers acc and val.
// It assumes that R13 has prime1v, R14 has prime2v, and R15 has prime4v.
#define mergeRound(acc, val) \
IMULQ R14, val \
ROLQ $31, val \
IMULQ R13, val \
XORQ val, acc \
IMULQ R13, acc \
ADDQ R15, acc
// func Sum64(b []byte) uint64
TEXT ·Sum64(SB), NOSPLIT, $0-32
// Load fixed primes.
MOVQ ·prime1v(SB), R13
MOVQ ·prime2v(SB), R14
MOVQ ·prime4v(SB), R15
// Load slice.
MOVQ b_base+0(FP), CX
MOVQ b_len+8(FP), DX
LEAQ (CX)(DX*1), BX
// The first loop limit will be len(b)-32.
SUBQ $32, BX
// Check whether we have at least one block.
CMPQ DX, $32
JLT noBlocks
// Set up initial state (v1, v2, v3, v4).
MOVQ R13, R8
ADDQ R14, R8
MOVQ R14, R9
XORQ R10, R10
XORQ R11, R11
SUBQ R13, R11
// Loop until CX > BX.
blockLoop:
round(R8)
round(R9)
round(R10)
round(R11)
CMPQ CX, BX
JLE blockLoop
MOVQ R8, AX
ROLQ $1, AX
MOVQ R9, R12
ROLQ $7, R12
ADDQ R12, AX
MOVQ R10, R12
ROLQ $12, R12
ADDQ R12, AX
MOVQ R11, R12
ROLQ $18, R12
ADDQ R12, AX
mergeRound(AX, R8)
mergeRound(AX, R9)
mergeRound(AX, R10)
mergeRound(AX, R11)
JMP afterBlocks
noBlocks:
MOVQ ·prime5v(SB), AX
afterBlocks:
ADDQ DX, AX
// Right now BX has len(b)-32, and we want to loop until CX > len(b)-8.
ADDQ $24, BX
CMPQ CX, BX
JG fourByte
wordLoop:
// Calculate k1.
MOVQ (CX), R8
ADDQ $8, CX
IMULQ R14, R8
ROLQ $31, R8
IMULQ R13, R8
XORQ R8, AX
ROLQ $27, AX
IMULQ R13, AX
ADDQ R15, AX
CMPQ CX, BX
JLE wordLoop
fourByte:
ADDQ $4, BX
CMPQ CX, BX
JG singles
MOVL (CX), R8
ADDQ $4, CX
IMULQ R13, R8
XORQ R8, AX
ROLQ $23, AX
IMULQ R14, AX
ADDQ ·prime3v(SB), AX
singles:
ADDQ $4, BX
CMPQ CX, BX
JGE finalize
singlesLoop:
MOVBQZX (CX), R12
ADDQ $1, CX
IMULQ ·prime5v(SB), R12
XORQ R12, AX
ROLQ $11, AX
IMULQ R13, AX
CMPQ CX, BX
JL singlesLoop
finalize:
MOVQ AX, R12
SHRQ $33, R12
XORQ R12, AX
IMULQ R14, AX
MOVQ AX, R12
SHRQ $29, R12
XORQ R12, AX
IMULQ ·prime3v(SB), AX
MOVQ AX, R12
SHRQ $32, R12
XORQ R12, AX
MOVQ AX, ret+24(FP)
RET
// writeBlocks uses the same registers as above except that it uses AX to store
// the d pointer.
// func writeBlocks(d *Digest, b []byte) int
TEXT ·writeBlocks(SB), NOSPLIT, $0-40
// Load fixed primes needed for round.
MOVQ ·prime1v(SB), R13
MOVQ ·prime2v(SB), R14
// Load slice.
MOVQ b_base+8(FP), CX
MOVQ b_len+16(FP), DX
LEAQ (CX)(DX*1), BX
SUBQ $32, BX
// Load vN from d.
MOVQ d+0(FP), AX
MOVQ 0(AX), R8 // v1
MOVQ 8(AX), R9 // v2
MOVQ 16(AX), R10 // v3
MOVQ 24(AX), R11 // v4
// We don't need to check the loop condition here; this function is
// always called with at least one block of data to process.
blockLoop:
round(R8)
round(R9)
round(R10)
round(R11)
CMPQ CX, BX
JLE blockLoop
// Copy vN back to d.
MOVQ R8, 0(AX)
MOVQ R9, 8(AX)
MOVQ R10, 16(AX)
MOVQ R11, 24(AX)
// The number of bytes written is CX minus the old base pointer.
SUBQ b_base+8(FP), CX
MOVQ CX, ret+32(FP)
RET

View File

@ -1,76 +0,0 @@
// +build !amd64 appengine !gc purego
package xxhash
// Sum64 computes the 64-bit xxHash digest of b.
func Sum64(b []byte) uint64 {
// A simpler version would be
// d := New()
// d.Write(b)
// return d.Sum64()
// but this is faster, particularly for small inputs.
n := len(b)
var h uint64
if n >= 32 {
v1 := prime1v + prime2
v2 := prime2
v3 := uint64(0)
v4 := -prime1v
for len(b) >= 32 {
v1 = round(v1, u64(b[0:8:len(b)]))
v2 = round(v2, u64(b[8:16:len(b)]))
v3 = round(v3, u64(b[16:24:len(b)]))
v4 = round(v4, u64(b[24:32:len(b)]))
b = b[32:len(b):len(b)]
}
h = rol1(v1) + rol7(v2) + rol12(v3) + rol18(v4)
h = mergeRound(h, v1)
h = mergeRound(h, v2)
h = mergeRound(h, v3)
h = mergeRound(h, v4)
} else {
h = prime5
}
h += uint64(n)
i, end := 0, len(b)
for ; i+8 <= end; i += 8 {
k1 := round(0, u64(b[i:i+8:len(b)]))
h ^= k1
h = rol27(h)*prime1 + prime4
}
if i+4 <= end {
h ^= uint64(u32(b[i:i+4:len(b)])) * prime1
h = rol23(h)*prime2 + prime3
i += 4
}
for ; i < end; i++ {
h ^= uint64(b[i]) * prime5
h = rol11(h) * prime1
}
h ^= h >> 33
h *= prime2
h ^= h >> 29
h *= prime3
h ^= h >> 32
return h
}
func writeBlocks(d *Digest, b []byte) int {
v1, v2, v3, v4 := d.v1, d.v2, d.v3, d.v4
n := len(b)
for len(b) >= 32 {
v1 = round(v1, u64(b[0:8:len(b)]))
v2 = round(v2, u64(b[8:16:len(b)]))
v3 = round(v3, u64(b[16:24:len(b)]))
v4 = round(v4, u64(b[24:32:len(b)]))
b = b[32:len(b):len(b)]
}
d.v1, d.v2, d.v3, d.v4 = v1, v2, v3, v4
return n - len(b)
}

View File

@ -1,15 +0,0 @@
// +build appengine
// This file contains the safe implementations of otherwise unsafe-using code.
package xxhash
// Sum64String computes the 64-bit xxHash digest of s.
func Sum64String(s string) uint64 {
return Sum64([]byte(s))
}
// WriteString adds more data to d. It always returns len(s), nil.
func (d *Digest) WriteString(s string) (n int, err error) {
return d.Write([]byte(s))
}

View File

@ -1,46 +0,0 @@
// +build !appengine
// This file encapsulates usage of unsafe.
// xxhash_safe.go contains the safe implementations.
package xxhash
import (
"reflect"
"unsafe"
)
// Notes:
//
// See https://groups.google.com/d/msg/golang-nuts/dcjzJy-bSpw/tcZYBzQqAQAJ
// for some discussion about these unsafe conversions.
//
// In the future it's possible that compiler optimizations will make these
// unsafe operations unnecessary: https://golang.org/issue/2205.
//
// Both of these wrapper functions still incur function call overhead since they
// will not be inlined. We could write Go/asm copies of Sum64 and Digest.Write
// for strings to squeeze out a bit more speed. Mid-stack inlining should
// eventually fix this.
// Sum64String computes the 64-bit xxHash digest of s.
// It may be faster than Sum64([]byte(s)) by avoiding a copy.
func Sum64String(s string) uint64 {
var b []byte
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
bh.Len = len(s)
bh.Cap = len(s)
return Sum64(b)
}
// WriteString adds more data to d. It always returns len(s), nil.
// It may be faster than Write([]byte(s)) by avoiding a copy.
func (d *Digest) WriteString(s string) (n int, err error) {
var b []byte
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
bh.Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
bh.Len = len(s)
bh.Cap = len(s)
return d.Write(b)
}

View File

@ -1 +0,0 @@
/durationcheck

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -1,5 +0,0 @@
build:
@GO111MODULE=on go build -ldflags '-s -w' -o durationcheck ./cmd/durationcheck/main.go
install:
@GO111MODULE=on go install -ldflags '-s -w' ./cmd/durationcheck

View File

@ -1,48 +0,0 @@
[![CircleCI](https://circleci.com/gh/charithe/durationcheck.svg?style=svg)](https://circleci.com/gh/charithe/durationcheck)
Duration Check
===============
A Go linter to detect cases where two `time.Duration` values are being multiplied in possibly erroneous ways.
For example, consider the following (highly contrived) function:
```go
func waitFor(someDuration time.Duration) {
timeToWait := someDuration * time.Second
time.Sleep(timeToWait)
}
```
Although the above code would compile without any errors, its runtime behaviour would almost certainly be incorrect.
A caller would reasonably expect `waitFor(5 * time.Seconds)` to wait for ~5 seconds but they would actually end up
waiting for ~1,388,889 hours.
The above example is just for illustration purposes only. The problem is glaringly obvious in such a simple function
and even the greenest Gopher would discover the issue immediately. However, imagine a much more complicated function
with many more lines and it is not inconceivable that such logic errors could go unnoticed.
See the [test cases](testdata/src/a/a.go) for more examples of the types of errors detected by the linter.
Installation
-------------
Requires Go 1.11 or above.
```
go get -u github.com/charithe/durationcheck/cmd/durationcheck
```
Usage
-----
Invoke `durationcheck` with your package name
```
durationcheck ./...
# or
durationcheck github.com/you/yourproject/...
```

View File

@ -1,188 +0,0 @@
package durationcheck
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/token"
"go/types"
"log"
"os"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var Analyzer = &analysis.Analyzer{
Name: "durationcheck",
Doc: "check for two durations multiplied together",
Run: run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
func run(pass *analysis.Pass) (interface{}, error) {
// if the package does not import time, it can be skipped from analysis
if !hasImport(pass.Pkg, "time") {
return nil, nil
}
inspect := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeTypes := []ast.Node{
(*ast.BinaryExpr)(nil),
}
inspect.Preorder(nodeTypes, check(pass))
return nil, nil
}
func hasImport(pkg *types.Package, importPath string) bool {
for _, imp := range pkg.Imports() {
if imp.Path() == importPath {
return true
}
}
return false
}
// check contains the logic for checking that time.Duration is used correctly in the code being analysed
func check(pass *analysis.Pass) func(ast.Node) {
return func(node ast.Node) {
expr := node.(*ast.BinaryExpr)
// we are only interested in multiplication
if expr.Op != token.MUL {
return
}
// get the types of the two operands
x, xOK := pass.TypesInfo.Types[expr.X]
y, yOK := pass.TypesInfo.Types[expr.Y]
if !xOK || !yOK {
return
}
if isDuration(x.Type) && isDuration(y.Type) {
// check that both sides are acceptable expressions
if isUnacceptableExpr(pass, expr.X) && isUnacceptableExpr(pass, expr.Y) {
pass.Reportf(expr.Pos(), "Multiplication of durations: `%s`", formatNode(expr))
}
}
}
}
func isDuration(x types.Type) bool {
return x.String() == "time.Duration" || x.String() == "*time.Duration"
}
// isUnacceptableExpr returns true if the argument is not an acceptable time.Duration expression
func isUnacceptableExpr(pass *analysis.Pass, expr ast.Expr) bool {
switch e := expr.(type) {
case *ast.BasicLit:
return false
case *ast.Ident:
return !isAcceptableNestedExpr(pass, e)
case *ast.CallExpr:
return !isAcceptableCast(pass, e)
case *ast.BinaryExpr:
return !isAcceptableNestedExpr(pass, e)
case *ast.UnaryExpr:
return !isAcceptableNestedExpr(pass, e)
case *ast.SelectorExpr:
return !isAcceptableNestedExpr(pass, e)
case *ast.StarExpr:
return !isAcceptableNestedExpr(pass, e)
case *ast.ParenExpr:
return !isAcceptableNestedExpr(pass, e)
case *ast.IndexExpr:
return !isAcceptableNestedExpr(pass, e)
default:
return true
}
}
// isAcceptableCast returns true if the argument is an acceptable expression cast to time.Duration
func isAcceptableCast(pass *analysis.Pass, e *ast.CallExpr) bool {
// check that there's a single argument
if len(e.Args) != 1 {
return false
}
// check that the argument is acceptable
if !isAcceptableNestedExpr(pass, e.Args[0]) {
return false
}
// check for time.Duration cast
selector, ok := e.Fun.(*ast.SelectorExpr)
if !ok {
return false
}
return isDurationCast(selector)
}
func isDurationCast(selector *ast.SelectorExpr) bool {
pkg, ok := selector.X.(*ast.Ident)
if !ok {
return false
}
if pkg.Name != "time" {
return false
}
return selector.Sel.Name == "Duration"
}
func isAcceptableNestedExpr(pass *analysis.Pass, n ast.Expr) bool {
switch e := n.(type) {
case *ast.BasicLit:
return true
case *ast.BinaryExpr:
return isAcceptableNestedExpr(pass, e.X) && isAcceptableNestedExpr(pass, e.Y)
case *ast.UnaryExpr:
return isAcceptableNestedExpr(pass, e.X)
case *ast.Ident:
return isAcceptableIdent(pass, e)
case *ast.CallExpr:
t := pass.TypesInfo.TypeOf(e)
return !isDuration(t)
case *ast.SelectorExpr:
return isAcceptableNestedExpr(pass, e.X) && isAcceptableIdent(pass, e.Sel)
case *ast.StarExpr:
return isAcceptableNestedExpr(pass, e.X)
case *ast.ParenExpr:
return isAcceptableNestedExpr(pass, e.X)
case *ast.IndexExpr:
t := pass.TypesInfo.TypeOf(e)
return !isDuration(t)
default:
return false
}
}
func isAcceptableIdent(pass *analysis.Pass, ident *ast.Ident) bool {
obj := pass.TypesInfo.ObjectOf(ident)
return !isDuration(obj.Type())
}
func formatNode(node ast.Node) string {
buf := new(bytes.Buffer)
if err := format.Node(buf, token.NewFileSet(), node); err != nil {
log.Printf("Error formatting expression: %v", err)
return ""
}
return buf.String()
}
func printAST(msg string, node ast.Node) {
fmt.Printf(">>> %s:\n%s\n\n\n", msg, formatNode(node))
ast.Fprint(os.Stdout, nil, node, nil)
fmt.Println("--------------")
}

View File

@ -1,3 +0,0 @@
*.test
*.out
.devcontainer/

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2021 Salvador Cavadini
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.

View File

@ -1,52 +0,0 @@
# garif
A GO package to create and manipulate SARIF logs.
SARIF, from _Static Analysis Results Interchange Format_, is a standard JSON-based format for the output of static analysis tools defined and promoted by [OASIS](https://www.oasis-open.org/).
Current supported version of the standard is [SARIF-v2.1.0](https://docs.oasis-open.org/sarif/sarif/v2.1.0/csprd01/sarif-v2.1.0-csprd01.html
).
## Usage
The package provides access to every element of the SARIF model, therefore you are free to manipulate it at every detail.
The package also provides constructors functions (`New...`) and decorators methods (`With...`) that simplify the creation of SARIF files for common use cases.
Using these constructors and decorators we can easily create the example SARIF file of the [Microsoft SARIF pages](https://github.com/microsoft/sarif-tutorials/blob/master/docs/1-Introduction.md)
```go
import to `github.com/chavacava/garif`
// ...
rule := garif.NewRule("no-unused-vars").
WithHelpUri("https://eslint.org/docs/rules/no-unused-vars").
WithShortDescription("disallow unused variables").
WithProperties("category", "Variables")
driver := garif.NewDriver("ESLint").
WithInformationUri("https://eslint.org").
WithRules(rule)
run := garif.NewRun(NewTool(driver)).
WithArtifactsURIs("file:///C:/dev/sarif/sarif-tutorials/samples/Introduction/simple-example.js")
run.WithResult(rule.Id, "'x' is assigned a value but never used.", "file:///C:/dev/sarif/sarif-tutorials/samples/Introduction/simple-example.js", 1, 5)
logFile := garif.NewLogFile([]*Run{run}, Version210)
logFile.Write(os.Stdout)
```
## Why this package?
This package was initiated during my works on adding to [`revive`](https://github.com/mgechev/revive) a SARIF output formatter.
I've tried to use [go-sarif](https://github.com/owenrumney/go-sarif) by [Owen Rumney](https://github.com/owenrumney) but it is too focused in the use case of the static analyzer [tfsec](https://tfsec.dev) so I've decided to create a package flexible enough to generate SARIF files in broader cases.
## More information about SARIF
For more information about SARIF, you can visit the [Oasis Open](https://www.oasis-open.org/committees/tc_home.php?wg_abbrev=sarif) site.
## Contributing
Of course, contributions are welcome!

View File

@ -1,338 +0,0 @@
package garif
// NewAddress creates a valid Address
func NewAddress() *Address {
return &Address{}
}
// NewArtifact creates a valid Artifact
func NewArtifact() *Artifact {
return &Artifact{}
}
// NewArtifactChange creates a valid ArtifactChange
func NewArtifactChange(location *ArtifactLocation, replacements ...*Replacement) *ArtifactChange {
return &ArtifactChange{
ArtifactLocation: location,
Replacements: replacements,
}
}
// NewArtifactContent creates a valid ArtifactContent
func NewArtifactContent() *ArtifactContent {
return &ArtifactContent{}
}
// NewArtifactLocation creates a valid ArtifactLocation
func NewArtifactLocation() *ArtifactLocation {
return &ArtifactLocation{}
}
// NewAttachment creates a valid Attachment
func NewAttachment(location *ArtifactLocation) *Attachment {
return &Attachment{ArtifactLocation: location}
}
// NewCodeFlow creates a valid CodeFlow
func NewCodeFlow(threadFlows ...*ThreadFlow) *CodeFlow {
return &CodeFlow{ThreadFlows: threadFlows}
}
// NewConfigurationOverride creates a valid ConfigurationOverride
func NewConfigurationOverride(configuration *ReportingConfiguration, descriptor *ReportingDescriptorReference) *ConfigurationOverride {
return &ConfigurationOverride{
Configuration: configuration,
Descriptor: descriptor,
}
}
// NewConversion creates a valid Conversion
func NewConversion(tool *Tool) *Conversion {
return &Conversion{Tool: tool}
}
// NewEdge creates a valid Edge
func NewEdge(id, sourceNodeId, targetNodeId string) *Edge {
return &Edge{
Id: id,
SourceNodeId: sourceNodeId,
TargetNodeId: targetNodeId,
}
}
// NewEdgeTraversal creates a valid EdgeTraversal
func NewEdgeTraversal(edgeId string) *EdgeTraversal {
return &EdgeTraversal{
EdgeId: edgeId,
}
}
// NewException creates a valid Exception
func NewException() *Exception {
return &Exception{}
}
// NewExternalProperties creates a valid ExternalProperties
func NewExternalProperties() *ExternalProperties {
return &ExternalProperties{}
}
// NewExternalPropertyFileReference creates a valid ExternalPropertyFileReference
func NewExternalPropertyFileReference() *ExternalPropertyFileReference {
return &ExternalPropertyFileReference{}
}
// NewExternalPropertyFileReferences creates a valid ExternalPropertyFileReferences
func NewExternalPropertyFileReferences() *ExternalPropertyFileReferences {
return &ExternalPropertyFileReferences{}
}
// NewFix creates a valid Fix
func NewFix(artifactChanges ...*ArtifactChange) *Fix {
return &Fix{
ArtifactChanges: artifactChanges,
}
}
// NewGraph creates a valid Graph
func NewGraph() *Graph {
return &Graph{}
}
// NewGraphTraversal creates a valid GraphTraversal
func NewGraphTraversal() *GraphTraversal {
return &GraphTraversal{}
}
// NewInvocation creates a valid Invocation
func NewInvocation(executionSuccessful bool) *Invocation {
return &Invocation{
ExecutionSuccessful: executionSuccessful,
}
}
// NewLocation creates a valid Location
func NewLocation() *Location {
return &Location{}
}
// NewLocationRelationship creates a valid LocationRelationship
func NewLocationRelationship(target int) *LocationRelationship {
return &LocationRelationship{
Target: target,
}
}
type LogFileVersion string
const Version210 LogFileVersion = "2.1.0"
// NewLogFile creates a valid LogFile
func NewLogFile(runs []*Run, version LogFileVersion) *LogFile {
return &LogFile{
Runs: runs,
Version: version,
}
}
// NewLogicalLocation creates a valid LogicalLocation
func NewLogicalLocation() *LogicalLocation {
return &LogicalLocation{}
}
// NewMessage creates a valid Message
func NewMessage() *Message {
return &Message{}
}
// NewMessageFromText creates a valid Message with the given text
func NewMessageFromText(text string) *Message {
return &Message{
Text: text,
}
}
// NewMultiformatMessageString creates a valid MultiformatMessageString
func NewMultiformatMessageString(text string) *MultiformatMessageString {
return &MultiformatMessageString{
Text: text,
}
}
// NewNode creates a valid Node
func NewNode(id string) *Node {
return &Node{
Id: id,
}
}
// NewNotification creates a valid Notification
func NewNotification(message *Message) *Notification {
return &Notification{
Message: message,
}
}
// NewPhysicalLocation creates a valid PhysicalLocation
func NewPhysicalLocation() *PhysicalLocation {
return &PhysicalLocation{}
}
// NewPropertyBag creates a valid PropertyBag
func NewPropertyBag() *PropertyBag {
return &PropertyBag{}
}
// NewRectangle creates a valid Rectangle
func NewRectangle() *Rectangle {
return &Rectangle{}
}
// NewRegion creates a valid Region
func NewRegion() *Region {
return &Region{}
}
// NewReplacement creates a valid Replacement
func NewReplacement(deletedRegion *Region) *Replacement {
return &Replacement{
DeletedRegion: deletedRegion,
}
}
// NewReportingConfiguration creates a valid ReportingConfiguration
func NewReportingConfiguration() *ReportingConfiguration {
return &ReportingConfiguration{}
}
// NewReportingDescriptor creates a valid ReportingDescriptor
func NewReportingDescriptor(id string) *ReportingDescriptor {
return &ReportingDescriptor{
Id: id,
}
}
// NewRule is an alias for NewReportingDescriptor
func NewRule(id string) *ReportingDescriptor {
return NewReportingDescriptor(id)
}
// NewReportingDescriptorReference creates a valid ReportingDescriptorReference
func NewReportingDescriptorReference() *ReportingDescriptorReference {
return &ReportingDescriptorReference{}
}
// NewReportingDescriptorRelationship creates a valid ReportingDescriptorRelationship
func NewReportingDescriptorRelationship(target *ReportingDescriptorReference) *ReportingDescriptorRelationship {
return &ReportingDescriptorRelationship{
Target: target,
}
}
// NewResult creates a valid Result
func NewResult(message *Message) *Result {
return &Result{
Message: message,
}
}
// NewResultProvenance creates a valid ResultProvenance
func NewResultProvenance() *ResultProvenance {
return &ResultProvenance{}
}
// NewRun creates a valid Run
func NewRun(tool *Tool) *Run {
return &Run{
Tool: tool,
}
}
// NewRunAutomationDetails creates a valid RunAutomationDetails
func NewRunAutomationDetails() *RunAutomationDetails {
return &RunAutomationDetails{}
}
// New creates a valid
func NewSpecialLocations() *SpecialLocations {
return &SpecialLocations{}
}
// NewStack creates a valid Stack
func NewStack(frames ...*StackFrame) *Stack {
return &Stack{
Frames: frames,
}
}
// NewStackFrame creates a valid StackFrame
func NewStackFrame() *StackFrame {
return &StackFrame{}
}
// NewSuppression creates a valid Suppression
func NewSuppression(kind string) *Suppression {
return &Suppression{
Kind: kind,
}
}
// NewThreadFlow creates a valid ThreadFlow
func NewThreadFlow(locations []*ThreadFlowLocation) *ThreadFlow {
return &ThreadFlow{
Locations: locations,
}
}
// NewThreadFlowLocation creates a valid ThreadFlowLocation
func NewThreadFlowLocation() *ThreadFlowLocation {
return &ThreadFlowLocation{}
}
// NewTool creates a valid Tool
func NewTool(driver *ToolComponent) *Tool {
return &Tool{
Driver: driver,
}
}
// NewToolComponent creates a valid ToolComponent
func NewToolComponent(name string) *ToolComponent {
return &ToolComponent{
Name: name,
}
}
// NewDriver is an alias for NewToolComponent
func NewDriver(name string) *ToolComponent {
return NewToolComponent(name)
}
// NewToolComponentReference creates a valid ToolComponentReference
func NewToolComponentReference() *ToolComponentReference {
return &ToolComponentReference{}
}
// NewTranslationMetadata creates a valid TranslationMetadata
func NewTranslationMetadata(name string) *TranslationMetadata {
return &TranslationMetadata{
Name: name,
}
}
// NewVersionControlDetails creates a valid VersionControlDetails
func NewVersionControlDetails(repositoryUri string) *VersionControlDetails {
return &VersionControlDetails{
RepositoryUri: repositoryUri,
}
}
// NewWebRequest creates a valid WebRequest
func NewWebRequest() *WebRequest {
return &WebRequest{}
}
// NewWebResponse creates a valid WebResponse
func NewWebResponse() *WebResponse {
return &WebResponse{}
}

View File

@ -1,94 +0,0 @@
package garif
// WithLineColumn sets a physical location with the given line and column
func (l *Location) WithLineColumn(line, column int) *Location {
if l.PhysicalLocation == nil {
l.PhysicalLocation = NewPhysicalLocation()
}
l.PhysicalLocation.Region = NewRegion()
l.PhysicalLocation.Region.StartLine = line
l.PhysicalLocation.Region.StartColumn = column
return l
}
// WithURI sets a physical location with the given URI
func (l *Location) WithURI(uri string) *Location {
if l.PhysicalLocation == nil {
l.PhysicalLocation = NewPhysicalLocation()
}
l.PhysicalLocation.ArtifactLocation = NewArtifactLocation()
l.PhysicalLocation.ArtifactLocation.Uri = uri
return l
}
// WithKeyValue sets (overwrites) the value of the given key
func (b PropertyBag) WithKeyValue(key string, value interface{}) PropertyBag {
b[key] = value
return b
}
// WithHelpUri sets the help URI for this ReportingDescriptor
func (r *ReportingDescriptor) WithHelpUri(uri string) *ReportingDescriptor {
r.HelpUri = uri
return r
}
// WithProperties adds the key & value to the properties of this ReportingDescriptor
func (r *ReportingDescriptor) WithProperties(key string, value interface{}) *ReportingDescriptor {
if r.Properties == nil {
r.Properties = NewPropertyBag()
}
r.Properties.WithKeyValue(key, value)
return r
}
// WithArtifactsURIs adds the given URI as artifacts of this Run
func (r *Run) WithArtifactsURIs(uris ...string) *Run {
if r.Artifacts == nil {
r.Artifacts = []*Artifact{}
}
for _, uri := range uris {
a := NewArtifact()
a.Location = NewArtifactLocation()
a.Location.Uri = uri
r.Artifacts = append(r.Artifacts, a)
}
return r
}
// WithResult adds a result to this Run
func (r *Run) WithResult(ruleId string, message string, uri string, line int, column int) *Run {
if r.Results == nil {
r.Results = []*Result{}
}
msg := NewMessage()
msg.Text = message
result := NewResult(msg)
location := NewLocation().WithURI(uri).WithLineColumn(line, column)
result.Locations = append(result.Locations, location)
result.RuleId = ruleId
r.Results = append(r.Results, result)
return r
}
// WithInformationUri sets the information URI
func (t *ToolComponent) WithInformationUri(uri string) *ToolComponent {
t.InformationUri = uri
return t
}
// WithRules sets (overwrites) the rules
func (t *ToolComponent) WithRules(rules ...*ReportingDescriptor) *ToolComponent {
t.Rules = rules
return t
}

View File

@ -1,11 +0,0 @@
// Package garif defines all the GO structures required to model a SARIF log file.
// These structures were created using the JSON-schema sarif-schema-2.1.0.json of SARIF logfiles
// available at https://github.com/oasis-tcs/sarif-spec/tree/master/Schemata.
//
// The package provides constructors for all structures (see constructors.go) These constructors
// ensure that the returned structure instantiation is valid with respect to the JSON schema and
// should be used in place of plain structure instantiation.
// The root structure is LogFile.
//
// The package provides utility decorators for the most commonly used structures (see decorators.go)
package garif

View File

@ -1,26 +0,0 @@
package garif
import (
"encoding/json"
"io"
)
// Write writes the JSON
func (l *LogFile) Write(w io.Writer) error {
marshal, err := json.Marshal(l)
if err != nil {
return err
}
_, err = w.Write(marshal)
return err
}
// PrettyWrite writes indented JSON
func (l *LogFile) PrettyWrite(w io.Writer) error {
marshal, err := json.MarshalIndent(l, "", " ")
if err != nil {
return err
}
_, err = w.Write(marshal)
return err
}

File diff suppressed because it is too large Load Diff

View File

@ -1,29 +0,0 @@
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.

View File

@ -1,368 +0,0 @@
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 {
pkgName := strings.Trim(line, "\"\\`")
if localFlag != "" && strings.HasPrefix(pkgName, localFlag) {
return local
}
if isStandardPackage(pkgName) {
return standard
}
return remote
}
const (
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
}

View File

@ -1,161 +0,0 @@
package gci
// Code generated based on go1.16beta1. DO NOT EDIT.
var standardPackages = map[string]struct{}{
"archive/tar": {},
"archive/zip": {},
"bufio": {},
"bytes": {},
"compress/bzip2": {},
"compress/flate": {},
"compress/gzip": {},
"compress/lzw": {},
"compress/zlib": {},
"container/heap": {},
"container/list": {},
"container/ring": {},
"context": {},
"crypto": {},
"crypto/aes": {},
"crypto/cipher": {},
"crypto/des": {},
"crypto/dsa": {},
"crypto/ecdsa": {},
"crypto/ed25519": {},
"crypto/elliptic": {},
"crypto/hmac": {},
"crypto/md5": {},
"crypto/rand": {},
"crypto/rc4": {},
"crypto/rsa": {},
"crypto/sha1": {},
"crypto/sha256": {},
"crypto/sha512": {},
"crypto/subtle": {},
"crypto/tls": {},
"crypto/x509": {},
"crypto/x509/pkix": {},
"database/sql": {},
"database/sql/driver": {},
"debug/dwarf": {},
"debug/elf": {},
"debug/gosym": {},
"debug/macho": {},
"debug/pe": {},
"debug/plan9obj": {},
"embed": {},
"encoding": {},
"encoding/ascii85": {},
"encoding/asn1": {},
"encoding/base32": {},
"encoding/base64": {},
"encoding/binary": {},
"encoding/csv": {},
"encoding/gob": {},
"encoding/hex": {},
"encoding/json": {},
"encoding/pem": {},
"encoding/xml": {},
"errors": {},
"expvar": {},
"flag": {},
"fmt": {},
"go/ast": {},
"go/build": {},
"go/constant": {},
"go/doc": {},
"go/format": {},
"go/importer": {},
"go/parser": {},
"go/printer": {},
"go/scanner": {},
"go/token": {},
"go/types": {},
"hash": {},
"hash/adler32": {},
"hash/crc32": {},
"hash/crc64": {},
"hash/fnv": {},
"hash/maphash": {},
"html": {},
"html/template": {},
"image": {},
"image/color": {},
"image/color/palette": {},
"image/draw": {},
"image/gif": {},
"image/jpeg": {},
"image/png": {},
"index/suffixarray": {},
"io": {},
"io/fs": {},
"io/ioutil": {},
"log": {},
"log/syslog": {},
"math": {},
"math/big": {},
"math/bits": {},
"math/cmplx": {},
"math/rand": {},
"mime": {},
"mime/multipart": {},
"mime/quotedprintable": {},
"net": {},
"net/http": {},
"net/http/cgi": {},
"net/http/cookiejar": {},
"net/http/fcgi": {},
"net/http/httptest": {},
"net/http/httptrace": {},
"net/http/httputil": {},
"net/http/pprof": {},
"net/mail": {},
"net/rpc": {},
"net/rpc/jsonrpc": {},
"net/smtp": {},
"net/textproto": {},
"net/url": {},
"os": {},
"os/exec": {},
"os/signal": {},
"os/user": {},
"path": {},
"path/filepath": {},
"plugin": {},
"reflect": {},
"regexp": {},
"regexp/syntax": {},
"runtime": {},
"runtime/cgo": {},
"runtime/debug": {},
"runtime/metrics": {},
"runtime/pprof": {},
"runtime/race": {},
"runtime/trace": {},
"sort": {},
"strconv": {},
"strings": {},
"sync": {},
"sync/atomic": {},
"syscall": {},
"testing": {},
"testing/fstest": {},
"testing/iotest": {},
"testing/quick": {},
"text/scanner": {},
"text/tabwriter": {},
"text/template": {},
"text/template/parse": {},
"time": {},
"time/tzdata": {},
"unicode": {},
"unicode/utf16": {},
"unicode/utf8": {},
"unsafe": {},
}
func isStandardPackage(pkg string) bool {
_, ok := standardPackages[pkg]
return ok
}

View File

@ -1 +0,0 @@
.idea/

View File

@ -1,19 +0,0 @@
values:
regexp:
copyright-holder: Copyright \(c\) {{year-range}} Denis Tingajkin
template: |
{{copyright-holder}}
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.

View File

@ -1,674 +0,0 @@
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>.

View File

@ -1,81 +0,0 @@
# 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`.
```bash
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 fields:
```yaml
---
temaplte: # expects header template string.
tempalte-path: # expects path to file with license header string.
values: # expects `const` or `regexp` node with values where values is a map string to string.
const:
key1: value1 # const value just checks equality. Note `key1` should be used in template string as {{ key1 }} or {{ KEY1 }}.
regexp:
key2: value2 # regexp value just checks regex match. The value should be a valid regexp pattern. Note `key2` should be used in template string as {{ key2 }} or {{ KEY2 }}.
```
Where `values` also can be used recursively. Example:
```yaml
values:
const:
key1: "value"
regexp:
key2: "{{key1}} value1" # Reads as regex pattern "value value1"
```
## Bult-in values
- **YEAR** - Expects current year. Example header value: `2020`. Example of template using: `{{YEAR}}` or `{{year}}`.
- **YEAR-RANGE** - Expects any valid year interval or current year. Example header value: `2020` or `2000-2020`. Example of template using: `{{year-range}}` or `{{YEAR-RANGE}}`.
## Execution
`go-header` linter expects file paths 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 | grep -E '.*\.go')
```
## Setup example
### Step 1
Create configuration file `.go-header.yml` in the root of project.
```yaml
---
values:
const:
MY COMPANY: mycompany.com
template: |
{{ 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 2
You are ready! Execute `go-header ${PATH_TO_FILES}` from the root of the project.

View File

@ -1,146 +0,0 @@
// Copyright (c) 2020 Denis Tingajkin
//
// 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.
package goheader
import (
"fmt"
"go/ast"
"os"
"os/exec"
"strings"
"time"
)
type Target struct {
Path string
File *ast.File
}
const iso = "2006-01-02 15:04:05 -0700"
func (t *Target) ModTime() (time.Time, error) {
diff, err := exec.Command("git", "diff", t.Path).CombinedOutput()
if err == nil && len(diff) == 0 {
line, err := exec.Command("git", "log", "-1", "--pretty=format:%cd", "--date=iso", "--", t.Path).CombinedOutput()
if err == nil {
return time.Parse(iso, string(line))
}
}
info, err := os.Stat(t.Path)
if err != nil {
return time.Time{}, err
}
return info.ModTime(), nil
}
type Analyzer struct {
values map[string]Value
template string
}
func (a *Analyzer) Analyze(target *Target) Issue {
if a.template == "" {
return NewIssue("Missed template for check")
}
if t, err := target.ModTime(); err == nil {
if t.Year() != time.Now().Year() {
return nil
}
}
file := target.File
var header string
var offset = Location{
Position: 1,
}
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()
offset.Position += 3
}
}
header = strings.TrimSpace(header)
if header == "" {
return NewIssue("Missed header for check")
}
s := NewReader(header)
s.SetOffset(offset)
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 ...Option) *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
}

View File

@ -1,99 +0,0 @@
// Copyright (c) 2020 Denis Tingajkin
//
// 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.
package goheader
import (
"errors"
"fmt"
"io/ioutil"
"strings"
"time"
"gopkg.in/yaml.v2"
)
// 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) builtInValues() map[string]Value {
var result = make(map[string]Value)
year := fmt.Sprint(time.Now().Year())
result["year-range"] = &RegexpValue{
RawValue: strings.ReplaceAll(`(20\d\d\-YEAR)|(YEAR)`, "YEAR", year),
}
result["year"] = &ConstValue{
RawValue: year,
}
return result
}
func (c *Configuration) GetValues() (map[string]Value, error) {
var result = c.builtInValues()
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 = strings.TrimSpace(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)
}

View File

@ -1,48 +0,0 @@
// Copyright (c) 2020 Denis Tingajkin
//
// 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.
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,
}
}

View File

@ -1,35 +0,0 @@
// Copyright (c) 2020 Denis Tingajkin
//
// 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.
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)
}
func (l Location) Add(other Location) Location {
return Location{
Line: l.Line + other.Line,
Position: l.Position + other.Position,
}
}

View File

@ -1,44 +0,0 @@
// Copyright (c) 2020 Denis Tingajkin
//
// 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.
package goheader
import "strings"
type Option interface {
apply(*Analyzer)
}
type applyAnalyzerOptionFunc func(*Analyzer)
func (f applyAnalyzerOptionFunc) apply(a *Analyzer) {
f(a)
}
func WithValues(values map[string]Value) Option {
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) Option {
return applyAnalyzerOptionFunc(func(a *Analyzer) {
a.template = template
})
}

View File

@ -1,116 +0,0 @@
/*
Copyright (c) 2020 Denis Tingajkin
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.
*/
package goheader
func NewReader(text string) *Reader {
return &Reader{source: text}
}
type Reader struct {
source string
position int
location Location
offset Location
}
func (r *Reader) SetOffset(offset Location) {
r.offset = offset
}
func (r *Reader) Position() int {
return r.position
}
func (r *Reader) Location() Location {
return r.location.Add(r.offset)
}
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}
}

View File

@ -1,128 +0,0 @@
// Copyright (c) 2020 Denis Tingajkin
//
// 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.
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{}

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 Eugene Simonov
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.

View File

@ -1,247 +0,0 @@
package analyzer
import (
"go/ast"
"go/token"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/inspector"
)
var maxDeclChars, maxDeclLines int
const (
maxDeclLinesUsage = `maximum length of variable declaration measured in number of lines, after which the linter won't suggest using short syntax.
Has precedence over max-decl-chars.`
maxDeclCharsUsage = `maximum length of variable declaration measured in number of characters, after which the linter won't suggest using short syntax.`
)
func init() {
Analyzer.Flags.IntVar(&maxDeclLines, "max-decl-lines", 1, maxDeclLinesUsage)
Analyzer.Flags.IntVar(&maxDeclChars, "max-decl-chars", 30, maxDeclCharsUsage)
}
// Analyzer is an analysis.Analyzer instance for ifshort linter.
var Analyzer = &analysis.Analyzer{
Name: "ifshort",
Doc: "Checks that your code uses short syntax for if-statements whenever possible.",
Run: run,
Requires: []*analysis.Analyzer{inspect.Analyzer},
}
func run(pass *analysis.Pass) (interface{}, error) {
inspector := pass.ResultOf[inspect.Analyzer].(*inspector.Inspector)
nodeFilter := []ast.Node{
(*ast.FuncDecl)(nil),
}
inspector.Preorder(nodeFilter, func(node ast.Node) {
fdecl := node.(*ast.FuncDecl)
/*if fdecl.Name.Name != "notUsed_BinaryExpressionInIndex_OK" {
return
}*/
if fdecl == nil || fdecl.Body == nil {
return
}
candidates := getNamedOccurrenceMap(fdecl, pass)
for _, stmt := range fdecl.Body.List {
candidates.checkStatement(stmt, token.NoPos)
}
for varName := range candidates {
for marker, occ := range candidates[varName] {
// If two or more vars with the same scope marker - skip them.
if candidates.isFoundByScopeMarker(marker) {
continue
}
pass.Reportf(occ.declarationPos,
"variable '%s' is only used in the if-statement (%s); consider using short syntax",
varName, pass.Fset.Position(occ.ifStmtPos))
}
}
})
return nil, nil
}
func (nom namedOccurrenceMap) checkStatement(stmt ast.Stmt, ifPos token.Pos) {
switch v := stmt.(type) {
case *ast.AssignStmt:
for _, el := range v.Rhs {
nom.checkExpression(el, ifPos)
}
if isAssign(v.Tok) {
for _, el := range v.Lhs {
nom.checkExpression(el, ifPos)
}
}
case *ast.DeferStmt:
for _, a := range v.Call.Args {
nom.checkExpression(a, ifPos)
}
case *ast.ExprStmt:
if callExpr, ok := v.X.(*ast.CallExpr); ok {
nom.checkExpression(callExpr, ifPos)
}
case *ast.ForStmt:
for _, el := range v.Body.List {
nom.checkStatement(el, ifPos)
}
if bexpr, ok := v.Cond.(*ast.BinaryExpr); ok {
nom.checkExpression(bexpr.X, ifPos)
nom.checkExpression(bexpr.Y, ifPos)
}
nom.checkStatement(v.Post, ifPos)
case *ast.GoStmt:
for _, a := range v.Call.Args {
nom.checkExpression(a, ifPos)
}
case *ast.IfStmt:
for _, el := range v.Body.List {
nom.checkStatement(el, v.If)
}
switch cond := v.Cond.(type) {
case *ast.BinaryExpr:
nom.checkExpression(cond.X, v.If)
nom.checkExpression(cond.Y, v.If)
case *ast.CallExpr:
nom.checkExpression(cond, v.If)
}
if init, ok := v.Init.(*ast.AssignStmt); ok {
for _, e := range init.Rhs {
nom.checkExpression(e, v.If)
}
}
case *ast.IncDecStmt:
nom.checkExpression(v.X, ifPos)
case *ast.RangeStmt:
nom.checkExpression(v.X, ifPos)
if v.Body != nil {
for _, e := range v.Body.List {
nom.checkStatement(e, ifPos)
}
}
case *ast.ReturnStmt:
for _, r := range v.Results {
nom.checkExpression(r, ifPos)
}
case *ast.SendStmt:
nom.checkExpression(v.Chan, ifPos)
nom.checkExpression(v.Value, ifPos)
case *ast.SwitchStmt:
nom.checkExpression(v.Tag, ifPos)
for _, el := range v.Body.List {
clauses, ok := el.(*ast.CaseClause)
if !ok {
continue
}
for _, c := range clauses.List {
switch v := c.(type) {
case *ast.BinaryExpr:
nom.checkExpression(v.X, ifPos)
nom.checkExpression(v.Y, ifPos)
case *ast.Ident:
nom.checkExpression(v, ifPos)
}
}
for _, c := range clauses.Body {
if est, ok := c.(*ast.ExprStmt); ok {
nom.checkExpression(est.X, ifPos)
}
switch v := c.(type) {
case *ast.AssignStmt:
for _, el := range v.Rhs {
nom.checkExpression(el, ifPos)
}
case *ast.ExprStmt:
nom.checkExpression(v.X, ifPos)
}
}
}
}
}
func (nom namedOccurrenceMap) checkExpression(candidate ast.Expr, ifPos token.Pos) {
switch v := candidate.(type) {
case *ast.BinaryExpr:
nom.checkExpression(v.X, ifPos)
nom.checkExpression(v.Y, ifPos)
case *ast.CallExpr:
for _, arg := range v.Args {
nom.checkExpression(arg, ifPos)
}
nom.checkExpression(v.Fun, ifPos)
if fun, ok := v.Fun.(*ast.SelectorExpr); ok {
nom.checkExpression(fun.X, ifPos)
}
case *ast.CompositeLit:
for _, el := range v.Elts {
switch v := el.(type) {
case *ast.Ident:
nom.checkExpression(v, ifPos)
case *ast.KeyValueExpr:
nom.checkExpression(v.Key, ifPos)
nom.checkExpression(v.Value, ifPos)
}
}
case *ast.FuncLit:
for _, el := range v.Body.List {
nom.checkStatement(el, ifPos)
}
case *ast.Ident:
if _, ok := nom[v.Name]; !ok || nom[v.Name].isEmponymousKey(ifPos) {
return
}
scopeMarker1 := nom[v.Name].getScopeMarkerForPosition(v.Pos())
delete(nom[v.Name], scopeMarker1)
for k := range nom {
for scopeMarker2 := range nom[k] {
if scopeMarker1 == scopeMarker2 {
delete(nom[k], scopeMarker2)
}
}
}
case *ast.IndexExpr:
nom.checkExpression(v.X, ifPos)
switch index := v.Index.(type) {
case *ast.BinaryExpr:
nom.checkExpression(index.X, ifPos)
case *ast.Ident:
nom.checkExpression(index, ifPos)
}
case *ast.SelectorExpr:
nom.checkExpression(v.X, ifPos)
case *ast.SliceExpr:
nom.checkExpression(v.High, ifPos)
nom.checkExpression(v.Low, ifPos)
nom.checkExpression(v.X, ifPos)
case *ast.TypeAssertExpr:
nom.checkExpression(v.X, ifPos)
case *ast.UnaryExpr:
nom.checkExpression(v.X, ifPos)
}
}
func isAssign(tok token.Token) bool {
return (tok == token.ASSIGN ||
tok == token.ADD_ASSIGN || tok == token.SUB_ASSIGN ||
tok == token.MUL_ASSIGN || tok == token.QUO_ASSIGN || tok == token.REM_ASSIGN ||
tok == token.AND_ASSIGN || tok == token.OR_ASSIGN || tok == token.XOR_ASSIGN || tok == token.AND_NOT_ASSIGN ||
tok == token.SHL_ASSIGN || tok == token.SHR_ASSIGN)
}

View File

@ -1,259 +0,0 @@
package analyzer
import (
"go/ast"
"go/token"
"time"
"golang.org/x/tools/go/analysis"
)
// occurrence is a variable occurrence.
type occurrence struct {
declarationPos token.Pos
ifStmtPos token.Pos
}
func (occ *occurrence) isComplete() bool {
return occ.ifStmtPos != token.NoPos && occ.declarationPos != token.NoPos
}
// scopeMarkeredOccurences is a map of scope markers to variable occurrences.
type scopeMarkeredOccurences map[int64]occurrence
func (smo scopeMarkeredOccurences) getGreatestMarker() int64 {
var maxScopeMarker int64
for marker := range smo {
if marker > maxScopeMarker {
maxScopeMarker = marker
}
}
return maxScopeMarker
}
// find scope marker of the greatest token.Pos that is smaller than provided.
func (smo scopeMarkeredOccurences) getScopeMarkerForPosition(pos token.Pos) int64 {
var m int64
var foundPos token.Pos
for marker, occ := range smo {
if occ.declarationPos < pos && occ.declarationPos >= foundPos {
m = marker
foundPos = occ.declarationPos
}
}
return m
}
func (smo scopeMarkeredOccurences) isEmponymousKey(pos token.Pos) bool {
if pos == token.NoPos {
return false
}
for _, occ := range smo {
if occ.ifStmtPos == pos {
return true
}
}
return false
}
// namedOccurrenceMap is a map of variable names to scopeMarkeredOccurences.
type namedOccurrenceMap map[string]scopeMarkeredOccurences
func getNamedOccurrenceMap(fdecl *ast.FuncDecl, pass *analysis.Pass) namedOccurrenceMap {
nom := namedOccurrenceMap(map[string]scopeMarkeredOccurences{})
if fdecl == nil || fdecl.Body == nil {
return nom
}
for _, stmt := range fdecl.Body.List {
switch v := stmt.(type) {
case *ast.AssignStmt:
nom.addFromAssignment(pass, v)
case *ast.IfStmt:
nom.addFromCondition(v)
nom.addFromIfClause(v)
nom.addFromElseClause(v)
}
}
candidates := namedOccurrenceMap(map[string]scopeMarkeredOccurences{})
for varName, markeredOccs := range nom {
for marker, occ := range markeredOccs {
if !occ.isComplete() && !nom.isFoundByScopeMarker(marker) {
continue
}
if _, ok := candidates[varName]; !ok {
candidates[varName] = scopeMarkeredOccurences{
marker: occ,
}
} else {
candidates[varName][marker] = occ
}
}
}
return candidates
}
func (nom namedOccurrenceMap) isFoundByScopeMarker(scopeMarker int64) bool {
var i int
for _, markeredOccs := range nom {
for marker := range markeredOccs {
if marker == scopeMarker {
i++
}
}
}
return i >= 2
}
func (nom namedOccurrenceMap) addFromAssignment(pass *analysis.Pass, assignment *ast.AssignStmt) {
if assignment.Tok != token.DEFINE {
return
}
scopeMarker := time.Now().UnixNano()
for i, el := range assignment.Lhs {
ident, ok := el.(*ast.Ident)
if !ok {
continue
}
if ident.Name == "_" || ident.Obj == nil || isUnshortenableAssignment(ident.Obj.Decl) {
continue
}
if markeredOccs, ok := nom[ident.Name]; ok {
markeredOccs[scopeMarker] = occurrence{
declarationPos: ident.Pos(),
}
nom[ident.Name] = markeredOccs
} else {
newOcc := occurrence{}
if areFlagSettingsSatisfied(pass, assignment, i) {
newOcc.declarationPos = ident.Pos()
}
nom[ident.Name] = scopeMarkeredOccurences{scopeMarker: newOcc}
}
}
}
func isUnshortenableAssignment(decl interface{}) bool {
assign, ok := decl.(*ast.AssignStmt)
if !ok {
return false
}
for _, el := range assign.Rhs {
u, ok := el.(*ast.UnaryExpr)
if !ok {
continue
}
if u.Op == token.AND {
if _, ok := u.X.(*ast.CompositeLit); ok {
return true
}
}
}
return false
}
func areFlagSettingsSatisfied(pass *analysis.Pass, assignment *ast.AssignStmt, i int) bool {
lh := assignment.Lhs[i]
rh := assignment.Rhs[len(assignment.Rhs)-1]
if len(assignment.Rhs) == len(assignment.Lhs) {
rh = assignment.Rhs[i]
}
if pass.Fset.Position(rh.End()).Line-pass.Fset.Position(rh.Pos()).Line > maxDeclLines {
return false
}
if int(rh.End()-lh.Pos()) > maxDeclChars {
return false
}
return true
}
func (nom namedOccurrenceMap) addFromCondition(stmt *ast.IfStmt) {
switch v := stmt.Cond.(type) {
case *ast.BinaryExpr:
for _, v := range [2]ast.Expr{v.X, v.Y} {
switch e := v.(type) {
case *ast.Ident:
nom.addFromIdent(stmt.If, e)
case *ast.SelectorExpr:
nom.addFromIdent(stmt.If, e.X)
}
}
case *ast.Ident:
nom.addFromIdent(stmt.If, v)
case *ast.CallExpr:
for _, a := range v.Args {
switch e := a.(type) {
case *ast.Ident:
nom.addFromIdent(stmt.If, e)
case *ast.CallExpr:
nom.addFromCallExpr(stmt.If, e)
}
}
}
}
func (nom namedOccurrenceMap) addFromIfClause(stmt *ast.IfStmt) {
nom.addFromBlockStmt(stmt.Body, stmt.If)
}
func (nom namedOccurrenceMap) addFromElseClause(stmt *ast.IfStmt) {
nom.addFromBlockStmt(stmt.Else, stmt.If)
}
func (nom namedOccurrenceMap) addFromBlockStmt(stmt ast.Stmt, ifPos token.Pos) {
blockStmt, ok := stmt.(*ast.BlockStmt)
if !ok {
return
}
for _, el := range blockStmt.List {
exptStmt, ok := el.(*ast.ExprStmt)
if !ok {
continue
}
if callExpr, ok := exptStmt.X.(*ast.CallExpr); ok {
nom.addFromCallExpr(ifPos, callExpr)
}
}
}
func (nom namedOccurrenceMap) addFromCallExpr(ifPos token.Pos, callExpr *ast.CallExpr) {
for _, arg := range callExpr.Args {
nom.addFromIdent(ifPos, arg)
}
}
func (nom namedOccurrenceMap) addFromIdent(ifPos token.Pos, v ast.Expr) {
ident, ok := v.(*ast.Ident)
if !ok {
return
}
if markeredOccs, ok := nom[ident.Name]; ok {
marker := nom[ident.Name].getGreatestMarker()
occ := markeredOccs[marker]
if occ.isComplete() {
return
}
occ.ifStmtPos = ifPos
nom[ident.Name][marker] = occ
}
}

View File

@ -1,18 +0,0 @@
# 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
# CPU and memory profiles
*.prof
# Dependency directories
vendor/

View File

@ -1,88 +0,0 @@
linters-settings:
dupl:
threshold: 100
gocyclo:
min-complexity: 15
gocritic:
enabled-tags:
- diagnostic
- experimental
- opinionated
- performance
- style
disabled-checks:
- ifElseChain
- whyNoLint
- wrapperFunc
golint:
min-confidence: 0.5
govet:
check-shadowing: true
lll:
line-length: 140
maligned:
suggest-new: true
misspell:
locale: US
nolintlint:
allow-leading-space: false
allow-unused: false
require-specific: true
require-explanation: true
allow-no-explanation:
- gocyclo
linters:
disable-all: true
enable:
- bodyclose
- deadcode
- depguard
- dogsled
- dupl
- errcheck
- gochecknoinits
- gocritic
- gocyclo
- gofmt
- goimports
- golint
- goprintffuncname
- gosec
- gosimple
- govet
- ineffassign
- interfacer
- lll
- misspell
- nakedret
- nolintlint
- rowserrcheck
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace
# don't enable:
# - asciicheck
# - gochecknoglobals
# - gocognit
# - godot
# - godox
# - goerr113
# - maligned
# - nestif
# - prealloc
# - testpackage
# - wsl
issues:
exclude-use-default: false
max-issues-per-linter: 0
max-same-issues: 0

View File

@ -1,80 +0,0 @@
{{with .PDoc}}
# Go Strcase
[![Go Report Card](https://goreportcard.com/badge/github.com/ettle/strcase)](https://goreportcard.com/report/github.com/ettle/strcase)
[![Coverage](http://gocover.io/_badge/github.com/ettle/strcase?0)](http://gocover.io/github.com/ettle/strcase)
[![GoDoc](https://godoc.org/github.com/ettle/strcase?status.svg)](https://pkg.go.dev/github.com/ettle/strcase)
Convert strings to `snake_case`, `camelCase`, `PascalCase`, `kebab-case` and more! Supports Go initialisms, customization, and Unicode.
`import "{{.ImportPath}}"`
## <a name="pkg-overview">Overview</a>
{{comment_md .Doc}}
{{example_html $ ""}}
## <a name="pkg-index">Index</a>{{if .Consts}}
* [Constants](#pkg-constants){{end}}{{if .Vars}}
* [Variables](#pkg-variables){{end}}{{- range .Funcs -}}{{$name_html := html .Name}}
* [{{node_html $ .Decl false | sanitize}}](#{{$name_html}}){{- end}}{{- range .Types}}{{$tname_html := html .Name}}
* [type {{$tname_html}}](#{{$tname_html}}){{- range .Funcs}}{{$name_html := html .Name}}
* [{{node_html $ .Decl false | sanitize}}](#{{$name_html}}){{- end}}{{- range .Methods}}{{$name_html := html .Name}}
* [{{node_html $ .Decl false | sanitize}}](#{{$tname_html}}.{{$name_html}}){{- end}}{{- end}}{{- if $.Notes}}{{- range $marker, $item := $.Notes}}
* [{{noteTitle $marker | html}}s](#pkg-note-{{$marker}}){{end}}{{end}}
{{if $.Examples}}
#### <a name="pkg-examples">Examples</a>{{- range $.Examples}}
* [{{example_name .Name}}](#example_{{.Name}}){{- end}}{{- end}}
{{with .Consts}}## <a name="pkg-constants">Constants</a>
{{range .}}{{node $ .Decl | pre}}
{{comment_md .Doc}}{{end}}{{end}}
{{with .Vars}}## <a name="pkg-variables">Variables</a>
{{range .}}{{node $ .Decl | pre}}
{{comment_md .Doc}}{{end}}{{end}}
{{range .Funcs}}{{$name_html := html .Name}}## <a name="{{$name_html}}">func</a> [{{$name_html}}]({{gh_url $ .Decl}})
{{node $ .Decl | pre}}
{{comment_md .Doc}}
{{example_html $ .Name}}
{{callgraph_html $ "" .Name}}{{end}}
{{range .Types}}{{$tname := .Name}}{{$tname_html := html .Name}}## <a name="{{$tname_html}}">type</a> [{{$tname_html}}]({{gh_url $ .Decl}})
{{node $ .Decl | pre}}
{{comment_md .Doc}}{{range .Consts}}
{{node $ .Decl | pre }}
{{comment_md .Doc}}{{end}}{{range .Vars}}
{{node $ .Decl | pre }}
{{comment_md .Doc}}{{end}}
{{example_html $ $tname}}
{{implements_html $ $tname}}
{{methodset_html $ $tname}}
{{range .Funcs}}{{$name_html := html .Name}}### <a name="{{$name_html}}">func</a> [{{$name_html}}]({{gh_url $ .Decl}})
{{node $ .Decl | pre}}
{{comment_md .Doc}}
{{example_html $ .Name}}{{end}}
{{callgraph_html $ "" .Name}}
{{range .Methods}}{{$name_html := html .Name}}### <a name="{{$tname_html}}.{{$name_html}}">func</a> ({{md .Recv}}) [{{$name_html}}]({{gh_url $ .Decl}})
{{node $ .Decl | pre}}
{{comment_md .Doc}}
{{$name := printf "%s_%s" $tname .Name}}{{example_html $ $name}}
{{callgraph_html $ .Recv .Name}}
{{end}}{{end}}{{end}}
{{with $.Notes}}
{{range $marker, $content := .}}
## <a name="pkg-note-{{$marker}}">{{noteTitle $marker | html}}s
<ul style="list-style: none; padding: 0;">
{{range .}}
<li><a href="{{gh_url $ .}}">&#x261e;</a> {{html .Body}}</li>
{{end}}
</ul>
{{end}}
{{end}}
{{if .Dirs}}
## <a name="Subdirectories">Subdirectories</a>
{{range $.Dirs.List}}
{{indent .Depth}}* [{{.Name | html}}]({{print "./" .Path}}){{if .Synopsis}} {{ .Synopsis}}{{end -}}
{{end}}
{{end}}

View File

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2020 Liyan David Chang
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.

View File

@ -1,16 +0,0 @@
.PHONY: benchmark docs lint test
docs:
which godoc2ghmd || ( go get github.com/DevotedHealth/godoc2ghmd && go mod tidy )
godoc2ghmd -template .readme.tmpl github.com/ettle/strcase > README.md
test:
go test -cover ./...
lint:
which golangci-lint || ( go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.27.0 && go mod tidy )
golangci-lint run
golangci-lint run benchmark/*.go
benchmark:
cd benchmark && go test -bench=. -test.benchmem && go mod tidy

View File

@ -1,542 +0,0 @@
# Go Strcase
[![Go Report Card](https://goreportcard.com/badge/github.com/ettle/strcase)](https://goreportcard.com/report/github.com/ettle/strcase)
[![Coverage](http://gocover.io/_badge/github.com/ettle/strcase?0)](http://gocover.io/github.com/ettle/strcase)
[![GoDoc](https://godoc.org/github.com/ettle/strcase?status.svg)](https://pkg.go.dev/github.com/ettle/strcase)
Convert strings to `snake_case`, `camelCase`, `PascalCase`, `kebab-case` and more! Supports Go initialisms, customization, and Unicode.
`import "github.com/ettle/strcase"`
## <a name="pkg-overview">Overview</a>
Package strcase is a package for converting strings into various word cases
(e.g. snake_case, camelCase)
go get -u github.com/ettle/strcase
Example usage
strcase.ToSnake("Hello World") // hello_world
strcase.ToSNAKE("Hello World") // HELLO_WORLD
strcase.ToKebab("helloWorld") // hello-world
strcase.ToKEBAB("helloWorld") // HELLO-WORLD
strcase.ToPascal("hello-world") // HelloWorld
strcase.ToCamel("hello-world") // helloWorld
// Handle odd cases
strcase.ToSnake("FOOBar") // foo_bar
// Support Go initialisms
strcase.ToGoCamel("http_response") // HTTPResponse
// Specify case and delimiter
strcase.ToCase("HelloWorld", strcase.UpperCase, '.') // HELLO.WORLD
### Why this package
String strcase is pretty straight forward and there are a number of methods to
do it. This package is fully featured, more customizable, better tested, and
faster* than other packages and what you would probably whip up yourself.
### Unicode support
We work for with unicode strings and pay very little performance penalty for it
as we optimized for the common use case of ASCII only strings.
### Customization
You can create a custom caser that changes the behavior to what you want. This
customization also reduces the pressure for us to change the default behavior
which means that things are more stable for everyone involved. The goal is to
make the common path easy and fast, while making the uncommon path possible.
c := NewCaser(
// Use Go's default initialisms e.g. ID, HTML
true,
// Override initialisms (e.g. don't initialize HTML but initialize SSL
map[string]bool{"SSL": true, "HTML": false},
// Write your own custom SplitFn
//
NewSplitFn(
[]rune{'*', '.', ','},
SplitCase,
SplitAcronym,
PreserveNumberFormatting,
SplitBeforeNumber,
SplitAfterNumber,
))
assert.Equal(t, "http_200", c.ToSnake("http200"))
### Initialism support
By default, we use the golint intialisms list. You can customize and override
the initialisms if you wish to add additional ones, such as "SSL" or "CMS" or
domain specific ones to your industry.
ToGoCamel("http_response") // HTTPResponse
ToGoSnake("http_response") // HTTP_response
### Test coverage
We have a wide ranging test suite to make sure that we understand our behavior.
Test coverage isn't everything, but we aim for 100% coverage.
### Fast
Optimized to reduce memory allocations with Builder. Benchmarked and optimized
around common cases.
We're on par with the fastest packages (that have less features) and much
faster than others. We also benchmarked against code snippets. Using string
builders to reduce memory allocation and reordering boolean checks for the
common cases have a large performance impact.
Hopefully I was fair to each library and happy to rerun benchmarks differently
or reword my commentary based on suggestions or updates.
// This package
// Go intialisms and custom casers are slower
BenchmarkToTitle-4 992491 1559 ns/op 32 B/op 1 allocs/op
BenchmarkToSnake-4 1000000 1475 ns/op 32 B/op 1 allocs/op
BenchmarkToSNAKE-4 1000000 1609 ns/op 32 B/op 1 allocs/op
BenchmarkToGoSnake-4 275010 3697 ns/op 44 B/op 4 allocs/op
BenchmarkToCustomCaser-4 342704 4191 ns/op 56 B/op 4 allocs/op
// Segment has very fast snake case and camel case libraries
// No features or customization, but very very fast
BenchmarkSegment-4 1303809 938 ns/op 16 B/op 1 allocs/op
// Stdlib strings.Title for comparison, even though it only splits on spaces
BenchmarkToTitleStrings-4 1213467 1164 ns/op 16 B/op 1 allocs/op
// Other libraries or code snippets
// - Most are slower, by up to an order of magnitude
// - None support initialisms or customization
// - Some generate only camelCase or snake_case
// - Many lack unicode support
BenchmarkToSnakeStoewer-4 973200 2075 ns/op 64 B/op 2 allocs/op
// Copying small rune arrays is slow
BenchmarkToSnakeSiongui-4 264315 4229 ns/op 48 B/op 10 allocs/op
BenchmarkGoValidator-4 206811 5152 ns/op 184 B/op 9 allocs/op
// String alloction is slow
BenchmarkToSnakeFatih-4 82675 12280 ns/op 392 B/op 26 allocs/op
BenchmarkToSnakeIanColeman-4 83276 13903 ns/op 145 B/op 13 allocs/op
// Regexp is slow
BenchmarkToSnakeGolangPrograms-4 74448 18586 ns/op 176 B/op 11 allocs/op
// These results aren't a surprise - my initial version of this library was
// painfully slow. I think most of us, without spending some time with
// profilers and benchmarks, would write also something on the slower side.
### Why not this package
If every nanosecond matters and this is used in a tight loop, use segment.io's
libraries (<a href="https://github.com/segmentio/go-snakecase">https://github.com/segmentio/go-snakecase</a> and
<a href="https://github.com/segmentio/go-camelcase">https://github.com/segmentio/go-camelcase</a>). They lack features, but make up for
it by being blazing fast. Alternatively, if you need your code to work slightly
differently, fork them and tailor it for your use case.
If you don't like having external imports, I get it. This package only imports
packages for testing, otherwise it only uses the standard library. If that's
not enough, you can use this repo as the foundation for your own. MIT Licensed.
This package is still relatively new and while I've used it for a while
personally, it doesn't have the miles that other packages do. I've tested this
code agains't their test cases to make sure that there aren't any surprises.
### Migrating from other packages
If you are migrating from from another package, you may find slight differences
in output. To reduce the delta, you may find it helpful to use the following
custom casers to mimic the behavior of the other package.
// From <a href="https://github.com/iancoleman/strcase">https://github.com/iancoleman/strcase</a>
var c = NewCaser(false, nil, NewSplitFn([]rune{'_', '-', '.'}, SplitCase, SplitAcronym, SplitBeforeNumber))
// From <a href="https://github.com/stoewer/go-strcase">https://github.com/stoewer/go-strcase</a>
var c = NewCaser(false, nil, NewSplitFn([]rune{'_', '-'}, SplitCase), SplitAcronym)
## <a name="pkg-index">Index</a>
* [func ToCamel(s string) string](#ToCamel)
* [func ToCase(s string, wordCase WordCase, delimiter rune) string](#ToCase)
* [func ToGoCamel(s string) string](#ToGoCamel)
* [func ToGoCase(s string, wordCase WordCase, delimiter rune) string](#ToGoCase)
* [func ToGoKebab(s string) string](#ToGoKebab)
* [func ToGoPascal(s string) string](#ToGoPascal)
* [func ToGoSnake(s string) string](#ToGoSnake)
* [func ToKEBAB(s string) string](#ToKEBAB)
* [func ToKebab(s string) string](#ToKebab)
* [func ToPascal(s string) string](#ToPascal)
* [func ToSNAKE(s string) string](#ToSNAKE)
* [func ToSnake(s string) string](#ToSnake)
* [type Caser](#Caser)
* [func NewCaser(goInitialisms bool, initialismOverrides map[string]bool, splitFn SplitFn) *Caser](#NewCaser)
* [func (c *Caser) ToCamel(s string) string](#Caser.ToCamel)
* [func (c *Caser) ToCase(s string, wordCase WordCase, delimiter rune) string](#Caser.ToCase)
* [func (c *Caser) ToKEBAB(s string) string](#Caser.ToKEBAB)
* [func (c *Caser) ToKebab(s string) string](#Caser.ToKebab)
* [func (c *Caser) ToPascal(s string) string](#Caser.ToPascal)
* [func (c *Caser) ToSNAKE(s string) string](#Caser.ToSNAKE)
* [func (c *Caser) ToSnake(s string) string](#Caser.ToSnake)
* [type SplitAction](#SplitAction)
* [type SplitFn](#SplitFn)
* [func NewSplitFn(delimiters []rune, splitOptions ...SplitOption) SplitFn](#NewSplitFn)
* [type SplitOption](#SplitOption)
* [type WordCase](#WordCase)
## <a name="ToCamel">func</a> [ToCamel](./strcase.go#L57)
``` go
func ToCamel(s string) string
```
ToCamel returns words in camelCase (capitalized words concatenated together, with first word lower case).
Also known as lowerCamelCase or mixedCase.
## <a name="ToCase">func</a> [ToCase](./strcase.go#L70)
``` go
func ToCase(s string, wordCase WordCase, delimiter rune) string
```
ToCase returns words in given case and delimiter.
## <a name="ToGoCamel">func</a> [ToGoCamel](./strcase.go#L65)
``` go
func ToGoCamel(s string) string
```
ToGoCamel returns words in camelCase (capitalized words concatenated together, with first word lower case).
Also known as lowerCamelCase or mixedCase.
Respects Go's common initialisms (e.g. httpResponse -> HTTPResponse).
## <a name="ToGoCase">func</a> [ToGoCase](./strcase.go#L77)
``` go
func ToGoCase(s string, wordCase WordCase, delimiter rune) string
```
ToGoCase returns words in given case and delimiter.
Respects Go's common initialisms (e.g. httpResponse -> HTTPResponse).
## <a name="ToGoKebab">func</a> [ToGoKebab](./strcase.go#L31)
``` go
func ToGoKebab(s string) string
```
ToGoKebab returns words in kebab-case (lower case words with dashes).
Also known as dash-case.
Respects Go's common initialisms (e.g. http-response -> HTTP-response).
## <a name="ToGoPascal">func</a> [ToGoPascal](./strcase.go#L51)
``` go
func ToGoPascal(s string) string
```
ToGoPascal returns words in PascalCase (capitalized words concatenated together).
Also known as UpperPascalCase.
Respects Go's common initialisms (e.g. HttpResponse -> HTTPResponse).
## <a name="ToGoSnake">func</a> [ToGoSnake](./strcase.go#L11)
``` go
func ToGoSnake(s string) string
```
ToGoSnake returns words in snake_case (lower case words with underscores).
Respects Go's common initialisms (e.g. http_response -> HTTP_response).
## <a name="ToKEBAB">func</a> [ToKEBAB](./strcase.go#L37)
``` go
func ToKEBAB(s string) string
```
ToKEBAB returns words in KEBAB-CASE (upper case words with dashes).
Also known as SCREAMING-KEBAB-CASE or SCREAMING-DASH-CASE.
## <a name="ToKebab">func</a> [ToKebab](./strcase.go#L23)
``` go
func ToKebab(s string) string
```
ToKebab returns words in kebab-case (lower case words with dashes).
Also known as dash-case.
## <a name="ToPascal">func</a> [ToPascal](./strcase.go#L43)
``` go
func ToPascal(s string) string
```
ToPascal returns words in PascalCase (capitalized words concatenated together).
Also known as UpperPascalCase.
## <a name="ToSNAKE">func</a> [ToSNAKE](./strcase.go#L17)
``` go
func ToSNAKE(s string) string
```
ToSNAKE returns words in SNAKE_CASE (upper case words with underscores).
Also known as SCREAMING_SNAKE_CASE or UPPER_CASE.
## <a name="ToSnake">func</a> [ToSnake](./strcase.go#L4)
``` go
func ToSnake(s string) string
```
ToSnake returns words in snake_case (lower case words with underscores).
## <a name="Caser">type</a> [Caser](./caser.go#L4-L7)
``` go
type Caser struct {
// contains filtered or unexported fields
}
```
Caser allows for customization of parsing and intialisms
### <a name="NewCaser">func</a> [NewCaser](./caser.go#L24)
``` go
func NewCaser(goInitialisms bool, initialismOverrides map[string]bool, splitFn SplitFn) *Caser
```
NewCaser returns a configured Caser.
A Caser should be created when you want fine grained control over how the words are split.
Notes on function arguments
goInitialisms: Whether to use Golint's intialisms
initialismOverrides: A mapping of extra initialisms
Keys must be in ALL CAPS. Merged with Golint's if goInitialisms is set.
Setting a key to false will override Golint's.
splitFn: How to separate words
Override the default split function. Consider using NewSplitFn to
configure one instead of writing your own.
### <a name="Caser.ToCamel">func</a> (\*Caser) [ToCamel](./caser.go#L80)
``` go
func (c *Caser) ToCamel(s string) string
```
ToCamel returns words in camelCase (capitalized words concatenated together, with first word lower case).
Also known as lowerCamelCase or mixedCase.
### <a name="Caser.ToCase">func</a> (\*Caser) [ToCase](./caser.go#L85)
``` go
func (c *Caser) ToCase(s string, wordCase WordCase, delimiter rune) string
```
ToCase returns words with a given case and delimiter.
### <a name="Caser.ToKEBAB">func</a> (\*Caser) [ToKEBAB](./caser.go#L68)
``` go
func (c *Caser) ToKEBAB(s string) string
```
ToKEBAB returns words in KEBAB-CASE (upper case words with dashes).
Also known as SCREAMING-KEBAB-CASE or SCREAMING-DASH-CASE.
### <a name="Caser.ToKebab">func</a> (\*Caser) [ToKebab](./caser.go#L62)
``` go
func (c *Caser) ToKebab(s string) string
```
ToKebab returns words in kebab-case (lower case words with dashes).
Also known as dash-case.
### <a name="Caser.ToPascal">func</a> (\*Caser) [ToPascal](./caser.go#L74)
``` go
func (c *Caser) ToPascal(s string) string
```
ToPascal returns words in PascalCase (capitalized words concatenated together).
Also known as UpperPascalCase.
### <a name="Caser.ToSNAKE">func</a> (\*Caser) [ToSNAKE](./caser.go#L56)
``` go
func (c *Caser) ToSNAKE(s string) string
```
ToSNAKE returns words in SNAKE_CASE (upper case words with underscores).
Also known as SCREAMING_SNAKE_CASE or UPPER_CASE.
### <a name="Caser.ToSnake">func</a> (\*Caser) [ToSnake](./caser.go#L50)
``` go
func (c *Caser) ToSnake(s string) string
```
ToSnake returns words in snake_case (lower case words with underscores).
## <a name="SplitAction">type</a> [SplitAction](./split.go#L110)
``` go
type SplitAction int
```
SplitAction defines if and how to split a string
``` go
const (
// Noop - Continue to next character
Noop SplitAction = iota
// Split - Split between words
// e.g. to split between wordsWithoutDelimiters
Split
// SkipSplit - Split the word and drop the character
// e.g. to split words with delimiters
SkipSplit
// Skip - Remove the character completely
Skip
)
```
## <a name="SplitFn">type</a> [SplitFn](./split.go#L6)
``` go
type SplitFn func(prev, curr, next rune) SplitAction
```
SplitFn defines how to split a string into words
### <a name="NewSplitFn">func</a> [NewSplitFn](./split.go#L14-L17)
``` go
func NewSplitFn(
delimiters []rune,
splitOptions ...SplitOption,
) SplitFn
```
NewSplitFn returns a SplitFn based on the options provided.
NewSplitFn covers the majority of common options that other strcase
libraries provide and should allow you to simply create a custom caser.
For more complicated use cases, feel free to write your own SplitFn
nolint:gocyclo
## <a name="SplitOption">type</a> [SplitOption](./split.go#L93)
``` go
type SplitOption int
```
SplitOption are options that allow for configuring NewSplitFn
``` go
const (
// SplitCase - FooBar -> Foo_Bar
SplitCase SplitOption = iota
// SplitAcronym - FOOBar -> Foo_Bar
// It won't preserve FOO's case. If you want, you can set the Caser's initialisms so FOO will be in all caps
SplitAcronym
// SplitBeforeNumber - port80 -> port_80
SplitBeforeNumber
// SplitAfterNumber - 200status -> 200_status
SplitAfterNumber
// PreserveNumberFormatting - a.b.2,000.3.c -> a_b_2,000.3_c
PreserveNumberFormatting
)
```
## <a name="WordCase">type</a> [WordCase](./convert.go#L6)
``` go
type WordCase int
```
WordCase is an enumeration of the ways to format a word.
``` go
const (
// Original - Preserve the original input strcase
Original WordCase = iota
// LowerCase - All letters lower cased (example)
LowerCase
// UpperCase - All letters upper cased (EXAMPLE)
UpperCase
// TitleCase - Only first letter upper cased (Example)
TitleCase
// CamelCase - TitleCase except lower case first word (exampleText)
CamelCase
)
```

View File

@ -1,87 +0,0 @@
package strcase
// Caser allows for customization of parsing and intialisms
type Caser struct {
initialisms map[string]bool
splitFn SplitFn
}
// NewCaser returns a configured Caser.
//
// A Caser should be created when you want fine grained control over how the words are split.
//
// Notes on function arguments
//
// goInitialisms: Whether to use Golint's intialisms
//
// initialismOverrides: A mapping of extra initialisms
// Keys must be in ALL CAPS. Merged with Golint's if goInitialisms is set.
// Setting a key to false will override Golint's.
//
// splitFn: How to separate words
// Override the default split function. Consider using NewSplitFn to
// configure one instead of writing your own.
func NewCaser(goInitialisms bool, initialismOverrides map[string]bool, splitFn SplitFn) *Caser {
c := &Caser{
initialisms: golintInitialisms,
splitFn: splitFn,
}
if c.splitFn == nil {
c.splitFn = defaultSplitFn
}
if goInitialisms && initialismOverrides != nil {
c.initialisms = map[string]bool{}
for k, v := range golintInitialisms {
c.initialisms[k] = v
}
for k, v := range initialismOverrides {
c.initialisms[k] = v
}
} else if !goInitialisms {
c.initialisms = initialismOverrides
}
return c
}
// ToSnake returns words in snake_case (lower case words with underscores).
func (c *Caser) ToSnake(s string) string {
return convert(s, c.splitFn, '_', LowerCase, c.initialisms)
}
// ToSNAKE returns words in SNAKE_CASE (upper case words with underscores).
// Also known as SCREAMING_SNAKE_CASE or UPPER_CASE.
func (c *Caser) ToSNAKE(s string) string {
return convert(s, c.splitFn, '_', UpperCase, c.initialisms)
}
// ToKebab returns words in kebab-case (lower case words with dashes).
// Also known as dash-case.
func (c *Caser) ToKebab(s string) string {
return convert(s, c.splitFn, '-', LowerCase, c.initialisms)
}
// ToKEBAB returns words in KEBAB-CASE (upper case words with dashes).
// Also known as SCREAMING-KEBAB-CASE or SCREAMING-DASH-CASE.
func (c *Caser) ToKEBAB(s string) string {
return convert(s, c.splitFn, '-', UpperCase, c.initialisms)
}
// ToPascal returns words in PascalCase (capitalized words concatenated together).
// Also known as UpperPascalCase.
func (c *Caser) ToPascal(s string) string {
return convert(s, c.splitFn, '\x00', TitleCase, c.initialisms)
}
// ToCamel returns words in camelCase (capitalized words concatenated together, with first word lower case).
// Also known as lowerCamelCase or mixedCase.
func (c *Caser) ToCamel(s string) string {
return convert(s, c.splitFn, '\x00', CamelCase, c.initialisms)
}
// ToCase returns words with a given case and delimiter.
func (c *Caser) ToCase(s string, wordCase WordCase, delimiter rune) string {
return convert(s, c.splitFn, delimiter, wordCase, c.initialisms)
}

View File

@ -1,297 +0,0 @@
package strcase
import "strings"
// WordCase is an enumeration of the ways to format a word.
type WordCase int
const (
// Original - Preserve the original input strcase
Original WordCase = iota
// LowerCase - All letters lower cased (example)
LowerCase
// UpperCase - All letters upper cased (EXAMPLE)
UpperCase
// TitleCase - Only first letter upper cased (Example)
TitleCase
// CamelCase - TitleCase except lower case first word (exampleText)
// Notably, even if the first word is an initialism, it will be lower
// cased. This is important for code generators where capital letters
// mean exported functions. i.e. jsonString(), not JSONString()
CamelCase
)
// We have 3 convert functions for performance reasons
// The general convert could handle everything, but is not optimized
//
// The other two functions are optimized for the general use cases - that is the non-custom caser functions
// Case 1: Any Case and supports Go Initialisms
// Case 2: UpperCase words, which don't need to support initialisms since everything is in upper case
// convertWithoutInitialims only works for to UpperCase and LowerCase
//nolint:gocyclo
func convertWithoutInitialisms(input string, delimiter rune, wordCase WordCase) string {
input = strings.TrimSpace(input)
runes := []rune(input)
if len(runes) == 0 {
return ""
}
var b strings.Builder
b.Grow(len(input) * 2) // In case we need to write delimiters where they weren't before
var prev, curr rune
next := runes[0] // 0 length will have already returned so safe to index
inWord := false
firstWord := true
for i := 0; i < len(runes); i++ {
prev = curr
curr = next
if i+1 == len(runes) {
next = 0
} else {
next = runes[i+1]
}
switch defaultSplitFn(prev, curr, next) {
case SkipSplit:
if inWord && delimiter != 0 {
b.WriteRune(delimiter)
}
inWord = false
continue
case Split:
if inWord && delimiter != 0 {
b.WriteRune(delimiter)
}
inWord = false
}
switch wordCase {
case UpperCase:
b.WriteRune(toUpper(curr))
case LowerCase:
b.WriteRune(toLower(curr))
case TitleCase:
if inWord {
b.WriteRune(toLower(curr))
} else {
b.WriteRune(toUpper(curr))
}
case CamelCase:
if inWord {
b.WriteRune(toLower(curr))
} else if firstWord {
b.WriteRune(toLower(curr))
firstWord = false
} else {
b.WriteRune(toUpper(curr))
}
default:
// Must be original case
b.WriteRune(curr)
}
inWord = inWord || true
}
return b.String()
}
// convertWithGoInitialisms changes a input string to a certain case with a
// delimiter, respecting go initialisms but not skip runes
//nolint:gocyclo
func convertWithGoInitialisms(input string, delimiter rune, wordCase WordCase) string {
input = strings.TrimSpace(input)
runes := []rune(input)
if len(runes) == 0 {
return ""
}
var b strings.Builder
b.Grow(len(input) * 2) // In case we need to write delimiters where they weren't before
firstWord := true
addWord := func(start, end int) {
if start == end {
return
}
if !firstWord && delimiter != 0 {
b.WriteRune(delimiter)
}
// Don't bother with initialisms if the word is longer than 5
// A quick proxy to avoid the extra memory allocations
if end-start <= 5 {
key := strings.ToUpper(string(runes[start:end]))
if golintInitialisms[key] {
if !firstWord || wordCase != CamelCase {
b.WriteString(key)
firstWord = false
return
}
}
}
for i := start; i < end; i++ {
r := runes[i]
switch wordCase {
case UpperCase:
panic("use convertWithoutInitialisms instead")
case LowerCase:
b.WriteRune(toLower(r))
case TitleCase:
if i == start {
b.WriteRune(toUpper(r))
} else {
b.WriteRune(toLower(r))
}
case CamelCase:
if !firstWord && i == start {
b.WriteRune(toUpper(r))
} else {
b.WriteRune(toLower(r))
}
default:
b.WriteRune(r)
}
}
firstWord = false
}
var prev, curr rune
next := runes[0] // 0 length will have already returned so safe to index
wordStart := 0
for i := 0; i < len(runes); i++ {
prev = curr
curr = next
if i+1 == len(runes) {
next = 0
} else {
next = runes[i+1]
}
switch defaultSplitFn(prev, curr, next) {
case Split:
addWord(wordStart, i)
wordStart = i
case SkipSplit:
addWord(wordStart, i)
wordStart = i + 1
}
}
if wordStart != len(runes) {
addWord(wordStart, len(runes))
}
return b.String()
}
// convert changes a input string to a certain case with a delimiter,
// respecting arbitrary initialisms and skip characters
//nolint:gocyclo
func convert(input string, fn SplitFn, delimiter rune, wordCase WordCase,
initialisms map[string]bool) string {
input = strings.TrimSpace(input)
runes := []rune(input)
if len(runes) == 0 {
return ""
}
var b strings.Builder
b.Grow(len(input) * 2) // In case we need to write delimiters where they weren't before
firstWord := true
var skipIndexes []int
addWord := func(start, end int) {
// If you have nothing good to say, say nothing at all
if start == end || len(skipIndexes) == end-start {
skipIndexes = nil
return
}
// If you have something to say, start with a delimiter
if !firstWord && delimiter != 0 {
b.WriteRune(delimiter)
}
// Check if you're an initialism
// Note - we don't check skip characters here since initialisms
// will probably never have junk characters in between
// I'm open to it if there is a use case
if initialisms != nil {
var word strings.Builder
for i := start; i < end; i++ {
word.WriteRune(toUpper(runes[i]))
}
key := word.String()
if initialisms[key] {
if !firstWord || wordCase != CamelCase {
b.WriteString(key)
firstWord = false
return
}
}
}
skipIdx := 0
for i := start; i < end; i++ {
if len(skipIndexes) > 0 && skipIdx < len(skipIndexes) && i == skipIndexes[skipIdx] {
skipIdx++
continue
}
r := runes[i]
switch wordCase {
case UpperCase:
b.WriteRune(toUpper(r))
case LowerCase:
b.WriteRune(toLower(r))
case TitleCase:
if i == start {
b.WriteRune(toUpper(r))
} else {
b.WriteRune(toLower(r))
}
case CamelCase:
if !firstWord && i == start {
b.WriteRune(toUpper(r))
} else {
b.WriteRune(toLower(r))
}
default:
b.WriteRune(r)
}
}
firstWord = false
skipIndexes = nil
}
var prev, curr rune
next := runes[0] // 0 length will have already returned so safe to index
wordStart := 0
for i := 0; i < len(runes); i++ {
prev = curr
curr = next
if i+1 == len(runes) {
next = 0
} else {
next = runes[i+1]
}
switch fn(prev, curr, next) {
case Skip:
skipIndexes = append(skipIndexes, i)
case Split:
addWord(wordStart, i)
wordStart = i
case SkipSplit:
addWord(wordStart, i)
wordStart = i + 1
}
}
if wordStart != len(runes) {
addWord(wordStart, len(runes))
}
return b.String()
}

View File

@ -1,155 +0,0 @@
/*
Package strcase is a package for converting strings into various word cases
(e.g. snake_case, camelCase)
go get -u github.com/ettle/strcase
Example usage
strcase.ToSnake("Hello World") // hello_world
strcase.ToSNAKE("Hello World") // HELLO_WORLD
strcase.ToKebab("helloWorld") // hello-world
strcase.ToKEBAB("helloWorld") // HELLO-WORLD
strcase.ToPascal("hello-world") // HelloWorld
strcase.ToCamel("hello-world") // helloWorld
// Handle odd cases
strcase.ToSnake("FOOBar") // foo_bar
// Support Go initialisms
strcase.ToGoPascal("http_response") // HTTPResponse
// Specify case and delimiter
strcase.ToCase("HelloWorld", strcase.UpperCase, '.') // HELLO.WORLD
Why this package
String strcase is pretty straight forward and there are a number of methods to
do it. This package is fully featured, more customizable, better tested, and
faster* than other packages and what you would probably whip up yourself.
Unicode support
We work for with unicode strings and pay very little performance penalty for it
as we optimized for the common use case of ASCII only strings.
Customization
You can create a custom caser that changes the behavior to what you want. This
customization also reduces the pressure for us to change the default behavior
which means that things are more stable for everyone involved. The goal is to
make the common path easy and fast, while making the uncommon path possible.
c := NewCaser(
// Use Go's default initialisms e.g. ID, HTML
true,
// Override initialisms (e.g. don't initialize HTML but initialize SSL
map[string]bool{"SSL": true, "HTML": false},
// Write your own custom SplitFn
//
NewSplitFn(
[]rune{'*', '.', ','},
SplitCase,
SplitAcronym,
PreserveNumberFormatting,
SplitBeforeNumber,
SplitAfterNumber,
))
assert.Equal(t, "http_200", c.ToSnake("http200"))
Initialism support
By default, we use the golint intialisms list. You can customize and override
the initialisms if you wish to add additional ones, such as "SSL" or "CMS" or
domain specific ones to your industry.
ToGoPascal("http_response") // HTTPResponse
ToGoSnake("http_response") // HTTP_response
Test coverage
We have a wide ranging test suite to make sure that we understand our behavior.
Test coverage isn't everything, but we aim for 100% coverage.
Fast
Optimized to reduce memory allocations with Builder. Benchmarked and optimized
around common cases.
We're on par with the fastest packages (that have less features) and much
faster than others. We also benchmarked against code snippets. Using string
builders to reduce memory allocation and reordering boolean checks for the
common cases have a large performance impact.
Hopefully I was fair to each library and happy to rerun benchmarks differently
or reword my commentary based on suggestions or updates.
// This package - faster then almost all libraries
// Initialisms are more complicated and slightly slower, but still faster then other libraries that do less
BenchmarkToTitle-4 7821166 221 ns/op 32 B/op 1 allocs/op
BenchmarkToSnake-4 9378589 202 ns/op 32 B/op 1 allocs/op
BenchmarkToSNAKE-4 6174453 223 ns/op 32 B/op 1 allocs/op
BenchmarkToGoSnake-4 3114266 434 ns/op 44 B/op 4 allocs/op
BenchmarkToCustomCaser-4 2973855 448 ns/op 56 B/op 4 allocs/op
// Segment has very fast snake case and camel case libraries
// No features or customization, but very very fast
BenchmarkSegment-4 24003495 64.9 ns/op 16 B/op 1 allocs/op
// Stdlib strings.Title for comparison, even though it only splits on spaces
BenchmarkToTitleStrings-4 11259376 161 ns/op 16 B/op 1 allocs/op
// Other libraries or code snippets
// - Most are slower, by up to an order of magnitude
// - None support initialisms or customization
// - Some generate only camelCase or snake_case
// - Many lack unicode support
BenchmarkToSnakeStoewer-4 7103268 297 ns/op 64 B/op 2 allocs/op
// Copying small rune arrays is slow
BenchmarkToSnakeSiongui-4 3710768 413 ns/op 48 B/op 10 allocs/op
BenchmarkGoValidator-4 2416479 1049 ns/op 184 B/op 9 allocs/op
// String alloction is slow
BenchmarkToSnakeFatih-4 1000000 2407 ns/op 624 B/op 26 allocs/op
BenchmarkToSnakeIanColeman-4 1005766 1426 ns/op 160 B/op 13 allocs/op
// Regexp is slow
BenchmarkToSnakeGolangPrograms-4 614689 2237 ns/op 225 B/op 11 allocs/op
// These results aren't a surprise - my initial version of this library was
// painfully slow. I think most of us, without spending some time with
// profilers and benchmarks, would write also something on the slower side.
Why not this package
If every nanosecond matters and this is used in a tight loop, use segment.io's
libraries (https://github.com/segmentio/go-snakecase and
https://github.com/segmentio/go-camelcase). They lack features, but make up for
it by being blazing fast. Alternatively, if you need your code to work slightly
differently, fork them and tailor it for your use case.
If you don't like having external imports, I get it. This package only imports
packages for testing, otherwise it only uses the standard library. If that's
not enough, you can use this repo as the foundation for your own. MIT Licensed.
This package is still relatively new and while I've used it for a while
personally, it doesn't have the miles that other packages do. I've tested this
code agains't their test cases to make sure that there aren't any surprises.
Migrating from other packages
If you are migrating from from another package, you may find slight differences
in output. To reduce the delta, you may find it helpful to use the following
custom casers to mimic the behavior of the other package.
// From https://github.com/iancoleman/strcase
var c = NewCaser(false, nil, NewSplitFn([]rune{'_', '-', '.'}, SplitCase, SplitAcronym, SplitBeforeNumber))
// From https://github.com/stoewer/go-strcase
var c = NewCaser(false, nil, NewSplitFn([]rune{'_', '-'}, SplitCase), SplitAcronym)
*/
package strcase

View File

@ -1,43 +0,0 @@
package strcase
// golintInitialisms are the golint initialisms
var golintInitialisms = map[string]bool{
"ACL": true,
"API": true,
"ASCII": true,
"CPU": true,
"CSS": true,
"DNS": true,
"EOF": true,
"GUID": true,
"HTML": true,
"HTTP": true,
"HTTPS": true,
"ID": true,
"IP": true,
"JSON": true,
"LHS": true,
"QPS": true,
"RAM": true,
"RHS": true,
"RPC": true,
"SLA": true,
"SMTP": true,
"SQL": true,
"SSH": true,
"TCP": true,
"TLS": true,
"TTL": true,
"UDP": true,
"UI": true,
"UID": true,
"UUID": true,
"URI": true,
"URL": true,
"UTF8": true,
"VM": true,
"XML": true,
"XMPP": true,
"XSRF": true,
"XSS": true,
}

View File

@ -1,164 +0,0 @@
package strcase
import "unicode"
// SplitFn defines how to split a string into words
type SplitFn func(prev, curr, next rune) SplitAction
// NewSplitFn returns a SplitFn based on the options provided.
//
// NewSplitFn covers the majority of common options that other strcase
// libraries provide and should allow you to simply create a custom caser.
// For more complicated use cases, feel free to write your own SplitFn
//nolint:gocyclo
func NewSplitFn(
delimiters []rune,
splitOptions ...SplitOption,
) SplitFn {
var splitCase, splitAcronym, splitBeforeNumber, splitAfterNumber, preserveNumberFormatting bool
for _, option := range splitOptions {
switch option {
case SplitCase:
splitCase = true
case SplitAcronym:
splitAcronym = true
case SplitBeforeNumber:
splitBeforeNumber = true
case SplitAfterNumber:
splitAfterNumber = true
case PreserveNumberFormatting:
preserveNumberFormatting = true
}
}
return func(prev, curr, next rune) SplitAction {
// The most common case will be that it's just a letter
// There are safe cases to process
if isLower(curr) && !isNumber(prev) {
return Noop
}
if isUpper(prev) && isUpper(curr) && isUpper(next) {
return Noop
}
if preserveNumberFormatting {
if (curr == '.' || curr == ',') &&
isNumber(prev) && isNumber(next) {
return Noop
}
}
if unicode.IsSpace(curr) {
return SkipSplit
}
for _, d := range delimiters {
if curr == d {
return SkipSplit
}
}
if splitBeforeNumber {
if isNumber(curr) && !isNumber(prev) {
if preserveNumberFormatting && (prev == '.' || prev == ',') {
return Noop
}
return Split
}
}
if splitAfterNumber {
if isNumber(prev) && !isNumber(curr) {
return Split
}
}
if splitCase {
if !isUpper(prev) && isUpper(curr) {
return Split
}
}
if splitAcronym {
if isUpper(prev) && isUpper(curr) && isLower(next) {
return Split
}
}
return Noop
}
}
// SplitOption are options that allow for configuring NewSplitFn
type SplitOption int
const (
// SplitCase - FooBar -> Foo_Bar
SplitCase SplitOption = iota
// SplitAcronym - FOOBar -> Foo_Bar
// It won't preserve FOO's case. If you want, you can set the Caser's initialisms so FOO will be in all caps
SplitAcronym
// SplitBeforeNumber - port80 -> port_80
SplitBeforeNumber
// SplitAfterNumber - 200status -> 200_status
SplitAfterNumber
// PreserveNumberFormatting - a.b.2,000.3.c -> a_b_2,000.3_c
PreserveNumberFormatting
)
// SplitAction defines if and how to split a string
type SplitAction int
const (
// Noop - Continue to next character
Noop SplitAction = iota
// Split - Split between words
// e.g. to split between wordsWithoutDelimiters
Split
// SkipSplit - Split the word and drop the character
// e.g. to split words with delimiters
SkipSplit
// Skip - Remove the character completely
Skip
)
//nolint:gocyclo
func defaultSplitFn(prev, curr, next rune) SplitAction {
// The most common case will be that it's just a letter so let lowercase letters return early since we know what they should do
if isLower(curr) {
return Noop
}
// Delimiters are _, -, ., and unicode spaces
// Handle . lower down as it needs to happen after number exceptions
if curr == '_' || curr == '-' || isSpace(curr) {
return SkipSplit
}
if isUpper(curr) {
if isLower(prev) {
// fooBar
return Split
} else if isUpper(prev) && isLower(next) {
// FOOBar
return Split
}
}
// Do numeric exceptions last to avoid perf penalty
if unicode.IsNumber(prev) {
// v4.3 is not split
if (curr == '.' || curr == ',') && unicode.IsNumber(next) {
return Noop
}
if !unicode.IsNumber(curr) && curr != '.' {
return Split
}
}
// While period is a default delimiter, keep it down here to avoid
// penalty for other delimiters
if curr == '.' {
return SkipSplit
}
return Noop
}

View File

@ -1,81 +0,0 @@
package strcase
// ToSnake returns words in snake_case (lower case words with underscores).
func ToSnake(s string) string {
return convertWithoutInitialisms(s, '_', LowerCase)
}
// ToGoSnake returns words in snake_case (lower case words with underscores).
//
// Respects Go's common initialisms (e.g. http_response -> HTTP_response).
func ToGoSnake(s string) string {
return convertWithGoInitialisms(s, '_', LowerCase)
}
// ToSNAKE returns words in SNAKE_CASE (upper case words with underscores).
// Also known as SCREAMING_SNAKE_CASE or UPPER_CASE.
func ToSNAKE(s string) string {
return convertWithoutInitialisms(s, '_', UpperCase)
}
// ToKebab returns words in kebab-case (lower case words with dashes).
// Also known as dash-case.
func ToKebab(s string) string {
return convertWithoutInitialisms(s, '-', LowerCase)
}
// ToGoKebab returns words in kebab-case (lower case words with dashes).
// Also known as dash-case.
//
// Respects Go's common initialisms (e.g. http-response -> HTTP-response).
func ToGoKebab(s string) string {
return convertWithGoInitialisms(s, '-', LowerCase)
}
// ToKEBAB returns words in KEBAB-CASE (upper case words with dashes).
// Also known as SCREAMING-KEBAB-CASE or SCREAMING-DASH-CASE.
func ToKEBAB(s string) string {
return convertWithoutInitialisms(s, '-', UpperCase)
}
// ToPascal returns words in PascalCase (capitalized words concatenated together).
// Also known as UpperPascalCase.
func ToPascal(s string) string {
return convertWithoutInitialisms(s, 0, TitleCase)
}
// ToGoPascal returns words in PascalCase (capitalized words concatenated together).
// Also known as UpperPascalCase.
//
// Respects Go's common initialisms (e.g. HttpResponse -> HTTPResponse).
func ToGoPascal(s string) string {
return convertWithGoInitialisms(s, 0, TitleCase)
}
// ToCamel returns words in camelCase (capitalized words concatenated together, with first word lower case).
// Also known as lowerCamelCase or mixedCase.
func ToCamel(s string) string {
return convertWithoutInitialisms(s, 0, CamelCase)
}
// ToGoCamel returns words in camelCase (capitalized words concatenated together, with first word lower case).
// Also known as lowerCamelCase or mixedCase.
//
// Respects Go's common initialisms, but first word remains lowercased which is
// important for code generator use cases (e.g. toJson -> toJSON, httpResponse
// -> httpResponse).
func ToGoCamel(s string) string {
return convertWithGoInitialisms(s, 0, CamelCase)
}
// ToCase returns words in given case and delimiter.
func ToCase(s string, wordCase WordCase, delimiter rune) string {
return convertWithoutInitialisms(s, delimiter, wordCase)
}
// ToGoCase returns words in given case and delimiter.
//
// Respects Go's common initialisms (e.g. httpResponse -> HTTPResponse).
func ToGoCase(s string, wordCase WordCase, delimiter rune) string {
return convertWithGoInitialisms(s, delimiter, wordCase)
}

View File

@ -1,48 +0,0 @@
package strcase
import "unicode"
// Unicode functions, optimized for the common case of ascii
// No performance lost by wrapping since these functions get inlined by the compiler
func isUpper(r rune) bool {
return unicode.IsUpper(r)
}
func isLower(r rune) bool {
return unicode.IsLower(r)
}
func isNumber(r rune) bool {
if r >= '0' && r <= '9' {
return true
}
return unicode.IsNumber(r)
}
func isSpace(r rune) bool {
if r == ' ' || r == '\t' || r == '\n' || r == '\r' {
return true
} else if r < 128 {
return false
}
return unicode.IsSpace(r)
}
func toUpper(r rune) rune {
if r >= 'a' && r <= 'z' {
return r - 32
} else if r < 128 {
return r
}
return unicode.ToUpper(r)
}
func toLower(r rune) rune {
if r >= 'A' && r <= 'Z' {
return r + 32
} else if r < 128 {
return r
}
return unicode.ToLower(r)
}

View File

@ -1,20 +0,0 @@
The MIT License (MIT)
Copyright (c) 2013 Fatih Arslan
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.

View File

@ -1,178 +0,0 @@
# 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://user-images.githubusercontent.com/438920/96832689-03b3e000-13f4-11eb-9803-46f4c4de3406.jpg)
## Install
```bash
go get github.com/fatih/color
```
## Examples
### Standard colors
```go
// Print with default helper functions
color.Cyan("Prints text in cyan.")
// A newline will be appended automatically
color.Blue("Prints %s in blue.", "text")
// These are using the default foreground colors
color.Red("We have red")
color.Magenta("And many others ..")
```
### Mix and reuse colors
```go
// Create a new color object
c := color.New(color.FgCyan).Add(color.Underline)
c.Println("Prints cyan text with an underline.")
// Or just add them to New()
d := color.New(color.FgCyan, color.Bold)
d.Printf("This prints bold cyan %s\n", "too!.")
// Mix up foreground and background colors, create new mixes!
red := color.New(color.FgRed)
boldRed := red.Add(color.Bold)
boldRed.Println("This will print text in bold red.")
whiteBackground := red.Add(color.BgWhite)
whiteBackground.Println("Red text with white background.")
```
### Use your own output (io.Writer)
```go
// Use your own io.Writer output
color.New(color.FgBlue).Fprintln(myWriter, "blue color!")
blue := color.New(color.FgBlue)
blue.Fprint(writer, "This will print text in blue.")
```
### Custom print functions (PrintFunc)
```go
// Create a custom print function for convenience
red := color.New(color.FgRed).PrintfFunc()
red("Warning")
red("Error: %s", err)
// Mix up multiple attributes
notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
notice("Don't forget this...")
```
### Custom fprint functions (FprintFunc)
```go
blue := color.New(FgBlue).FprintfFunc()
blue(myWriter, "important notice: %s", stars)
// Mix up with multiple attributes
success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
success(myWriter, "Don't forget this...")
```
### Insert into noncolor strings (SprintFunc)
```go
// Create SprintXxx functions to mix strings with other non-colorized strings:
yellow := color.New(color.FgYellow).SprintFunc()
red := color.New(color.FgRed).SprintFunc()
fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error"))
info := color.New(color.FgWhite, color.BgGreen).SprintFunc()
fmt.Printf("This %s rocks!\n", info("package"))
// Use helper functions
fmt.Println("This", color.RedString("warning"), "should be not neglected.")
fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.")
// Windows supported too! Just don't forget to change the output to color.Output
fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
```
### Plug into existing code
```go
// Use handy standard colors
color.Set(color.FgYellow)
fmt.Println("Existing text will now be in yellow")
fmt.Printf("This one %s\n", "too")
color.Unset() // Don't forget to unset
// You can mix up parameters
color.Set(color.FgMagenta, color.Bold)
defer color.Unset() // Use it in your function
fmt.Println("All text will now be bold magenta.")
```
### Disable/Enable color
There might be a case where you want to explicitly disable/enable color output. the
`go-isatty` package will automatically disable color output for non-tty output streams
(for example if the output were piped directly to `less`).
The `color` package also disables color output if the [`NO_COLOR`](https://no-color.org) environment
variable is set (regardless of its value).
`Color` has support to disable/enable colors programatically both globally and
for single color definitions. For example suppose you have a CLI app and a
`--no-color` bool flag. You can easily disable the color output with:
```go
var flagNoColor = flag.Bool("no-color", false, "Disable color output")
if *flagNoColor {
color.NoColor = true // disables colorized output
}
```
It also has support for single color definitions (local). You can
disable/enable color output on the fly:
```go
c := color.New(color.FgCyan)
c.Println("Prints cyan text")
c.DisableColor()
c.Println("This is printed without any color")
c.EnableColor()
c.Println("This prints again cyan...")
```
## GitHub Actions
To output color in GitHub Actions (or other CI systems that support ANSI colors), make sure to set `color.NoColor = false` so that it bypasses the check for non-tty output streams.
## Todo
* Save/Return previous values
* Evaluate fmt.Formatter interface
## Credits
* [Fatih Arslan](https://github.com/fatih)
* Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable)
## License
The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details

View File

@ -1,618 +0,0 @@
package color
import (
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
)
var (
// NoColor defines if the output is colorized or not. It's dynamically set to
// false or true based on the stdout's file descriptor referring to a terminal
// or not. It's also set to true if the NO_COLOR environment variable is
// set (regardless of its value). This is a global option and affects all
// colors. For more control over each color block use the methods
// DisableColor() individually.
NoColor = noColorExists() || os.Getenv("TERM") == "dumb" ||
(!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()))
// Output defines the standard output of the print functions. By default
// os.Stdout is used.
Output = colorable.NewColorableStdout()
// Error defines a color supporting writer for os.Stderr.
Error = colorable.NewColorableStderr()
// colorsCache is used to reduce the count of created Color objects and
// allows to reuse already created objects with required Attribute.
colorsCache = make(map[Attribute]*Color)
colorsCacheMu sync.Mutex // protects colorsCache
)
// noColorExists returns true if the environment variable NO_COLOR exists.
func noColorExists() bool {
_, exists := os.LookupEnv("NO_COLOR")
return exists
}
// Color defines a custom color object which is defined by SGR parameters.
type Color struct {
params []Attribute
noColor *bool
}
// Attribute defines a single SGR Code
type Attribute int
const escape = "\x1b"
// Base attributes
const (
Reset Attribute = iota
Bold
Faint
Italic
Underline
BlinkSlow
BlinkRapid
ReverseVideo
Concealed
CrossedOut
)
// Foreground text colors
const (
FgBlack Attribute = iota + 30
FgRed
FgGreen
FgYellow
FgBlue
FgMagenta
FgCyan
FgWhite
)
// Foreground Hi-Intensity text colors
const (
FgHiBlack Attribute = iota + 90
FgHiRed
FgHiGreen
FgHiYellow
FgHiBlue
FgHiMagenta
FgHiCyan
FgHiWhite
)
// Background text colors
const (
BgBlack Attribute = iota + 40
BgRed
BgGreen
BgYellow
BgBlue
BgMagenta
BgCyan
BgWhite
)
// Background Hi-Intensity text colors
const (
BgHiBlack Attribute = iota + 100
BgHiRed
BgHiGreen
BgHiYellow
BgHiBlue
BgHiMagenta
BgHiCyan
BgHiWhite
)
// New returns a newly created color object.
func New(value ...Attribute) *Color {
c := &Color{
params: make([]Attribute, 0),
}
if noColorExists() {
c.noColor = boolPtr(true)
}
c.Add(value...)
return c
}
// Set sets the given parameters immediately. It will change the color of
// output with the given SGR parameters until color.Unset() is called.
func Set(p ...Attribute) *Color {
c := New(p...)
c.Set()
return c
}
// Unset resets all escape attributes and clears the output. Usually should
// be called after Set().
func Unset() {
if NoColor {
return
}
fmt.Fprintf(Output, "%s[%dm", escape, Reset)
}
// Set sets the SGR sequence.
func (c *Color) Set() *Color {
if c.isNoColorSet() {
return c
}
fmt.Fprintf(Output, c.format())
return c
}
func (c *Color) unset() {
if c.isNoColorSet() {
return
}
Unset()
}
func (c *Color) setWriter(w io.Writer) *Color {
if c.isNoColorSet() {
return c
}
fmt.Fprintf(w, c.format())
return c
}
func (c *Color) unsetWriter(w io.Writer) {
if c.isNoColorSet() {
return
}
if NoColor {
return
}
fmt.Fprintf(w, "%s[%dm", escape, Reset)
}
// Add is used to chain SGR parameters. Use as many as parameters to combine
// and create custom color objects. Example: Add(color.FgRed, color.Underline).
func (c *Color) Add(value ...Attribute) *Color {
c.params = append(c.params, value...)
return c
}
func (c *Color) prepend(value Attribute) {
c.params = append(c.params, 0)
copy(c.params[1:], c.params[0:])
c.params[0] = value
}
// Fprint formats using the default formats for its operands and writes to w.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
return fmt.Fprint(w, a...)
}
// Print formats using the default formats for its operands and writes to
// standard output. Spaces are added between operands when neither is a
// string. It returns the number of bytes written and any write error
// encountered. This is the standard fmt.Print() method wrapped with the given
// color.
func (c *Color) Print(a ...interface{}) (n int, err error) {
c.Set()
defer c.unset()
return fmt.Fprint(Output, a...)
}
// Fprintf formats according to a format specifier and writes to w.
// It returns the number of bytes written and any write error encountered.
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
return fmt.Fprintf(w, format, a...)
}
// Printf formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
// This is the standard fmt.Printf() method wrapped with the given color.
func (c *Color) Printf(format string, a ...interface{}) (n int, err error) {
c.Set()
defer c.unset()
return fmt.Fprintf(Output, format, a...)
}
// Fprintln formats using the default formats for its operands and writes to w.
// Spaces are always added between operands and a newline is appended.
// On Windows, users should wrap w with colorable.NewColorable() if w is of
// type *os.File.
func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
c.setWriter(w)
defer c.unsetWriter(w)
return fmt.Fprintln(w, a...)
}
// Println formats using the default formats for its operands and writes to
// standard output. Spaces are always added between operands and a newline is
// appended. It returns the number of bytes written and any write error
// encountered. This is the standard fmt.Print() method wrapped with the given
// color.
func (c *Color) Println(a ...interface{}) (n int, err error) {
c.Set()
defer c.unset()
return fmt.Fprintln(Output, a...)
}
// Sprint is just like Print, but returns a string instead of printing it.
func (c *Color) Sprint(a ...interface{}) string {
return c.wrap(fmt.Sprint(a...))
}
// Sprintln is just like Println, but returns a string instead of printing it.
func (c *Color) Sprintln(a ...interface{}) string {
return c.wrap(fmt.Sprintln(a...))
}
// Sprintf is just like Printf, but returns a string instead of printing it.
func (c *Color) Sprintf(format string, a ...interface{}) string {
return c.wrap(fmt.Sprintf(format, a...))
}
// FprintFunc returns a new function that prints the passed arguments as
// colorized with color.Fprint().
func (c *Color) FprintFunc() func(w io.Writer, a ...interface{}) {
return func(w io.Writer, a ...interface{}) {
c.Fprint(w, a...)
}
}
// PrintFunc returns a new function that prints the passed arguments as
// colorized with color.Print().
func (c *Color) PrintFunc() func(a ...interface{}) {
return func(a ...interface{}) {
c.Print(a...)
}
}
// FprintfFunc returns a new function that prints the passed arguments as
// colorized with color.Fprintf().
func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...interface{}) {
return func(w io.Writer, format string, a ...interface{}) {
c.Fprintf(w, format, a...)
}
}
// PrintfFunc returns a new function that prints the passed arguments as
// colorized with color.Printf().
func (c *Color) PrintfFunc() func(format string, a ...interface{}) {
return func(format string, a ...interface{}) {
c.Printf(format, a...)
}
}
// FprintlnFunc returns a new function that prints the passed arguments as
// colorized with color.Fprintln().
func (c *Color) FprintlnFunc() func(w io.Writer, a ...interface{}) {
return func(w io.Writer, a ...interface{}) {
c.Fprintln(w, a...)
}
}
// PrintlnFunc returns a new function that prints the passed arguments as
// colorized with color.Println().
func (c *Color) PrintlnFunc() func(a ...interface{}) {
return func(a ...interface{}) {
c.Println(a...)
}
}
// SprintFunc returns a new function that returns colorized strings for the
// given arguments with fmt.Sprint(). Useful to put into or mix into other
// string. Windows users should use this in conjunction with color.Output, example:
//
// put := New(FgYellow).SprintFunc()
// fmt.Fprintf(color.Output, "This is a %s", put("warning"))
func (c *Color) SprintFunc() func(a ...interface{}) string {
return func(a ...interface{}) string {
return c.wrap(fmt.Sprint(a...))
}
}
// SprintfFunc returns a new function that returns colorized strings for the
// given arguments with fmt.Sprintf(). Useful to put into or mix into other
// string. Windows users should use this in conjunction with color.Output.
func (c *Color) SprintfFunc() func(format string, a ...interface{}) string {
return func(format string, a ...interface{}) string {
return c.wrap(fmt.Sprintf(format, a...))
}
}
// SprintlnFunc returns a new function that returns colorized strings for the
// given arguments with fmt.Sprintln(). Useful to put into or mix into other
// string. Windows users should use this in conjunction with color.Output.
func (c *Color) SprintlnFunc() func(a ...interface{}) string {
return func(a ...interface{}) string {
return c.wrap(fmt.Sprintln(a...))
}
}
// sequence returns a formatted SGR sequence to be plugged into a "\x1b[...m"
// an example output might be: "1;36" -> bold cyan
func (c *Color) sequence() string {
format := make([]string, len(c.params))
for i, v := range c.params {
format[i] = strconv.Itoa(int(v))
}
return strings.Join(format, ";")
}
// wrap wraps the s string with the colors attributes. The string is ready to
// be printed.
func (c *Color) wrap(s string) string {
if c.isNoColorSet() {
return s
}
return c.format() + s + c.unformat()
}
func (c *Color) format() string {
return fmt.Sprintf("%s[%sm", escape, c.sequence())
}
func (c *Color) unformat() string {
return fmt.Sprintf("%s[%dm", escape, Reset)
}
// DisableColor disables the color output. Useful to not change any existing
// code and still being able to output. Can be used for flags like
// "--no-color". To enable back use EnableColor() method.
func (c *Color) DisableColor() {
c.noColor = boolPtr(true)
}
// EnableColor enables the color output. Use it in conjunction with
// DisableColor(). Otherwise this method has no side effects.
func (c *Color) EnableColor() {
c.noColor = boolPtr(false)
}
func (c *Color) isNoColorSet() bool {
// check first if we have user set action
if c.noColor != nil {
return *c.noColor
}
// if not return the global option, which is disabled by default
return NoColor
}
// Equals returns a boolean value indicating whether two colors are equal.
func (c *Color) Equals(c2 *Color) bool {
if len(c.params) != len(c2.params) {
return false
}
for _, attr := range c.params {
if !c2.attrExists(attr) {
return false
}
}
return true
}
func (c *Color) attrExists(a Attribute) bool {
for _, attr := range c.params {
if attr == a {
return true
}
}
return false
}
func boolPtr(v bool) *bool {
return &v
}
func getCachedColor(p Attribute) *Color {
colorsCacheMu.Lock()
defer colorsCacheMu.Unlock()
c, ok := colorsCache[p]
if !ok {
c = New(p)
colorsCache[p] = c
}
return c
}
func colorPrint(format string, p Attribute, a ...interface{}) {
c := getCachedColor(p)
if !strings.HasSuffix(format, "\n") {
format += "\n"
}
if len(a) == 0 {
c.Print(format)
} else {
c.Printf(format, a...)
}
}
func colorString(format string, p Attribute, a ...interface{}) string {
c := getCachedColor(p)
if len(a) == 0 {
return c.SprintFunc()(format)
}
return c.SprintfFunc()(format, a...)
}
// Black is a convenient helper function to print with black foreground. A
// newline is appended to format by default.
func Black(format string, a ...interface{}) { colorPrint(format, FgBlack, a...) }
// Red is a convenient helper function to print with red foreground. A
// newline is appended to format by default.
func Red(format string, a ...interface{}) { colorPrint(format, FgRed, a...) }
// Green is a convenient helper function to print with green foreground. A
// newline is appended to format by default.
func Green(format string, a ...interface{}) { colorPrint(format, FgGreen, a...) }
// Yellow is a convenient helper function to print with yellow foreground.
// A newline is appended to format by default.
func Yellow(format string, a ...interface{}) { colorPrint(format, FgYellow, a...) }
// Blue is a convenient helper function to print with blue foreground. A
// newline is appended to format by default.
func Blue(format string, a ...interface{}) { colorPrint(format, FgBlue, a...) }
// Magenta is a convenient helper function to print with magenta foreground.
// A newline is appended to format by default.
func Magenta(format string, a ...interface{}) { colorPrint(format, FgMagenta, a...) }
// Cyan is a convenient helper function to print with cyan foreground. A
// newline is appended to format by default.
func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) }
// White is a convenient helper function to print with white foreground. A
// newline is appended to format by default.
func White(format string, a ...interface{}) { colorPrint(format, FgWhite, a...) }
// BlackString is a convenient helper function to return a string with black
// foreground.
func BlackString(format string, a ...interface{}) string { return colorString(format, FgBlack, a...) }
// RedString is a convenient helper function to return a string with red
// foreground.
func RedString(format string, a ...interface{}) string { return colorString(format, FgRed, a...) }
// GreenString is a convenient helper function to return a string with green
// foreground.
func GreenString(format string, a ...interface{}) string { return colorString(format, FgGreen, a...) }
// YellowString is a convenient helper function to return a string with yellow
// foreground.
func YellowString(format string, a ...interface{}) string { return colorString(format, FgYellow, a...) }
// BlueString is a convenient helper function to return a string with blue
// foreground.
func BlueString(format string, a ...interface{}) string { return colorString(format, FgBlue, a...) }
// MagentaString is a convenient helper function to return a string with magenta
// foreground.
func MagentaString(format string, a ...interface{}) string {
return colorString(format, FgMagenta, a...)
}
// CyanString is a convenient helper function to return a string with cyan
// foreground.
func CyanString(format string, a ...interface{}) string { return colorString(format, FgCyan, a...) }
// WhiteString is a convenient helper function to return a string with white
// foreground.
func WhiteString(format string, a ...interface{}) string { return colorString(format, FgWhite, a...) }
// HiBlack is a convenient helper function to print with hi-intensity black foreground. A
// newline is appended to format by default.
func HiBlack(format string, a ...interface{}) { colorPrint(format, FgHiBlack, a...) }
// HiRed is a convenient helper function to print with hi-intensity red foreground. A
// newline is appended to format by default.
func HiRed(format string, a ...interface{}) { colorPrint(format, FgHiRed, a...) }
// HiGreen is a convenient helper function to print with hi-intensity green foreground. A
// newline is appended to format by default.
func HiGreen(format string, a ...interface{}) { colorPrint(format, FgHiGreen, a...) }
// HiYellow is a convenient helper function to print with hi-intensity yellow foreground.
// A newline is appended to format by default.
func HiYellow(format string, a ...interface{}) { colorPrint(format, FgHiYellow, a...) }
// HiBlue is a convenient helper function to print with hi-intensity blue foreground. A
// newline is appended to format by default.
func HiBlue(format string, a ...interface{}) { colorPrint(format, FgHiBlue, a...) }
// HiMagenta is a convenient helper function to print with hi-intensity magenta foreground.
// A newline is appended to format by default.
func HiMagenta(format string, a ...interface{}) { colorPrint(format, FgHiMagenta, a...) }
// HiCyan is a convenient helper function to print with hi-intensity cyan foreground. A
// newline is appended to format by default.
func HiCyan(format string, a ...interface{}) { colorPrint(format, FgHiCyan, a...) }
// HiWhite is a convenient helper function to print with hi-intensity white foreground. A
// newline is appended to format by default.
func HiWhite(format string, a ...interface{}) { colorPrint(format, FgHiWhite, a...) }
// HiBlackString is a convenient helper function to return a string with hi-intensity black
// foreground.
func HiBlackString(format string, a ...interface{}) string {
return colorString(format, FgHiBlack, a...)
}
// HiRedString is a convenient helper function to return a string with hi-intensity red
// foreground.
func HiRedString(format string, a ...interface{}) string { return colorString(format, FgHiRed, a...) }
// HiGreenString is a convenient helper function to return a string with hi-intensity green
// foreground.
func HiGreenString(format string, a ...interface{}) string {
return colorString(format, FgHiGreen, a...)
}
// HiYellowString is a convenient helper function to return a string with hi-intensity yellow
// foreground.
func HiYellowString(format string, a ...interface{}) string {
return colorString(format, FgHiYellow, a...)
}
// HiBlueString is a convenient helper function to return a string with hi-intensity blue
// foreground.
func HiBlueString(format string, a ...interface{}) string { return colorString(format, FgHiBlue, a...) }
// HiMagentaString is a convenient helper function to return a string with hi-intensity magenta
// foreground.
func HiMagentaString(format string, a ...interface{}) string {
return colorString(format, FgHiMagenta, a...)
}
// HiCyanString is a convenient helper function to return a string with hi-intensity cyan
// foreground.
func HiCyanString(format string, a ...interface{}) string { return colorString(format, FgHiCyan, a...) }
// HiWhiteString is a convenient helper function to return a string with hi-intensity white
// foreground.
func HiWhiteString(format string, a ...interface{}) string {
return colorString(format, FgHiWhite, a...)
}

135
vendor/github.com/fatih/color/doc.go generated vendored
View File

@ -1,135 +0,0 @@
/*
Package color is an ANSI color package to output colorized or SGR defined
output to the standard output. The API can be used in several way, pick one
that suits you.
Use simple and default helper functions with predefined foreground colors:
color.Cyan("Prints text in cyan.")
// a newline will be appended automatically
color.Blue("Prints %s in blue.", "text")
// More default foreground colors..
color.Red("We have red")
color.Yellow("Yellow color too!")
color.Magenta("And many others ..")
// Hi-intensity colors
color.HiGreen("Bright green color.")
color.HiBlack("Bright black means gray..")
color.HiWhite("Shiny white color!")
However there are times where custom color mixes are required. Below are some
examples to create custom color objects and use the print functions of each
separate color object.
// Create a new color object
c := color.New(color.FgCyan).Add(color.Underline)
c.Println("Prints cyan text with an underline.")
// Or just add them to New()
d := color.New(color.FgCyan, color.Bold)
d.Printf("This prints bold cyan %s\n", "too!.")
// Mix up foreground and background colors, create new mixes!
red := color.New(color.FgRed)
boldRed := red.Add(color.Bold)
boldRed.Println("This will print text in bold red.")
whiteBackground := red.Add(color.BgWhite)
whiteBackground.Println("Red text with White background.")
// Use your own io.Writer output
color.New(color.FgBlue).Fprintln(myWriter, "blue color!")
blue := color.New(color.FgBlue)
blue.Fprint(myWriter, "This will print text in blue.")
You can create PrintXxx functions to simplify even more:
// Create a custom print function for convenient
red := color.New(color.FgRed).PrintfFunc()
red("warning")
red("error: %s", err)
// Mix up multiple attributes
notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
notice("don't forget this...")
You can also FprintXxx functions to pass your own io.Writer:
blue := color.New(FgBlue).FprintfFunc()
blue(myWriter, "important notice: %s", stars)
// Mix up with multiple attributes
success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
success(myWriter, don't forget this...")
Or create SprintXxx functions to mix strings with other non-colorized strings:
yellow := New(FgYellow).SprintFunc()
red := New(FgRed).SprintFunc()
fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error"))
info := New(FgWhite, BgGreen).SprintFunc()
fmt.Printf("this %s rocks!\n", info("package"))
Windows support is enabled by default. All Print functions work as intended.
However only for color.SprintXXX functions, user should use fmt.FprintXXX and
set the output to color.Output:
fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
info := New(FgWhite, BgGreen).SprintFunc()
fmt.Fprintf(color.Output, "this %s rocks!\n", info("package"))
Using with existing code is possible. Just use the Set() method to set the
standard output to the given parameters. That way a rewrite of an existing
code is not required.
// Use handy standard colors.
color.Set(color.FgYellow)
fmt.Println("Existing text will be now in Yellow")
fmt.Printf("This one %s\n", "too")
color.Unset() // don't forget to unset
// You can mix up parameters
color.Set(color.FgMagenta, color.Bold)
defer color.Unset() // use it in your function
fmt.Println("All text will be now bold magenta.")
There might be a case where you want to disable color output (for example to
pipe the standard output of your app to somewhere else). `Color` has support to
disable colors both globally and for single color definition. For example
suppose you have a CLI app and a `--no-color` bool flag. You can easily disable
the color output with:
var flagNoColor = flag.Bool("no-color", false, "Disable color output")
if *flagNoColor {
color.NoColor = true // disables colorized output
}
You can also disable the color by setting the NO_COLOR environment variable to any value.
It also has support for single color definitions (local). You can
disable/enable color output on the fly:
c := color.New(color.FgCyan)
c.Println("Prints cyan text")
c.DisableColor()
c.Println("This is printed without any color")
c.EnableColor()
c.Println("This prints again cyan...")
*/
package color

Some files were not shown because too many files have changed in this diff Show More