*: partial staticcheck fix

This commit is contained in:
wpedrak 2021-03-10 13:07:36 +01:00 committed by Wojtek Pędrak
parent cb0e58942f
commit 2c2456bf3d
23 changed files with 39 additions and 40 deletions

View File

@ -523,7 +523,7 @@ type simpleHTTPClient struct {
// ErrNoRequest indicates that the HTTPRequest object could not be found // ErrNoRequest indicates that the HTTPRequest object could not be found
// or was nil. No processing could continue. // or was nil. No processing could continue.
var ErrNoRequest = errors.New("No HTTPRequest was available") var ErrNoRequest = errors.New("no HTTPRequest was available")
func (c *simpleHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) { func (c *simpleHTTPClient) Do(ctx context.Context, act httpAction) (*http.Response, []byte, error) {
req := act.HTTPRequest(c.endpoint) req := act.HTTPRequest(c.endpoint)

View File

@ -298,7 +298,7 @@ func (c *Client) credentialsForEndpoint(ep string) grpccredentials.TransportCred
} }
return credentials.NewBundle(credentials.Config{}).TransportCredentials() return credentials.NewBundle(credentials.Config{}).TransportCredentials()
default: default:
panic(fmt.Errorf("Unsupported CredsRequirement: %v", r)) panic(fmt.Errorf("unsupported CredsRequirement: %v", r))
} }
} }

View File

@ -140,13 +140,13 @@ func TestDialNoTimeout(t *testing.T) {
} }
func TestIsHaltErr(t *testing.T) { func TestIsHaltErr(t *testing.T) {
if !isHaltErr(nil, fmt.Errorf("etcdserver: some etcdserver error")) { if !isHaltErr(context.TODO(), fmt.Errorf("etcdserver: some etcdserver error")) {
t.Errorf(`error prefixed with "etcdserver: " should be Halted by default`) t.Errorf(`error prefixed with "etcdserver: " should be Halted by default`)
} }
if isHaltErr(nil, rpctypes.ErrGRPCStopped) { if isHaltErr(context.TODO(), rpctypes.ErrGRPCStopped) {
t.Errorf("error %v should not halt", rpctypes.ErrGRPCStopped) t.Errorf("error %v should not halt", rpctypes.ErrGRPCStopped)
} }
if isHaltErr(nil, rpctypes.ErrGRPCNoLeader) { if isHaltErr(context.TODO(), rpctypes.ErrGRPCNoLeader) {
t.Errorf("error %v should not halt", rpctypes.ErrGRPCNoLeader) t.Errorf("error %v should not halt", rpctypes.ErrGRPCNoLeader)
} }
ctx, cancel := context.WithCancel(context.TODO()) ctx, cancel := context.WithCancel(context.TODO())

View File

@ -26,13 +26,13 @@ import (
func TestMetadataWithRequireLeader(t *testing.T) { func TestMetadataWithRequireLeader(t *testing.T) {
ctx := context.TODO() ctx := context.TODO()
md, ok := metadata.FromOutgoingContext(ctx) _, ok := metadata.FromOutgoingContext(ctx)
if ok { if ok {
t.Fatal("expected no outgoing metadata ctx key") t.Fatal("expected no outgoing metadata ctx key")
} }
// add a conflicting key with some other value // add a conflicting key with some other value
md = metadata.Pairs(rpctypes.MetadataRequireLeaderKey, "invalid") md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, "invalid")
// add a key, and expect not be overwritten // add a key, and expect not be overwritten
md.Set("hello", "1", "2") md.Set("hello", "1", "2")
ctx = metadata.NewOutgoingContext(ctx, md) ctx = metadata.NewOutgoingContext(ctx, md)

View File

@ -50,7 +50,7 @@ func extractHostFromPath(pathStr string) string {
func mustSplit2(s, sep string) (string, string) { func mustSplit2(s, sep string) (string, string) {
spl := strings.SplitN(s, sep, 2) spl := strings.SplitN(s, sep, 2)
if len(spl) < 2 { if len(spl) < 2 {
panic(fmt.Errorf("Token '%v' expected to have separator sep: `%v`", s, sep)) panic(fmt.Errorf("token '%v' expected to have separator sep: `%v`", s, sep))
} }
return spl[0], spl[1] return spl[0], spl[1]
} }

View File

@ -77,7 +77,7 @@ func TestKvOrdering(t *testing.T) {
tt.prevRev, tt.prevRev,
sync.RWMutex{}, sync.RWMutex{},
} }
res, err := kv.Get(nil, "mockKey") res, err := kv.Get(context.TODO(), "mockKey")
if err != nil { if err != nil {
t.Errorf("#%d: expected response %+v, got error %+v", i, tt.response, err) t.Errorf("#%d: expected response %+v, got error %+v", i, tt.response, err)
} }

View File

@ -313,7 +313,7 @@ func isSafeRetry(lg *zap.Logger, err error, callOpts *options) bool {
} }
func isContextError(err error) bool { func isContextError(err error) bool {
return grpc.Code(err) == codes.DeadlineExceeded || grpc.Code(err) == codes.Canceled return status.Code(err) == codes.DeadlineExceeded || status.Code(err) == codes.Canceled
} }
func contextErrToGrpcErr(err error) error { func contextErrToGrpcErr(err error) error {

View File

@ -15,6 +15,7 @@
package clientv3 package clientv3
import ( import (
"context"
"testing" "testing"
"time" "time"
@ -44,7 +45,7 @@ func TestTxnPanics(t *testing.T) {
{ {
f: func() { f: func() {
defer df() defer df()
kv.Txn(nil).If(cmp).If(cmp) kv.Txn(context.TODO()).If(cmp).If(cmp)
}, },
err: "cannot call If twice!", err: "cannot call If twice!",
@ -52,7 +53,7 @@ func TestTxnPanics(t *testing.T) {
{ {
f: func() { f: func() {
defer df() defer df()
kv.Txn(nil).Then(op).If(cmp) kv.Txn(context.TODO()).Then(op).If(cmp)
}, },
err: "cannot call If after Then!", err: "cannot call If after Then!",
@ -60,7 +61,7 @@ func TestTxnPanics(t *testing.T) {
{ {
f: func() { f: func() {
defer df() defer df()
kv.Txn(nil).Else(op).If(cmp) kv.Txn(context.TODO()).Else(op).If(cmp)
}, },
err: "cannot call If after Else!", err: "cannot call If after Else!",
@ -68,7 +69,7 @@ func TestTxnPanics(t *testing.T) {
{ {
f: func() { f: func() {
defer df() defer df()
kv.Txn(nil).Then(op).Then(op) kv.Txn(context.TODO()).Then(op).Then(op)
}, },
err: "cannot call Then twice!", err: "cannot call Then twice!",
@ -76,7 +77,7 @@ func TestTxnPanics(t *testing.T) {
{ {
f: func() { f: func() {
defer df() defer df()
kv.Txn(nil).Else(op).Then(op) kv.Txn(context.TODO()).Else(op).Then(op)
}, },
err: "cannot call Then after Else!", err: "cannot call Then after Else!",
@ -84,7 +85,7 @@ func TestTxnPanics(t *testing.T) {
{ {
f: func() { f: func() {
defer df() defer df()
kv.Txn(nil).Else(op).Else(op) kv.Txn(context.TODO()).Else(op).Else(op)
}, },
err: "cannot call Else twice!", err: "cannot call Else twice!",

View File

@ -109,7 +109,7 @@ func execWatchCommandFunc(c *cli.Context, ki client.KeysAPI) {
go func() { go func() {
err := cmd.Start() err := cmd.Start()
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, err.Error()) fmt.Fprint(os.Stderr, err.Error())
os.Exit(1) os.Exit(1)
} }
cmd.Wait() cmd.Wait()

View File

@ -133,7 +133,7 @@ func epHealthCommandFunc(cmd *cobra.Command, args []string) {
eh.Error = err.Error() eh.Error = err.Error()
} }
if eh.Health == true { if eh.Health {
resp, err := cli.AlarmList(ctx) resp, err := cli.AlarmList(ctx)
if err == nil && len(resp.Alarms) > 0 { if err == nil && len(resp.Alarms) > 0 {
eh.Health = false eh.Health = false

View File

@ -98,6 +98,6 @@ func printMemberListWithHexJSON(r clientv3.MemberListResponse) {
} }
} }
buffer.WriteString("}") buffer.WriteString("}")
fmt.Println(string(buffer.Bytes())) fmt.Println(buffer.String())
} }

View File

@ -98,7 +98,7 @@ func watchInteractiveFunc(cmd *cobra.Command, osArgs []string, envKey, envRange
for { for {
l, err := reader.ReadString('\n') l, err := reader.ReadString('\n')
if err != nil { if err != nil {
ExitWithError(ExitInvalidInput, fmt.Errorf("Error reading watch request line: %v", err)) ExitWithError(ExitInvalidInput, fmt.Errorf("error reading watch request line: %v", err))
} }
l = strings.TrimSuffix(l, "\n") l = strings.TrimSuffix(l, "\n")

View File

@ -121,7 +121,7 @@ func ZeroToEnd(f *os.File) error {
// Returns error if dir is empty or exist with a different permission than specified. // Returns error if dir is empty or exist with a different permission than specified.
func CheckDirPermission(dir string, perm os.FileMode) error { func CheckDirPermission(dir string, perm os.FileMode) error {
if !Exist(dir) { if !Exist(dir) {
return fmt.Errorf("directory %q empty, cannot check permission.", dir) return fmt.Errorf("directory %q empty, cannot check permission", dir)
} }
//check the existing permission on the directory //check the existing permission on the directory
dirInfo, err := os.Stat(dir) dirInfo, err := os.Stat(dir)
@ -130,7 +130,7 @@ func CheckDirPermission(dir string, perm os.FileMode) error {
} }
dirMode := dirInfo.Mode().Perm() dirMode := dirInfo.Mode().Perm()
if dirMode != perm { if dirMode != perm {
err = fmt.Errorf("directory %q exist, but the permission is %q. The recommended permission is %q to prevent possible unprivileged access to the data.", dir, dirInfo.Mode(), os.FileMode(PrivateDirMode)) err = fmt.Errorf("directory %q exist, but the permission is %q. The recommended permission is %q to prevent possible unprivileged access to the data", dir, dirInfo.Mode(), os.FileMode(PrivateDirMode))
return err return err
} }
return nil return nil

View File

@ -41,10 +41,10 @@ func NewTransport(info TLSInfo, dialtimeoutd time.Duration) (*http.Transport, er
TLSClientConfig: cfg, TLSClientConfig: cfg,
} }
dialer := (&net.Dialer{ dialer := &net.Dialer{
Timeout: dialtimeoutd, Timeout: dialtimeoutd,
KeepAlive: 30 * time.Second, KeepAlive: 30 * time.Second,
}) }
dial := func(net, addr string) (net.Conn, error) { dial := func(net, addr string) (net.Conn, error) {
return dialer.Dial("unix", addr) return dialer.Dial("unix", addr)
} }

View File

@ -188,7 +188,6 @@ func (c Changer) makeVoter(cfg *tracker.Config, prs tracker.ProgressMap, id uint
nilAwareDelete(&cfg.Learners, id) nilAwareDelete(&cfg.Learners, id)
nilAwareDelete(&cfg.LearnersNext, id) nilAwareDelete(&cfg.LearnersNext, id)
incoming(cfg.Voters)[id] = struct{}{} incoming(cfg.Voters)[id] = struct{}{}
return
} }
// makeLearner makes the given ID a learner or stages it to be a learner once // makeLearner makes the given ID a learner or stages it to be a learner once
@ -321,10 +320,10 @@ func checkInvariants(cfg tracker.Config, prs tracker.ProgressMap) error {
if !joint(cfg) { if !joint(cfg) {
// We enforce that empty maps are nil instead of zero. // We enforce that empty maps are nil instead of zero.
if outgoing(cfg.Voters) != nil { if outgoing(cfg.Voters) != nil {
return fmt.Errorf("Voters[1] must be nil when not joint") return fmt.Errorf("cfg.Voters[1] must be nil when not joint")
} }
if cfg.LearnersNext != nil { if cfg.LearnersNext != nil {
return fmt.Errorf("LearnersNext must be nil when not joint") return fmt.Errorf("cfg.LearnersNext must be nil when not joint")
} }
if cfg.AutoLeave { if cfg.AutoLeave {
return fmt.Errorf("AutoLeave must be false when not joint") return fmt.Errorf("AutoLeave must be false when not joint")

View File

@ -169,7 +169,7 @@ func TestDataDriven(t *testing.T) {
// test case. // test case.
if !joint { if !joint {
idx := c.CommittedIndex(l) idx := c.CommittedIndex(l)
fmt.Fprintf(&buf, c.Describe(l)) fmt.Fprint(&buf, c.Describe(l))
// These alternative computations should return the same // These alternative computations should return the same
// result. If not, print to the output. // result. If not, print to the output.
if aIdx := alternativeMajorityCommittedIndex(c, l); aIdx != idx { if aIdx := alternativeMajorityCommittedIndex(c, l); aIdx != idx {
@ -213,7 +213,7 @@ func TestDataDriven(t *testing.T) {
fmt.Fprintf(&buf, "%s\n", idx) fmt.Fprintf(&buf, "%s\n", idx)
} else { } else {
cc := JointConfig([2]MajorityConfig{c, cj}) cc := JointConfig([2]MajorityConfig{c, cj})
fmt.Fprintf(&buf, cc.Describe(l)) fmt.Fprint(&buf, cc.Describe(l))
idx := cc.CommittedIndex(l) idx := cc.CommittedIndex(l)
// Interchanging the majorities shouldn't make a difference. If it does, print. // Interchanging the majorities shouldn't make a difference. If it does, print.
if aIdx := JointConfig([2]MajorityConfig{cj, c}).CommittedIndex(l); aIdx != idx { if aIdx := JointConfig([2]MajorityConfig{cj, c}).CommittedIndex(l); aIdx != idx {

View File

@ -44,10 +44,10 @@ func TestQuick(t *testing.T) {
} }
// smallRandIdxMap returns a reasonably sized map of ids to commit indexes. // smallRandIdxMap returns a reasonably sized map of ids to commit indexes.
func smallRandIdxMap(rand *rand.Rand, size int) map[uint64]Index { func smallRandIdxMap(rand *rand.Rand, _ int) map[uint64]Index {
// Hard-code a reasonably small size here (quick will hard-code 50, which // Hard-code a reasonably small size here (quick will hard-code 50, which
// is not useful here). // is not useful here).
size = 10 size := 10
n := rand.Intn(size) n := rand.Intn(size)
ids := rand.Perm(2 * n)[:n] ids := rand.Perm(2 * n)[:n]

View File

@ -28,7 +28,7 @@ func (env *InteractionEnv) handleLogLevel(t *testing.T, d datadriven.TestData) e
func (env *InteractionEnv) LogLevel(name string) error { func (env *InteractionEnv) LogLevel(name string) error {
for i, s := range lvlNames { for i, s := range lvlNames {
if strings.ToLower(s) == strings.ToLower(name) { if strings.EqualFold(s, name) {
env.Output.Lvl = i env.Output.Lvl = i
return nil return nil
} }

View File

@ -99,9 +99,9 @@ func (env *InteractionEnv) ProcessReady(idx int) error {
snap.Metadata.ConfState = *cs snap.Metadata.ConfState = *cs
env.Nodes[idx].History = append(env.Nodes[idx].History, snap) env.Nodes[idx].History = append(env.Nodes[idx].History, snap)
} }
for _, msg := range rd.Messages {
env.Messages = append(env.Messages, msg) env.Messages = append(env.Messages, rd.Messages...)
}
rn.Advance(rd) rn.Advance(rd)
return nil return nil
} }

View File

@ -64,7 +64,7 @@ func startNode(id uint64, peers []raft.Peer, iface iface) *node {
func (n *node) start() { func (n *node) start() {
n.stopc = make(chan struct{}) n.stopc = make(chan struct{})
ticker := time.Tick(5 * time.Millisecond) ticker := time.NewTicker(5 * time.Millisecond).C
go func() { go func() {
for { for {

View File

@ -467,7 +467,7 @@ func TestRawNodeJointAutoLeave(t *testing.T) {
t.Fatalf("exp:\n%+v\nact:\n%+v", expCs, cs) t.Fatalf("exp:\n%+v\nact:\n%+v", expCs, cs)
} }
if 0 != rawNode.raft.pendingConfIndex { if rawNode.raft.pendingConfIndex != 0 {
t.Fatalf("pendingConfIndex: expected %d, got %d", 0, rawNode.raft.pendingConfIndex) t.Fatalf("pendingConfIndex: expected %d, got %d", 0, rawNode.raft.pendingConfIndex)
} }

View File

@ -44,8 +44,7 @@ type BasicStatus struct {
func getProgressCopy(r *raft) map[uint64]tracker.Progress { func getProgressCopy(r *raft) map[uint64]tracker.Progress {
m := make(map[uint64]tracker.Progress) m := make(map[uint64]tracker.Progress)
r.prs.Visit(func(id uint64, pr *tracker.Progress) { r.prs.Visit(func(id uint64, pr *tracker.Progress) {
var p tracker.Progress p := *pr
p = *pr
p.Inflights = pr.Inflights.Clone() p.Inflights = pr.Inflights.Clone()
pr = nil pr = nil

View File

@ -194,7 +194,7 @@ func (p *ProgressTracker) Visit(f func(id uint64, pr *Progress)) {
// The optimization here mirrors that in `(MajorityConfig).CommittedIndex`, // The optimization here mirrors that in `(MajorityConfig).CommittedIndex`,
// see there for details. // see there for details.
var sl [7]uint64 var sl [7]uint64
ids := sl[:] var ids []uint64
if len(sl) >= n { if len(sl) >= n {
ids = sl[:n] ids = sl[:n]
} else { } else {