golangci-lint: Upgrade, fix issues (#397)

The golangci-lint being used was quite dated.
This change upgrades to the latest version.
Adds and updates exclusions based on new failures.

Note on revive:
I've included an opt-out for unused parameters for revive
because turning `newThing(required bool)` to `newThing(_ bool)`
is a loss of useful information.

The changes to the Go files are to fix the following issues:

```
camelcase.go:16: File is not `gofmt`-ed with `-s` (gofmt)
config_test.go:50:18: directive `//nolint: gosec` is unused for linter "gosec" (nolintlint)
defaults_test.go:28:25: G601: Implicit memory aliasing in for loop. (gosec)
doc.go:5: File is not `gofmt`-ed with `-s` (gofmt)
kong.go:446:18: directive `//nolint: gosec` is unused for linter "gosec" (nolintlint)
kong_test.go:503:20: G601: Implicit memory aliasing in for loop. (gosec)
model.go:493:10: composites: reflect.ValueError struct literal uses unkeyed fields (govet)
scanner.go:112: File is not `gofmt`-ed with `-s` (gofmt)
```

And to address broken nolint directives reported as follows by
golangci-lint.

```
[.. skipped .. ]
tag.go:65:1: directive `// nolint:gocyclo` should be written without leading space as `//nolint:gocyclo` (nolintlint)
tag.go:206:51: directive `// nolint: gocyclo` should be written without leading space as `//nolint: gocyclo` (nolintlint)
util_test.go:23:43: directive `// nolint: errcheck` should be written without leading space as `//nolint: errcheck` (nolintlint)
util_test.go:51:22: directive `// nolint: errcheck` should be written without leading space as `//nolint: errcheck` (nolintlint)
```
This commit is contained in:
Abhinav Gupta
2023-12-10 14:37:07 -08:00
committed by GitHub
parent 4ca2606342
commit a86bda490b
25 changed files with 129 additions and 101 deletions
+22
View File
@@ -41,10 +41,21 @@ linters:
- exhaustruct - exhaustruct
- nonamedreturns - nonamedreturns
- nilnil - nilnil
- nosnakecase # deprecated since v1.48.1
- structcheck # deprecated since v1.49.0
- deadcode # deprecated since v1.49.0
- varcheck # deprecated since v1.49.0
- depguard # nothing to guard against yet
- tagalign # hurts readability of kong tags
linters-settings: linters-settings:
govet: govet:
check-shadowing: true check-shadowing: true
# These govet checks are disabled by default, but they're useful.
enable:
- niliness
- sortslice
- unusedwrite
dupl: dupl:
threshold: 100 threshold: 100
gocyclo: gocyclo:
@@ -66,3 +77,14 @@ issues:
- 'bad syntax for struct tag pair' - 'bad syntax for struct tag pair'
- 'result .* \(error\) is always nil' - 'result .* \(error\) is always nil'
- 'package io/ioutil is deprecated' - 'package io/ioutil is deprecated'
exclude-rules:
# Don't warn on unused parameters.
# Parameter names are useful for documentation.
# Replacing them with '_' hides useful information.
- linters: [revive]
text: 'unused-parameter: parameter \S+ seems to be unused, consider removing or renaming it as _'
# Duplicate words are okay in tests.
- linters: [dupword]
path: _test\.go
+1 -1
View File
@@ -1 +1 @@
.golangci-lint-1.46.2.pkg .golangci-lint-1.55.2.pkg
+2 -2
View File
@@ -41,7 +41,7 @@ func (b bindings) addProvider(provider interface{}) error {
errv := out[1] errv := out[1]
var err error var err error
if !errv.IsNil() { if !errv.IsNil() {
err = errv.Interface().(error) // nolint err = errv.Interface().(error) //nolint
} }
return out[0], err return out[0], err
} }
@@ -99,7 +99,7 @@ func callFunction(f reflect.Value, bindings bindings) error {
if out[0].IsNil() { if out[0].IsNil() {
return nil return nil
} }
return out[0].Interface().(error) // nolint return out[0].Interface().(error) //nolint
} }
func callAnyFunction(f reflect.Value, bindings bindings) (out []any, err error) { func callAnyFunction(f reflect.Value, bindings bindings) (out []any, err error) {
+24 -24
View File
@@ -13,37 +13,37 @@ import (
// //
// Examples // Examples
// //
// "" => [""] // "" => [""]
// "lowercase" => ["lowercase"] // "lowercase" => ["lowercase"]
// "Class" => ["Class"] // "Class" => ["Class"]
// "MyClass" => ["My", "Class"] // "MyClass" => ["My", "Class"]
// "MyC" => ["My", "C"] // "MyC" => ["My", "C"]
// "HTML" => ["HTML"] // "HTML" => ["HTML"]
// "PDFLoader" => ["PDF", "Loader"] // "PDFLoader" => ["PDF", "Loader"]
// "AString" => ["A", "String"] // "AString" => ["A", "String"]
// "SimpleXMLParser" => ["Simple", "XML", "Parser"] // "SimpleXMLParser" => ["Simple", "XML", "Parser"]
// "vimRPCPlugin" => ["vim", "RPC", "Plugin"] // "vimRPCPlugin" => ["vim", "RPC", "Plugin"]
// "GL11Version" => ["GL", "11", "Version"] // "GL11Version" => ["GL", "11", "Version"]
// "99Bottles" => ["99", "Bottles"] // "99Bottles" => ["99", "Bottles"]
// "May5" => ["May", "5"] // "May5" => ["May", "5"]
// "BFG9000" => ["BFG", "9000"] // "BFG9000" => ["BFG", "9000"]
// "BöseÜberraschung" => ["Böse", "Überraschung"] // "BöseÜberraschung" => ["Böse", "Überraschung"]
// "Two spaces" => ["Two", " ", "spaces"] // "Two spaces" => ["Two", " ", "spaces"]
// "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"] // "BadUTF8\xe2\xe2\xa1" => ["BadUTF8\xe2\xe2\xa1"]
// //
// Splitting rules // Splitting rules
// //
// 1) If string is not valid UTF-8, return it without splitting as // 1. If string is not valid UTF-8, return it without splitting as
// single item array. // single item array.
// 2) Assign all unicode characters into one of 4 sets: lower case // 2. Assign all unicode characters into one of 4 sets: lower case
// letters, upper case letters, numbers, and all other characters. // letters, upper case letters, numbers, and all other characters.
// 3) Iterate through characters of string, introducing splits // 3. Iterate through characters of string, introducing splits
// between adjacent characters that belong to different sets. // between adjacent characters that belong to different sets.
// 4) Iterate through array of split strings, and if a given string // 4. Iterate through array of split strings, and if a given string
// is upper case: // is upper case:
// if subsequent string is lower case: // if subsequent string is lower case:
// move last character of upper case string to beginning of // move last character of upper case string to beginning of
// lower case string // lower case string
func camelCase(src string) (entries []string) { func camelCase(src string) (entries []string) {
// don't split invalid utf8 // don't split invalid utf8
if !utf8.ValidString(src) { if !utf8.ValidString(src) {
+1 -1
View File
@@ -47,7 +47,7 @@ func makeConfig(t *testing.T, config interface{}) (path string, cleanup func())
t.Helper() t.Helper()
w, err := ioutil.TempFile("", "") w, err := ioutil.TempFile("", "")
assert.NoError(t, err) assert.NoError(t, err)
defer w.Close() // nolint: gosec defer w.Close()
err = json.NewEncoder(w).Encode(config) err = json.NewEncoder(w).Encode(config)
assert.NoError(t, err) assert.NoError(t, err)
return w.Name(), func() { os.Remove(w.Name()) } return w.Name(), func() { os.Remove(w.Name()) }
+3 -3
View File
@@ -161,7 +161,7 @@ func (c *Context) Empty() bool {
} }
// Validate the current context. // Validate the current context.
func (c *Context) Validate() error { // nolint: gocyclo func (c *Context) Validate() error { //nolint: gocyclo
err := Visit(c.Model, func(node Visitable, next Next) error { err := Visit(c.Model, func(node Visitable, next Next) error {
switch node := node.(type) { switch node := node.(type) {
case *Value: case *Value:
@@ -347,7 +347,7 @@ func (c *Context) endParsing() {
} }
} }
func (c *Context) trace(node *Node) (err error) { // nolint: gocyclo func (c *Context) trace(node *Node) (err error) { //nolint: gocyclo
positional := 0 positional := 0
node.Active = true node.Active = true
@@ -377,7 +377,7 @@ func (c *Context) trace(node *Node) (err error) { // nolint: gocyclo
switch { switch {
case v == "-": case v == "-":
fallthrough fallthrough
default: // nolint default: //nolint
c.scan.Pop() c.scan.Pop()
c.scan.PushTyped(token.Value, PositionalArgumentToken) c.scan.PushTyped(token.Value, PositionalArgumentToken)
+1
View File
@@ -24,6 +24,7 @@ func TestApplyDefaults(t *testing.T) {
expected: CLI{Str: "str", Duration: time.Second}}, expected: CLI{Str: "str", Duration: time.Second}},
} }
for _, tt := range tests { for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
err := ApplyDefaults(&tt.target) err := ApplyDefaults(&tt.target)
assert.NoError(t, err) assert.NoError(t, err)
+17 -17
View File
@@ -2,31 +2,31 @@
// //
// Here's an example: // Here's an example:
// //
// shell rm [-f] [-r] <paths> ... // shell rm [-f] [-r] <paths> ...
// shell ls [<paths> ...] // shell ls [<paths> ...]
// //
// This can be represented by the following command-line structure: // This can be represented by the following command-line structure:
// //
// package main // package main
// //
// import "github.com/alecthomas/kong" // import "github.com/alecthomas/kong"
// //
// var CLI struct { // var CLI struct {
// Rm struct { // Rm struct {
// Force bool `short:"f" help:"Force removal."` // Force bool `short:"f" help:"Force removal."`
// Recursive bool `short:"r" help:"Recursively remove files."` // Recursive bool `short:"r" help:"Recursively remove files."`
// //
// Paths []string `arg help:"Paths to remove." type:"path"` // Paths []string `arg help:"Paths to remove." type:"path"`
// } `cmd help:"Remove files."` // } `cmd help:"Remove files."`
// //
// Ls struct { // Ls struct {
// Paths []string `arg optional help:"Paths to list." type:"path"` // Paths []string `arg optional help:"Paths to list." type:"path"`
// } `cmd help:"List paths."` // } `cmd help:"List paths."`
// } // }
// //
// func main() { // func main() {
// kong.Parse(&CLI) // kong.Parse(&CLI)
// } // }
// //
// See https://github.com/alecthomas/kong for details. // See https://github.com/alecthomas/kong for details.
package kong package kong
+1 -1
View File
@@ -21,7 +21,7 @@ func TestParseHandlingBadBuild(t *testing.T) {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
assert.Equal(t, "fail=' is not quoted properly", r.(error).Error()) // nolint assert.Equal(t, "fail=' is not quoted properly", r.(error).Error()) //nolint
} }
}() }()
+1
View File
@@ -1,3 +1,4 @@
//go:build appengine || (!linux && !freebsd && !darwin && !dragonfly && !netbsd && !openbsd)
// +build appengine !linux,!freebsd,!darwin,!dragonfly,!netbsd,!openbsd // +build appengine !linux,!freebsd,!darwin,!dragonfly,!netbsd,!openbsd
package kong package kong
+2 -2
View File
@@ -27,9 +27,9 @@ func guessWidth(w io.Writer) int {
if _, _, err := syscall.Syscall6( if _, _, err := syscall.Syscall6(
syscall.SYS_IOCTL, syscall.SYS_IOCTL,
uintptr(fd), // nolint: unconvert uintptr(fd), //nolint: unconvert
uintptr(syscall.TIOCGWINSZ), uintptr(syscall.TIOCGWINSZ),
uintptr(unsafe.Pointer(&dimensions)), // nolint: gas uintptr(unsafe.Pointer(&dimensions)), //nolint: gas
0, 0, 0, 0, 0, 0,
); err == 0 { ); err == 0 {
if dimensions[1] == 0 { if dimensions[1] == 0 {
+1 -1
View File
@@ -600,7 +600,7 @@ func TestAutoGroup(t *testing.T) {
if node, ok := parent.(*kong.Node); ok { if node, ok := parent.(*kong.Node); ok {
return &kong.Group{ return &kong.Group{
Key: node.Name, Key: node.Name,
Title: strings.Title(node.Name) + " flags:", // nolint Title: strings.Title(node.Name) + " flags:", //nolint
} }
} }
return nil return nil
+3 -3
View File
@@ -412,7 +412,7 @@ func (k *Kong) FatalIfErrorf(err error, args ...interface{}) {
} }
msg := err.Error() msg := err.Error()
if len(args) > 0 { if len(args) > 0 {
msg = fmt.Sprintf(args[0].(string), args[1:]...) + ": " + err.Error() // nolint msg = fmt.Sprintf(args[0].(string), args[1:]...) + ": " + err.Error() //nolint
} }
// Maybe display usage information. // Maybe display usage information.
var parseErr *ParseError var parseErr *ParseError
@@ -439,11 +439,11 @@ func (k *Kong) LoadConfig(path string) (Resolver, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
r, err := os.Open(path) // nolint: gas r, err := os.Open(path) //nolint: gas
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer r.Close() // nolint: gosec defer r.Close()
return k.loader(r) return k.loader(r)
} }
+7 -6
View File
@@ -495,6 +495,7 @@ func TestHooks(t *testing.T) {
p := mustNew(t, &cli, kong.Bind(ctx)) p := mustNew(t, &cli, kong.Bind(ctx))
for _, test := range tests { for _, test := range tests {
test := test
*ctx = hookContext{} *ctx = hookContext{}
cli.One = hookCmd{} cli.One = hookCmd{}
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
@@ -753,7 +754,7 @@ func TestEmbedInterface(t *testing.T) {
_, err := p.Parse([]string{"--some-flag=foo", "--flag=yes"}) _, err := p.Parse([]string{"--some-flag=foo", "--flag=yes"})
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "foo", cli.SomeFlag) assert.Equal(t, "foo", cli.SomeFlag)
assert.Equal(t, "yes", cli.TestInterface.(*TestImpl).Flag) // nolint assert.Equal(t, "yes", cli.TestInterface.(*TestImpl).Flag) //nolint
} }
func TestExcludedField(t *testing.T) { func TestExcludedField(t *testing.T) {
@@ -1352,16 +1353,16 @@ func TestHydratePointerCommandsAndEmbeds(t *testing.T) {
assert.Equal(t, &embed{Embed: true}, cli.Embed) assert.Equal(t, &embed{Embed: true}, cli.Embed)
} }
// nolint //nolint:revive
type testIgnoreFields struct { type testIgnoreFields struct {
Foo struct { Foo struct {
Bar bool Bar bool
Sub struct { Sub struct {
SubFlag1 bool `kong:"name=subflag1"` SubFlag1 bool `kong:"name=subflag1"`
XXX_SubFlag2 bool `kong:"name=subflag2"` XXX_SubFlag2 bool `kong:"name=subflag2"` //nolint:stylecheck
} `kong:"cmd"` } `kong:"cmd"`
} `kong:"cmd"` } `kong:"cmd"`
XXX_Baz struct { XXX_Baz struct { //nolint:stylecheck
Boo bool Boo bool
} `kong:"cmd,name=baz"` } `kong:"cmd,name=baz"`
} }
@@ -1928,8 +1929,8 @@ func TestBoolPtrNil(t *testing.T) {
func TestUnsupportedPtr(t *testing.T) { func TestUnsupportedPtr(t *testing.T) {
type Foo struct { type Foo struct {
x int // nolint x int //nolint
y int // nolint y int //nolint
} }
var cli struct { var cli struct {
+17 -17
View File
@@ -59,9 +59,9 @@ type mapperValueAdapter struct {
func (m *mapperValueAdapter) Decode(ctx *DecodeContext, target reflect.Value) error { func (m *mapperValueAdapter) Decode(ctx *DecodeContext, target reflect.Value) error {
if target.Type().Implements(mapperValueType) { if target.Type().Implements(mapperValueType) {
return target.Interface().(MapperValue).Decode(ctx) // nolint return target.Interface().(MapperValue).Decode(ctx) //nolint
} }
return target.Addr().Interface().(MapperValue).Decode(ctx) // nolint return target.Addr().Interface().(MapperValue).Decode(ctx) //nolint
} }
func (m *mapperValueAdapter) IsBool() bool { func (m *mapperValueAdapter) IsBool() bool {
@@ -77,9 +77,9 @@ func (m *textUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Value
return err return err
} }
if target.Type().Implements(textUnmarshalerType) { if target.Type().Implements(textUnmarshalerType) {
return target.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)) // nolint return target.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)) //nolint
} }
return target.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)) // nolint return target.Addr().Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(value)) //nolint
} }
type binaryUnmarshalerAdapter struct{} type binaryUnmarshalerAdapter struct{}
@@ -91,9 +91,9 @@ func (m *binaryUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Val
return err return err
} }
if target.Type().Implements(binaryUnmarshalerType) { if target.Type().Implements(binaryUnmarshalerType) {
return target.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary([]byte(value)) // nolint return target.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary([]byte(value)) //nolint
} }
return target.Addr().Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary([]byte(value)) // nolint return target.Addr().Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary([]byte(value)) //nolint
} }
type jsonUnmarshalerAdapter struct{} type jsonUnmarshalerAdapter struct{}
@@ -105,9 +105,9 @@ func (j *jsonUnmarshalerAdapter) Decode(ctx *DecodeContext, target reflect.Value
return err return err
} }
if target.Type().Implements(jsonUnmarshalerType) { if target.Type().Implements(jsonUnmarshalerType) {
return target.Interface().(json.Unmarshaler).UnmarshalJSON([]byte(value)) // nolint return target.Interface().(json.Unmarshaler).UnmarshalJSON([]byte(value)) //nolint
} }
return target.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(value)) // nolint return target.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(value)) //nolint
} }
// A Mapper represents how a field is mapped from command-line values to Go. // A Mapper represents how a field is mapped from command-line values to Go.
@@ -142,7 +142,7 @@ type BoolMapperExt interface {
// A MapperFunc is a single function that complies with the Mapper interface. // A MapperFunc is a single function that complies with the Mapper interface.
type MapperFunc func(ctx *DecodeContext, target reflect.Value) error type MapperFunc func(ctx *DecodeContext, target reflect.Value) error
func (m MapperFunc) Decode(ctx *DecodeContext, target reflect.Value) error { // nolint: revive func (m MapperFunc) Decode(ctx *DecodeContext, target reflect.Value) error { //nolint: revive
return m(ctx, target) return m(ctx, target)
} }
@@ -339,7 +339,7 @@ func durationDecoder() MapperFunc {
return fmt.Errorf("expected duration but got %q: %v", v, err) return fmt.Errorf("expected duration but got %q: %v", v, err)
} }
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64: case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
d = reflect.ValueOf(v).Convert(reflect.TypeOf(time.Duration(0))).Interface().(time.Duration) // nolint: forcetypeassert d = reflect.ValueOf(v).Convert(reflect.TypeOf(time.Duration(0))).Interface().(time.Duration) //nolint: forcetypeassert
default: default:
return fmt.Errorf("expected duration but got %q", v) return fmt.Errorf("expected duration but got %q", v)
} }
@@ -367,7 +367,7 @@ func timeDecoder() MapperFunc {
} }
} }
func intDecoder(bits int) MapperFunc { // nolint: dupl func intDecoder(bits int) MapperFunc { //nolint: dupl
return func(ctx *DecodeContext, target reflect.Value) error { return func(ctx *DecodeContext, target reflect.Value) error {
t, err := ctx.Scan.PopValue("int") t, err := ctx.Scan.PopValue("int")
if err != nil { if err != nil {
@@ -396,7 +396,7 @@ func intDecoder(bits int) MapperFunc { // nolint: dupl
} }
} }
func uintDecoder(bits int) MapperFunc { // nolint: dupl func uintDecoder(bits int) MapperFunc { //nolint: dupl
return func(ctx *DecodeContext, target reflect.Value) error { return func(ctx *DecodeContext, target reflect.Value) error {
t, err := ctx.Scan.PopValue("uint") t, err := ctx.Scan.PopValue("uint")
if err != nil { if err != nil {
@@ -611,7 +611,7 @@ func fileMapper(r *Registry) MapperFunc {
file = os.Stdin file = os.Stdin
} else { } else {
path = ExpandPath(path) path = ExpandPath(path)
file, err = os.Open(path) // nolint: gosec file, err = os.Open(path) //nolint: gosec
if err != nil { if err != nil {
return err return err
} }
@@ -872,7 +872,7 @@ type NamedFileContentFlag struct {
Contents []byte Contents []byte
} }
func (f *NamedFileContentFlag) Decode(ctx *DecodeContext) error { // nolint: revive func (f *NamedFileContentFlag) Decode(ctx *DecodeContext) error { //nolint: revive
var filename string var filename string
err := ctx.Scan.PopValueInto("filename", &filename) err := ctx.Scan.PopValueInto("filename", &filename)
if err != nil { if err != nil {
@@ -884,7 +884,7 @@ func (f *NamedFileContentFlag) Decode(ctx *DecodeContext) error { // nolint: rev
return nil return nil
} }
filename = ExpandPath(filename) filename = ExpandPath(filename)
data, err := ioutil.ReadFile(filename) // nolint: gosec data, err := ioutil.ReadFile(filename) //nolint: gosec
if err != nil { if err != nil {
return fmt.Errorf("failed to open %q: %v", filename, err) return fmt.Errorf("failed to open %q: %v", filename, err)
} }
@@ -896,7 +896,7 @@ func (f *NamedFileContentFlag) Decode(ctx *DecodeContext) error { // nolint: rev
// FileContentFlag is a flag value that loads a file's contents into its value. // FileContentFlag is a flag value that loads a file's contents into its value.
type FileContentFlag []byte type FileContentFlag []byte
func (f *FileContentFlag) Decode(ctx *DecodeContext) error { // nolint: revive func (f *FileContentFlag) Decode(ctx *DecodeContext) error { //nolint: revive
var filename string var filename string
err := ctx.Scan.PopValueInto("filename", &filename) err := ctx.Scan.PopValueInto("filename", &filename)
if err != nil { if err != nil {
@@ -908,7 +908,7 @@ func (f *FileContentFlag) Decode(ctx *DecodeContext) error { // nolint: revive
return nil return nil
} }
filename = ExpandPath(filename) filename = ExpandPath(filename)
data, err := ioutil.ReadFile(filename) // nolint: gosec data, err := ioutil.ReadFile(filename) //nolint: gosec
if err != nil { if err != nil {
return fmt.Errorf("failed to open %q: %v", filename, err) return fmt.Errorf("failed to open %q: %v", filename, err)
} }
+8 -8
View File
@@ -356,14 +356,14 @@ func TestNumbers(t *testing.T) {
_, err := p.Parse([]string{ _, err := p.Parse([]string{
"--f-32", fmt.Sprintf("%v", math.MaxFloat32), "--f-32", fmt.Sprintf("%v", math.MaxFloat32),
"--f-64", fmt.Sprintf("%v", math.MaxFloat64), "--f-64", fmt.Sprintf("%v", math.MaxFloat64),
"--i-8", fmt.Sprintf("%v", int8(math.MaxInt8)), "--i-8", fmt.Sprintf("%v", int8(math.MaxInt8)), //nolint:perfsprint // want int8
"--i-16", fmt.Sprintf("%v", int16(math.MaxInt16)), "--i-16", fmt.Sprintf("%v", int16(math.MaxInt16)), //nolint:perfsprint // want int16
"--i-32", fmt.Sprintf("%v", int32(math.MaxInt32)), "--i-32", fmt.Sprintf("%v", int32(math.MaxInt32)), //nolint:perfsprint // want int32
"--i-64", fmt.Sprintf("%v", int64(math.MaxInt64)), "--i-64", fmt.Sprintf("%v", int64(math.MaxInt64)), //nolint:perfsprint // want int64
"--u-8", fmt.Sprintf("%v", uint8(math.MaxUint8)), "--u-8", fmt.Sprintf("%v", uint8(math.MaxUint8)), //nolint:perfsprint // want uint8
"--u-16", fmt.Sprintf("%v", uint16(math.MaxUint16)), "--u-16", fmt.Sprintf("%v", uint16(math.MaxUint16)), //nolint:perfsprint // want uint16
"--u-32", fmt.Sprintf("%v", uint32(math.MaxUint32)), "--u-32", fmt.Sprintf("%v", uint32(math.MaxUint32)), //nolint:perfsprint // want uint32
"--u-64", fmt.Sprintf("%v", uint64(math.MaxUint64)), "--u-64", fmt.Sprintf("%v", uint64(math.MaxUint64)), //nolint:perfsprint // want uint64
}) })
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, CLI{ assert.Equal(t, CLI{
+4 -1
View File
@@ -490,6 +490,9 @@ func reflectValueIsZero(v reflect.Value) bool {
default: default:
// This should never happens, but will act as a safeguard for // This should never happens, but will act as a safeguard for
// later, as a default value doesn't makes sense here. // later, as a default value doesn't makes sense here.
panic(&reflect.ValueError{"reflect.Value.IsZero", v.Kind()}) panic(&reflect.ValueError{
Method: "reflect.Value.IsZero",
Kind: v.Kind(),
})
} }
} }
+2 -2
View File
@@ -20,7 +20,7 @@ type Option interface {
// OptionFunc is function that adheres to the Option interface. // OptionFunc is function that adheres to the Option interface.
type OptionFunc func(k *Kong) error type OptionFunc func(k *Kong) error
func (o OptionFunc) Apply(k *Kong) error { return o(k) } // nolint: revive func (o OptionFunc) Apply(k *Kong) error { return o(k) } //nolint: revive
// Vars sets the variables to use for interpolation into help strings and default values. // Vars sets the variables to use for interpolation into help strings and default values.
// //
@@ -287,7 +287,7 @@ func AutoGroup(format func(parent Visitable, flag *Flag) *Group) Option {
// See also ExplicitGroups for a more structured alternative. // See also ExplicitGroups for a more structured alternative.
type Groups map[string]string type Groups map[string]string
func (g Groups) Apply(k *Kong) error { // nolint: revive func (g Groups) Apply(k *Kong) error { //nolint: revive
for key, info := range g { for key, info := range g {
lines := strings.Split(info, "\n") lines := strings.Split(info, "\n")
title := strings.TrimSpace(lines[0]) title := strings.TrimSpace(lines[0])
+3 -3
View File
@@ -30,7 +30,7 @@ func TestBindTo(t *testing.T) {
saw := "" saw := ""
method := func(i iface) error { method := func(i iface) error {
saw = string(i.(impl)) // nolint saw = string(i.(impl)) //nolint
return nil return nil
} }
@@ -50,7 +50,7 @@ func TestInvalidCallback(t *testing.T) {
saw := "" saw := ""
method := func(i iface) string { method := func(i iface) string {
saw = string(i.(impl)) // nolint saw = string(i.(impl)) //nolint
return saw return saw
} }
@@ -75,7 +75,7 @@ func TestCallbackCustomError(t *testing.T) {
saw := "" saw := ""
method := func(i iface) *zrror { method := func(i iface) *zrror {
saw = string(i.(impl)) // nolint saw = string(i.(impl)) //nolint
return nil return nil
} }
+2 -2
View File
@@ -22,10 +22,10 @@ type ResolverFunc func(context *Context, parent *Path, flag *Flag) (interface{},
var _ Resolver = ResolverFunc(nil) var _ Resolver = ResolverFunc(nil)
func (r ResolverFunc) Resolve(context *Context, parent *Path, flag *Flag) (interface{}, error) { // nolint: revive func (r ResolverFunc) Resolve(context *Context, parent *Path, flag *Flag) (interface{}, error) { //nolint: revive
return r(context, parent, flag) return r(context, parent, flag)
} }
func (r ResolverFunc) Validate(app *Application) error { return nil } // nolint: revive func (r ResolverFunc) Validate(app *Application) error { return nil } //nolint: revive
// JSON returns a Resolver that retrieves values from a JSON source. // JSON returns a Resolver that retrieves values from a JSON source.
// //
+2 -2
View File
@@ -82,7 +82,7 @@ func (t Token) InferredType() TokenType {
return t.Type return t.Type
} }
if v, ok := t.Value.(string); ok { if v, ok := t.Value.(string); ok {
if strings.HasPrefix(v, "--") { // nolint: gocritic if strings.HasPrefix(v, "--") { //nolint: gocritic
return FlagToken return FlagToken
} else if v == "-" { } else if v == "-" {
return PositionalArgumentToken return PositionalArgumentToken
@@ -109,7 +109,7 @@ func (t Token) IsValue() bool {
// //
// For example, the token "--foo=bar" will be split into the following by the parser: // For example, the token "--foo=bar" will be split into the following by the parser:
// //
// [{FlagToken, "foo"}, {FlagValueToken, "bar"}] // [{FlagToken, "foo"}, {FlagValueToken, "bar"}]
type Scanner struct { type Scanner struct {
args []Token args []Token
} }
+2 -2
View File
@@ -62,7 +62,7 @@ type tagChars struct {
var kongChars = tagChars{sep: ',', quote: '\'', assign: '=', needsUnquote: false} var kongChars = tagChars{sep: ',', quote: '\'', assign: '=', needsUnquote: false}
var bareChars = tagChars{sep: ' ', quote: '"', assign: ':', needsUnquote: true} var bareChars = tagChars{sep: ' ', quote: '"', assign: ':', needsUnquote: true}
// nolint:gocyclo //nolint:gocyclo
func parseTagItems(tagString string, chr tagChars) (map[string][]string, error) { func parseTagItems(tagString string, chr tagChars) (map[string][]string, error) {
d := map[string][]string{} d := map[string][]string{}
key := []rune{} key := []rune{}
@@ -203,7 +203,7 @@ func parseTag(parent reflect.Value, ft reflect.StructField) (*Tag, error) {
return t, nil return t, nil
} }
func hydrateTag(t *Tag, typ reflect.Type) error { // nolint: gocyclo func hydrateTag(t *Tag, typ reflect.Type) error { //nolint: gocyclo
var typeName string var typeName string
var isBool bool var isBool bool
var isBoolPtr bool var isBoolPtr bool
+1 -1
View File
@@ -17,7 +17,7 @@ func (c ConfigFlag) BeforeResolve(kong *Kong, ctx *Context, trace *Path) error {
if kong.loader == nil { if kong.loader == nil {
return fmt.Errorf("kong must be configured with kong.Configuration(...)") return fmt.Errorf("kong must be configured with kong.Configuration(...)")
} }
path := string(ctx.FlagValue(trace.Flag).(ConfigFlag)) // nolint path := string(ctx.FlagValue(trace.Flag).(ConfigFlag)) //nolint
resolver, err := kong.LoadConfig(path) resolver, err := kong.LoadConfig(path)
if err != nil { if err != nil {
return err return err
+2 -2
View File
@@ -20,7 +20,7 @@ func TestConfigFlag(t *testing.T) {
w, err := ioutil.TempFile("", "") w, err := ioutil.TempFile("", "")
assert.NoError(t, err) assert.NoError(t, err)
defer os.Remove(w.Name()) defer os.Remove(w.Name())
w.WriteString(`{"flag": "hello world"}`) // nolint: errcheck w.WriteString(`{"flag": "hello world"}`) //nolint: errcheck
w.Close() w.Close()
p := Must(&cli, Configuration(JSON)) p := Must(&cli, Configuration(JSON))
@@ -48,7 +48,7 @@ func TestVersionFlag(t *testing.T) {
func TestChangeDirFlag(t *testing.T) { func TestChangeDirFlag(t *testing.T) {
cwd, err := os.Getwd() cwd, err := os.Getwd()
assert.NoError(t, err) assert.NoError(t, err)
defer os.Chdir(cwd) // nolint: errcheck defer os.Chdir(cwd) //nolint: errcheck
dir := t.TempDir() dir := t.TempDir()
file := filepath.Join(dir, "out.txt") file := filepath.Join(dir, "out.txt")