Skip to content

Commit 90c723d

Browse files
authored
Staticcheck fixes (ipfs#196)
* Staticcheck fixes This fixes all staticcheck warnings for this library.
1 parent c3c51f7 commit 90c723d

22 files changed

+100
-112
lines changed

.travis.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ os:
44
language: go
55

66
go:
7-
- 1.11.x
7+
- 1.14.2
88

99
env:
1010
global:

chan_test.go

+6-5
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@ func TestChanResponsePair(t *testing.T) {
2929
wg.Add(1)
3030
go func() {
3131
for _, v := range tc.values {
32-
v_, err := res.Next()
32+
v2, err := res.Next()
3333
if err != nil {
3434
t.Error("Next returned unexpected error:", err)
3535
}
36-
if v != v_ {
37-
t.Errorf("Next returned unexpected value %q, expected %q", v_, v)
36+
if v != v2 {
37+
t.Errorf("Next returned unexpected value %q, expected %q", v2, v)
3838
}
3939
}
4040

@@ -93,7 +93,7 @@ func TestSingle1(t *testing.T) {
9393

9494
err := re.Close()
9595
if err != ErrClosingClosedEmitter {
96-
t.Fatalf("expected double close error, got %v", err)
96+
t.Errorf("expected double close error, got %v", err)
9797
}
9898
close(wait)
9999
}()
@@ -127,7 +127,8 @@ func TestSingle2(t *testing.T) {
127127
go func() {
128128
err := re.Emit(Single{42})
129129
if err != ErrClosedEmitter {
130-
t.Fatal("expected closed emitter error, got", err)
130+
t.Error("expected closed emitter error, got", err)
131+
return
131132
}
132133
}()
133134

cli/cmd_suggestion.go

+10-4
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ func suggestUnknownCmd(args []string, root *cmds.Command) []string {
3838
var suggestions []string
3939
sortableSuggestions := make(suggestionSlice, 0)
4040
var sFinal []string
41-
const MIN_LEVENSHTEIN = 3
41+
const MinLevenshtein = 3
4242

4343
var options levenshtein.Options = levenshtein.Options{
4444
InsCost: 1,
@@ -50,7 +50,7 @@ func suggestUnknownCmd(args []string, root *cmds.Command) []string {
5050
}
5151

5252
// Start with a simple strings.Contains check
53-
for name, _ := range root.Subcommands {
53+
for name := range root.Subcommands {
5454
if strings.Contains(arg, name) {
5555
suggestions = append(suggestions, name)
5656
}
@@ -61,9 +61,9 @@ func suggestUnknownCmd(args []string, root *cmds.Command) []string {
6161
return suggestions
6262
}
6363

64-
for name, _ := range root.Subcommands {
64+
for name := range root.Subcommands {
6565
lev := levenshtein.DistanceForStrings([]rune(arg), []rune(name), options)
66-
if lev <= MIN_LEVENSHTEIN {
66+
if lev <= MinLevenshtein {
6767
sortableSuggestions = append(sortableSuggestions, &suggestion{name, lev})
6868
}
6969
}
@@ -78,11 +78,17 @@ func suggestUnknownCmd(args []string, root *cmds.Command) []string {
7878
func printSuggestions(inputs []string, root *cmds.Command) (err error) {
7979

8080
suggestions := suggestUnknownCmd(inputs, root)
81+
8182
if len(suggestions) > 1 {
83+
//lint:ignore ST1005 user facing error
8284
err = fmt.Errorf("Unknown Command \"%s\"\n\nDid you mean any of these?\n\n\t%s", inputs[0], strings.Join(suggestions, "\n\t"))
85+
8386
} else if len(suggestions) > 0 {
87+
//lint:ignore ST1005 user facing error
8488
err = fmt.Errorf("Unknown Command \"%s\"\n\nDid you mean this?\n\n\t%s", inputs[0], suggestions[0])
89+
8590
} else {
91+
//lint:ignore ST1005 user facing error
8692
err = fmt.Errorf("Unknown Command \"%s\"\n", inputs[0])
8793
}
8894
return

cli/helptext.go

+5-12
Original file line numberDiff line numberDiff line change
@@ -137,8 +137,11 @@ func init() {
137137
shortHelpTemplate = template.Must(template.New("shortHelp").Parse(shortHelpFormat))
138138
}
139139

140+
// ErrNoHelpRequested returns when request for help help does not include the
141+
// short nor the long option.
140142
var ErrNoHelpRequested = errors.New("no help requested")
141143

144+
// HandleHelp writes help to a writer for the given request's command.
142145
func HandleHelp(appName string, req *cmds.Request, out io.Writer) error {
143146
long, _ := req.Options[cmds.OptLongHelp].(bool)
144147
short, _ := req.Options[cmds.OptShortHelp].(bool)
@@ -369,18 +372,15 @@ func appendWrapped(prefix, text string, width int) string {
369372
func optionFlag(flag string) string {
370373
if len(flag) == 1 {
371374
return fmt.Sprintf(shortFlag, flag)
372-
} else {
373-
return fmt.Sprintf(longFlag, flag)
374375
}
376+
return fmt.Sprintf(longFlag, flag)
375377
}
376378

377379
func optionText(width int, cmd ...*cmds.Command) []string {
378380
// get a slice of the options we want to list out
379381
options := make([]cmds.Option, 0)
380382
for _, c := range cmd {
381-
for _, opt := range c.Options {
382-
options = append(options, opt)
383-
}
383+
options = append(options, c.Options...)
384384
}
385385

386386
// add option names to output
@@ -503,13 +503,6 @@ func align(lines []string) []string {
503503
return lines
504504
}
505505

506-
func indent(lines []string, prefix string) []string {
507-
for i, line := range lines {
508-
lines[i] = prefix + indentString(line, prefix)
509-
}
510-
return lines
511-
}
512-
513506
func indentString(line string, prefix string) string {
514507
return prefix + strings.Replace(line, "\n", "\n"+prefix, -1)
515508
}

cli/parse_test.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package cli
33
import (
44
"context"
55
"fmt"
6-
"github.com/ipfs/go-ipfs-files"
76
"io"
87
"io/ioutil"
98
"net/url"
@@ -12,6 +11,8 @@ import (
1211
"strings"
1312
"testing"
1413

14+
files "github.com/ipfs/go-ipfs-files"
15+
1516
cmds "github.com/ipfs/go-ipfs-cmds"
1617
)
1718

@@ -211,7 +212,7 @@ func TestArgumentParsing(t *testing.T) {
211212

212213
test := func(cmd words, f *os.File, res words) {
213214
if f != nil {
214-
if _, err := f.Seek(0, os.SEEK_SET); err != nil {
215+
if _, err := f.Seek(0, io.SeekStart); err != nil {
215216
t.Fatal(err)
216217
}
217218
}
@@ -486,7 +487,7 @@ func TestBodyArgs(t *testing.T) {
486487

487488
for _, tc := range tcs {
488489
if tc.f != nil {
489-
if _, err := tc.f.Seek(0, os.SEEK_SET); err != nil {
490+
if _, err := tc.f.Seek(0, io.SeekStart); err != nil {
490491
t.Fatal(err)
491492
}
492493
}

cli/responseemitter_test.go

+1-7
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,9 @@ import (
55
"fmt"
66
"testing"
77

8-
"github.com/ipfs/go-ipfs-cmds"
8+
cmds "github.com/ipfs/go-ipfs-cmds"
99
)
1010

11-
type writeCloser struct {
12-
*bytes.Buffer
13-
}
14-
15-
func (wc writeCloser) Close() error { return nil }
16-
1711
type tcCloseWithError struct {
1812
stdout, stderr *bytes.Buffer
1913
exStdout, exStderr string

cli/single_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import (
55
"context"
66
"testing"
77

8-
"github.com/ipfs/go-ipfs-cmds"
8+
cmds "github.com/ipfs/go-ipfs-cmds"
99
)
1010

1111
func TestSingle(t *testing.T) {
@@ -25,7 +25,8 @@ func TestSingle(t *testing.T) {
2525

2626
go func() {
2727
if err := cmds.EmitOnce(re, "test"); err != nil {
28-
t.Fatal(err)
28+
t.Error(err)
29+
return
2930
}
3031

3132
err := re.Emit("this should not be emitted")

command.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@ import (
1313
"fmt"
1414
"strings"
1515

16-
"github.com/ipfs/go-ipfs-files"
16+
files "github.com/ipfs/go-ipfs-files"
1717

1818
logging "github.com/ipfs/go-log"
1919
)
2020

21+
// DefaultOutputEncoding defines the default API output encoding.
2122
const DefaultOutputEncoding = JSON
2223

2324
var log = logging.Logger("cmds")
@@ -93,13 +94,13 @@ type Command struct {
9394

9495
var (
9596
// ErrNotCallable signals a command that cannot be called.
96-
ErrNotCallable = ClientError("This command can't be called directly. Try one of its subcommands.")
97+
ErrNotCallable = ClientError("this command cannot be called directly; try one of its subcommands.")
9798

9899
// ErrNoFormatter signals that the command can not be formatted.
99-
ErrNoFormatter = ClientError("This command cannot be formatted to plain text")
100+
ErrNoFormatter = ClientError("this command cannot be formatted to plain text")
100101

101102
// ErrIncorrectType signales that the commands returned a value with unexpected type.
102-
ErrIncorrectType = errors.New("The command returned a value with a different type than expected")
103+
ErrIncorrectType = errors.New("the command returned a value with a different type than expected")
103104
)
104105

105106
// Call invokes the command for the given Request

command_test.go

+6-5
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ func TestOptionValidation(t *testing.T) {
3939
cmd.Call(req, re, nil)
4040
} else {
4141
if err == nil {
42-
t.Errorf("Should have failed with error %q", tc.NewRequestError)
42+
t.Errorf("should have failed with error %q", tc.NewRequestError)
4343
} else if err.Error() != tc.NewRequestError {
4444
t.Errorf("expected error %q, got %q", tc.NewRequestError, err)
4545
}
@@ -50,7 +50,7 @@ func TestOptionValidation(t *testing.T) {
5050
tcs := []testcase{
5151
{
5252
opts: map[string]interface{}{"boop": true},
53-
NewRequestError: `Option "boop" should be type "string", but got type "bool"`,
53+
NewRequestError: `option "boop" should be type "string", but got type "bool"`,
5454
},
5555
{opts: map[string]interface{}{"beep": 5}},
5656
{opts: map[string]interface{}{"beep": 5, "boop": "test"}},
@@ -61,10 +61,10 @@ func TestOptionValidation(t *testing.T) {
6161
{opts: map[string]interface{}{"S": [2]string{"a", "b"}}},
6262
{
6363
opts: map[string]interface{}{"S": true},
64-
NewRequestError: `Option "S" should be type "array", but got type "bool"`},
64+
NewRequestError: `option "S" should be type "array", but got type "bool"`},
6565
{
6666
opts: map[string]interface{}{"beep": ":)"},
67-
NewRequestError: `Could not convert value ":)" to type "int" (for option "-beep")`,
67+
NewRequestError: `could not convert value ":)" to type "int" (for option "-beep")`,
6868
},
6969
}
7070

@@ -279,7 +279,8 @@ func TestPostRun(t *testing.T) {
279279
t.Log("next returned", v, err)
280280
if err != nil {
281281
close(ch)
282-
t.Fatal(err)
282+
t.Error(err)
283+
return
283284
}
284285

285286
ch <- v

executor_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import (
88
"testing"
99
)
1010

11-
var theError = errors.New("an error occurred")
11+
var errGeneric = errors.New("an error occurred")
1212

1313
var root = &Command{
1414
Subcommands: map[string]*Command{
@@ -20,7 +20,7 @@ var root = &Command{
2020
},
2121
"testError": &Command{
2222
Run: func(req *Request, re ResponseEmitter, env Environment) error {
23-
err := theError
23+
err := errGeneric
2424
if err != nil {
2525
return err
2626
}

http/config.go

+3-7
Original file line numberDiff line numberDiff line change
@@ -170,15 +170,11 @@ func allowUserAgent(r *http.Request, cfg *ServerConfig) bool {
170170
return true
171171
}
172172

173-
// Allow if the user agent does not start with Mozilla... (i.e. curl)
174-
ua := r.Header.Get("User-agent")
175-
if !strings.HasPrefix(ua, "Mozilla") {
176-
return true
177-
}
178-
173+
// Allow if the user agent does not start with Mozilla... (i.e. curl).
179174
// Disallow otherwise.
180175
//
181176
// This means the request probably came from a browser and thus, it
182177
// should have included Origin or referer headers.
183-
return false
178+
ua := r.Header.Get("User-agent")
179+
return !strings.HasPrefix(ua, "Mozilla")
184180
}

http/handler.go

+5-11
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"errors"
66
"net/http"
77
"runtime/debug"
8-
"strings"
98
"sync"
109
"time"
1110

@@ -17,11 +16,12 @@ import (
1716
var log = logging.Logger("cmds/http")
1817

1918
var (
20-
ErrNotFound = errors.New("404 page not found")
21-
errApiVersionMismatch = errors.New("api version mismatch")
19+
// ErrNotFound is returned when the endpoint does not exist.
20+
ErrNotFound = errors.New("404 page not found")
2221
)
2322

2423
const (
24+
// StreamErrHeader is used as trailer when stream errors happen.
2525
StreamErrHeader = "X-Stream-Error"
2626
streamHeader = "X-Stream-Output"
2727
channelHeader = "X-Chunked-Output"
@@ -32,7 +32,7 @@ const (
3232
transferEncodingHeader = "Transfer-Encoding"
3333
originHeader = "origin"
3434

35-
applicationJson = "application/json"
35+
applicationJSON = "application/json"
3636
applicationOctetStream = "application/octet-stream"
3737
plainText = "text/plain"
3838
)
@@ -57,6 +57,7 @@ type handler struct {
5757
env cmds.Environment
5858
}
5959

60+
// NewHandler creates the http.Handler for the given commands.
6061
func NewHandler(env cmds.Environment, root *cmds.Command, cfg *ServerConfig) http.Handler {
6162
if cfg == nil {
6263
panic("must provide a valid ServerConfig")
@@ -190,13 +191,6 @@ func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
190191
h.root.Call(req, re, h.env)
191192
}
192193

193-
func sanitizedErrStr(err error) string {
194-
s := err.Error()
195-
s = strings.Split(s, "\n")[0]
196-
s = strings.Split(s, "\r")[0]
197-
return s
198-
}
199-
200194
func setAllowedHeaders(w http.ResponseWriter, allowGet bool) {
201195
w.Header().Add("Allow", http.MethodHead)
202196
w.Header().Add("Allow", http.MethodOptions)

http/parse.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -10,9 +10,9 @@ import (
1010
"strconv"
1111
"strings"
1212

13-
"github.com/ipfs/go-ipfs-cmds"
13+
cmds "github.com/ipfs/go-ipfs-cmds"
1414

15-
"github.com/ipfs/go-ipfs-files"
15+
files "github.com/ipfs/go-ipfs-files"
1616
logging "github.com/ipfs/go-log"
1717
)
1818

@@ -133,7 +133,7 @@ func parseRequest(r *http.Request, root *cmds.Command) (*cmds.Request, error) {
133133

134134
// if there is a required filearg, error if no files were provided
135135
if len(requiredFile) > 0 && f == nil {
136-
return nil, fmt.Errorf("File argument '%s' is required", requiredFile)
136+
return nil, fmt.Errorf("file argument '%s' is required", requiredFile)
137137
}
138138

139139
ctx := logging.ContextWithLoggable(r.Context(), uuidLoggable())

0 commit comments

Comments
 (0)