Introduce staticcheck for stricter builds (#7035)

This commit is contained in:
Harshavardhana
2019-02-13 04:59:36 -08:00
committed by Nitish Tiwari
parent 4ba77a916d
commit df35d7db9d
71 changed files with 274 additions and 777 deletions

View File

@@ -60,7 +60,7 @@ func TestCertNew(t *testing.T) {
if !reflect.DeepEqual(gcert.Certificate, expectedCert.Certificate) {
t.Error("certificate doesn't match expected certificate")
}
c, err = certs.New("server.crt", "server2.key", tls.LoadX509KeyPair)
_, err = certs.New("server.crt", "server2.key", tls.LoadX509KeyPair)
if err == nil {
t.Fatal("Expected to fail but got success")
}

View File

@@ -38,18 +38,6 @@ func TestFree(t *testing.T) {
t.Fatal(err)
}
if di.Total <= 0 {
t.Error("Unexpected Total", di.Total)
}
if di.Free <= 0 {
t.Error("Unexpected Free", di.Free)
}
if di.Files <= 0 {
t.Error("Unexpected Files", di.Files)
}
if di.Ffree <= 0 {
t.Error("Unexpected Ffree", di.Ffree)
}
if di.FSType == "UNKNOWN" {
t.Error("Unexpected FSType", di.FSType)
}

View File

@@ -38,10 +38,10 @@ var (
// `{1...64}`
// `{33...64}`
func parseEllipsesRange(pattern string) (seq []string, err error) {
if strings.Index(pattern, openBraces) == -1 {
if !strings.Contains(pattern, openBraces) {
return nil, errors.New("Invalid argument")
}
if strings.Index(pattern, closeBraces) == -1 {
if !strings.Contains(pattern, closeBraces) {
return nil, errors.New("Invalid argument")
}
@@ -145,7 +145,7 @@ func (p Pattern) Expand() []string {
case p.Suffix != "" && p.Prefix == "":
labels = append(labels, fmt.Sprintf("%s%s", p.Seq[i], p.Suffix))
case p.Suffix == "" && p.Prefix == "":
labels = append(labels, fmt.Sprintf("%s", p.Seq[i]))
labels = append(labels, p.Seq[i])
default:
labels = append(labels, fmt.Sprintf("%s%s%s", p.Prefix, p.Seq[i], p.Suffix))
}

View File

@@ -191,13 +191,11 @@ func (q Queue) ToRulesMap() RulesMap {
// Unused. Available for completion.
type lambda struct {
common
ARN string `xml:"CloudFunction"`
}
// Unused. Available for completion.
type topic struct {
common
ARN string `xml:"Topic" json:"Topic"`
}

View File

@@ -199,8 +199,7 @@ func TestQueueUnmarshalXML(t *testing.T) {
}
func TestQueueValidate(t *testing.T) {
var data []byte
data = []byte(`
data := []byte(`
<QueueConfiguration>
<Id>1</Id>
<Filter></Filter>
@@ -281,8 +280,7 @@ func TestQueueValidate(t *testing.T) {
}
func TestQueueSetRegion(t *testing.T) {
var data []byte
data = []byte(`
data := []byte(`
<QueueConfiguration>
<Id>1</Id>
<Filter></Filter>
@@ -341,8 +339,7 @@ func TestQueueSetRegion(t *testing.T) {
}
func TestQueueToRulesMap(t *testing.T) {
var data []byte
data = []byte(`
data := []byte(`
<QueueConfiguration>
<Id>1</Id>
<Filter></Filter>
@@ -520,8 +517,7 @@ func TestConfigUnmarshalXML(t *testing.T) {
}
func TestConfigValidate(t *testing.T) {
var data []byte
data = []byte(`
data := []byte(`
<NotificationConfiguration>
<QueueConfiguration>
<Id>1</Id>
@@ -628,8 +624,7 @@ func TestConfigValidate(t *testing.T) {
}
func TestConfigSetRegion(t *testing.T) {
var data []byte
data = []byte(`
data := []byte(`
<NotificationConfiguration>
<QueueConfiguration>
<Id>1</Id>
@@ -733,8 +728,7 @@ func TestConfigSetRegion(t *testing.T) {
}
func TestConfigToRulesMap(t *testing.T) {
var data []byte
data = []byte(`
data := []byte(`
<NotificationConfiguration>
<QueueConfiguration>
<Id>1</Id>

View File

@@ -142,13 +142,13 @@ Test-Header: TestHeaderValue
status, testCase.expectedStatus)
}
matched, err := regexp.MatchString(testCase.expectedLogRegexp, string(logOutput.Bytes()))
matched, err := regexp.MatchString(testCase.expectedLogRegexp, logOutput.String())
if err != nil {
t.Fatalf("Test %d: Incorrect regexp: %v", i+1, err)
}
if !matched {
t.Fatalf("Test %d: Unexpected log content, found: `%s`", i+1, string(logOutput.Bytes()))
t.Fatalf("Test %d: Unexpected log content, found: `%s`", i+1, logOutput.String())
}
}
}

View File

@@ -60,6 +60,9 @@ func TestHashReaderHelperMethods(t *testing.T) {
t.Errorf("Expected md5hex \"e2fc714c4727ee9395f324cd2e7f331f\", got %s", hex.EncodeToString(r.MD5Current()))
}
expectedSHA256, err := hex.DecodeString("88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589")
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(r.SHA256(), expectedSHA256) {
t.Errorf("Expected md5hex \"88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589\", got %s", r.SHA256HexString())
}

View File

@@ -22,7 +22,6 @@ import (
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/http/httputil"
"net/url"
@@ -61,9 +60,6 @@ type AdminClient struct {
// Advanced functionality.
isTraceEnabled bool
traceOutput io.Writer
// Random seed.
random *rand.Rand
}
// Global constants.
@@ -118,21 +114,17 @@ func privateNew(endpoint, accessKeyID, secretAccessKey string, secure bool) (*Ad
}
// SetAppInfo - add application details to user agent.
func (c *AdminClient) SetAppInfo(appName string, appVersion string) {
func (adm *AdminClient) SetAppInfo(appName string, appVersion string) {
// if app name and version is not set, we do not a new user
// agent.
if appName != "" && appVersion != "" {
c.appInfo = struct {
appName string
appVersion string
}{}
c.appInfo.appName = appName
c.appInfo.appVersion = appVersion
adm.appInfo.appName = appName
adm.appInfo.appVersion = appVersion
}
}
// SetCustomTransport - set new custom transport.
func (c *AdminClient) SetCustomTransport(customHTTPTransport http.RoundTripper) {
func (adm *AdminClient) SetCustomTransport(customHTTPTransport http.RoundTripper) {
// Set this to override default transport
// ``http.DefaultTransport``.
//
@@ -147,28 +139,28 @@ func (c *AdminClient) SetCustomTransport(customHTTPTransport http.RoundTripper)
// }
// api.SetTransport(tr)
//
if c.httpClient != nil {
c.httpClient.Transport = customHTTPTransport
if adm.httpClient != nil {
adm.httpClient.Transport = customHTTPTransport
}
}
// TraceOn - enable HTTP tracing.
func (c *AdminClient) TraceOn(outputStream io.Writer) {
func (adm *AdminClient) TraceOn(outputStream io.Writer) {
// if outputStream is nil then default to os.Stdout.
if outputStream == nil {
outputStream = os.Stdout
}
// Sets a new output stream.
c.traceOutput = outputStream
adm.traceOutput = outputStream
// Enable tracing.
c.isTraceEnabled = true
adm.isTraceEnabled = true
}
// TraceOff - disable HTTP tracing.
func (c *AdminClient) TraceOff() {
func (adm *AdminClient) TraceOff() {
// Disable tracing.
c.isTraceEnabled = false
adm.isTraceEnabled = false
}
// requestMetadata - is container for all the values to make a
@@ -181,7 +173,7 @@ type requestData struct {
}
// Filter out signature value from Authorization header.
func (c AdminClient) filterSignature(req *http.Request) {
func (adm AdminClient) filterSignature(req *http.Request) {
/// Signature V4 authorization header.
// Save the original auth.
@@ -197,19 +189,18 @@ func (c AdminClient) filterSignature(req *http.Request) {
// Set a temporary redacted auth
req.Header.Set("Authorization", newAuth)
return
}
// dumpHTTP - dump HTTP request and response.
func (c AdminClient) dumpHTTP(req *http.Request, resp *http.Response) error {
func (adm AdminClient) dumpHTTP(req *http.Request, resp *http.Response) error {
// Starts http dump.
_, err := fmt.Fprintln(c.traceOutput, "---------START-HTTP---------")
_, err := fmt.Fprintln(adm.traceOutput, "---------START-HTTP---------")
if err != nil {
return err
}
// Filter out Signature field from Authorization header.
c.filterSignature(req)
adm.filterSignature(req)
// Only display request header.
reqTrace, err := httputil.DumpRequestOut(req, false)
@@ -218,7 +209,7 @@ func (c AdminClient) dumpHTTP(req *http.Request, resp *http.Response) error {
}
// Write request to trace output.
_, err = fmt.Fprint(c.traceOutput, string(reqTrace))
_, err = fmt.Fprint(adm.traceOutput, string(reqTrace))
if err != nil {
return err
}
@@ -254,24 +245,24 @@ func (c AdminClient) dumpHTTP(req *http.Request, resp *http.Response) error {
}
}
// Write response to trace output.
_, err = fmt.Fprint(c.traceOutput, strings.TrimSuffix(string(respTrace), "\r\n"))
_, err = fmt.Fprint(adm.traceOutput, strings.TrimSuffix(string(respTrace), "\r\n"))
if err != nil {
return err
}
// Ends the http dump.
_, err = fmt.Fprintln(c.traceOutput, "---------END-HTTP---------")
_, err = fmt.Fprintln(adm.traceOutput, "---------END-HTTP---------")
return err
}
// do - execute http request.
func (c AdminClient) do(req *http.Request) (*http.Response, error) {
func (adm AdminClient) do(req *http.Request) (*http.Response, error) {
var resp *http.Response
var err error
// Do the request in a loop in case of 307 http is met since golang still doesn't
// handle properly this situation (https://github.com/golang/go/issues/7912)
for {
resp, err = c.httpClient.Do(req)
resp, err = adm.httpClient.Do(req)
if err != nil {
// Handle this specifically for now until future Golang
// versions fix this issue properly.
@@ -304,8 +295,8 @@ func (c AdminClient) do(req *http.Request) (*http.Response, error) {
}
// If trace is enabled, dump http request and response.
if c.isTraceEnabled {
err = c.dumpHTTP(req, resp)
if adm.isTraceEnabled {
err = adm.dumpHTTP(req, resp)
if err != nil {
return nil, err
}
@@ -323,7 +314,7 @@ var successStatus = []int{
// executeMethod - instantiates a given method, and retries the
// request upon any error up to maxRetries attempts in a binomially
// delayed manner using a standard back off algorithm.
func (c AdminClient) executeMethod(method string, reqData requestData) (res *http.Response, err error) {
func (adm AdminClient) executeMethod(method string, reqData requestData) (res *http.Response, err error) {
// Create a done channel to control 'ListObjects' go routine.
doneCh := make(chan struct{}, 1)
@@ -333,13 +324,13 @@ func (c AdminClient) executeMethod(method string, reqData requestData) (res *htt
// Instantiate a new request.
var req *http.Request
req, err = c.newRequest(method, reqData)
req, err = adm.newRequest(method, reqData)
if err != nil {
return nil, err
}
// Initiate the request.
res, err = c.do(req)
res, err = adm.do(req)
if err != nil {
return nil, err
}
@@ -368,15 +359,15 @@ func (c AdminClient) executeMethod(method string, reqData requestData) (res *htt
}
// set User agent.
func (c AdminClient) setUserAgent(req *http.Request) {
func (adm AdminClient) setUserAgent(req *http.Request) {
req.Header.Set("User-Agent", libraryUserAgent)
if c.appInfo.appName != "" && c.appInfo.appVersion != "" {
req.Header.Set("User-Agent", libraryUserAgent+" "+c.appInfo.appName+"/"+c.appInfo.appVersion)
if adm.appInfo.appName != "" && adm.appInfo.appVersion != "" {
req.Header.Set("User-Agent", libraryUserAgent+" "+adm.appInfo.appName+"/"+adm.appInfo.appVersion)
}
}
// newRequest - instantiate a new HTTP request for a given method.
func (c AdminClient) newRequest(method string, reqData requestData) (req *http.Request, err error) {
func (adm AdminClient) newRequest(method string, reqData requestData) (req *http.Request, err error) {
// If no method is supplied default to 'POST'.
if method == "" {
method = "POST"
@@ -386,7 +377,7 @@ func (c AdminClient) newRequest(method string, reqData requestData) (req *http.R
location := ""
// Construct a new target URL.
targetURL, err := c.makeTargetURL(reqData)
targetURL, err := adm.makeTargetURL(reqData)
if err != nil {
return nil, err
}
@@ -397,7 +388,7 @@ func (c AdminClient) newRequest(method string, reqData requestData) (req *http.R
return nil, err
}
c.setUserAgent(req)
adm.setUserAgent(req)
for k, v := range reqData.customHeaders {
req.Header.Set(k, v[0])
}
@@ -407,15 +398,15 @@ func (c AdminClient) newRequest(method string, reqData requestData) (req *http.R
req.Header.Set("X-Amz-Content-Sha256", hex.EncodeToString(sum256(reqData.content)))
req.Body = ioutil.NopCloser(bytes.NewReader(reqData.content))
req = s3signer.SignV4(*req, c.accessKeyID, c.secretAccessKey, "", location)
req = s3signer.SignV4(*req, adm.accessKeyID, adm.secretAccessKey, "", location)
return req, nil
}
// makeTargetURL make a new target url.
func (c AdminClient) makeTargetURL(r requestData) (*url.URL, error) {
func (adm AdminClient) makeTargetURL(r requestData) (*url.URL, error) {
host := c.endpointURL.Host
scheme := c.endpointURL.Scheme
host := adm.endpointURL.Host
scheme := adm.endpointURL.Scheme
urlStr := scheme + "://" + host + libraryAdminURLPrefix + r.relPath

View File

@@ -31,9 +31,8 @@ func TestMimeLookup(t *testing.T) {
}
func TestTypeByExtension(t *testing.T) {
var contentType string
// Test TypeByExtension.
contentType = TypeByExtension(".txt")
contentType := TypeByExtension(".txt")
if contentType != "text/plain" {
t.Fatalf("Invalid content type are found expected \"text/plain\", got %s", contentType)
}

View File

@@ -62,17 +62,16 @@ func FormatJSONSyntaxError(data io.Reader, offset int64) (highlight string) {
if readBytes > offset {
break
}
switch b {
case '\n':
if b == '\n' {
readLine.Reset()
errLine++
case '\t':
continue
} else if b == '\t' {
readLine.WriteByte(' ')
case '\r':
} else if b == '\r' {
break
default:
readLine.WriteByte(b)
}
readLine.WriteByte(b)
}
lineLen := readLine.Len()

View File

@@ -307,7 +307,6 @@ func (writer *messageWriter) start() {
case <-recordStagingTicker.C:
if !writer.flushRecords() {
quitFlag = true
break
}
case <-keepAliveTicker.C:

View File

@@ -408,9 +408,7 @@ func (s3Select *S3Select) Evaluate(w http.ResponseWriter) {
}
if err != nil {
if serr := writer.FinishWithError("InternalError", err.Error()); serr != nil {
// FIXME: log errors.
}
_ = writer.FinishWithError("InternalError", err.Error())
}
}

View File

@@ -274,10 +274,6 @@ func (e *FuncExpr) aggregateRow(r Record) error {
// called after calling aggregateRow() on each input row, to calculate
// the final aggregate result.
func (e *Expression) getAggregate() (*Value, error) {
return e.evalNode(nil)
}
func (e *FuncExpr) getAggregate() (*Value, error) {
switch e.getFunctionName() {
case aggFnCount:

View File

@@ -234,7 +234,9 @@ func handleDateAdd(r Record, d *DateAddFunc) (*Value, error) {
if err != nil {
return nil, err
}
inferTypeAsTimestamp(ts)
if err = inferTypeAsTimestamp(ts); err != nil {
return nil, err
}
t, ok := ts.ToTimestamp()
if !ok {
return nil, fmt.Errorf("%s() expects a timestamp argument", sqlFnDateAdd)
@@ -248,7 +250,9 @@ func handleDateDiff(r Record, d *DateDiffFunc) (*Value, error) {
if err != nil {
return nil, err
}
inferTypeAsTimestamp(tval1)
if err = inferTypeAsTimestamp(tval1); err != nil {
return nil, err
}
ts1, ok := tval1.ToTimestamp()
if !ok {
return nil, fmt.Errorf("%s() expects two timestamp arguments", sqlFnDateDiff)
@@ -258,7 +262,9 @@ func handleDateDiff(r Record, d *DateDiffFunc) (*Value, error) {
if err != nil {
return nil, err
}
inferTypeAsTimestamp(tval2)
if err = inferTypeAsTimestamp(tval2); err != nil {
return nil, err
}
ts2, ok := tval2.ToTimestamp()
if !ok {
return nil, fmt.Errorf("%s() expects two timestamp arguments", sqlFnDateDiff)
@@ -363,7 +369,9 @@ func handleSQLExtract(r Record, e *ExtractFunc) (res *Value, err error) {
return nil, verr
}
inferTypeAsTimestamp(timeVal)
if err = inferTypeAsTimestamp(timeVal); err != nil {
return nil, err
}
t, ok := timeVal.ToTimestamp()
if !ok {

View File

@@ -83,8 +83,6 @@ type Select struct {
type SelectExpression struct {
All bool `parser:" @\"*\""`
Expressions []*AliasedExpression `parser:"| @@ { \",\" @@ }"`
prop qProp
}
// TableExpression represents the FROM clause

View File

@@ -38,7 +38,6 @@ var (
layoutSecond,
layoutNanosecond,
}
oneNanoSecond = 1
)
func parseSQLTimestamp(s string) (t time.Time, err error) {

View File

@@ -248,7 +248,7 @@ func (v *Value) CSVString() string {
case typeBool:
return fmt.Sprintf("%v", v.value.(bool))
case typeString:
return fmt.Sprintf("%s", v.value.(string))
return v.value.(string)
case typeInt:
return fmt.Sprintf("%v", v.value.(int64))
case typeFloat:
@@ -610,22 +610,22 @@ func (v *Value) minmax(a *Value, isMax, isFirstRow bool) error {
return nil
}
func inferTypeAsTimestamp(v *Value) {
func inferTypeAsTimestamp(v *Value) error {
if s, ok := v.ToString(); ok {
t, err := parseSQLTimestamp(s)
if err != nil {
return
return err
}
v.setTimestamp(t)
} else if b, ok := v.ToBytes(); ok {
s := string(b)
t, err := parseSQLTimestamp(s)
if err != nil {
return
return err
}
v.setTimestamp(t)
}
return
return nil
}
// inferTypeAsString is used to convert untyped values to string - it

View File

@@ -22,8 +22,7 @@ import (
// Simply make sure creating a new tree works.
func TestNewTrie(t *testing.T) {
var trie *Trie
trie = NewTrie()
trie := NewTrie()
if trie.size != 0 {
t.Errorf("expected size 0, got: %d", trie.size)
@@ -32,8 +31,7 @@ func TestNewTrie(t *testing.T) {
// Ensure that we can insert new keys into the tree, then check the size.
func TestInsert(t *testing.T) {
var trie *Trie
trie = NewTrie()
trie := NewTrie()
// We need to have an empty tree to begin with.
if trie.size != 0 {
@@ -51,8 +49,7 @@ func TestInsert(t *testing.T) {
// Ensure that PrefixMatch gives us the correct two keys in the tree.
func TestPrefixMatch(t *testing.T) {
var trie *Trie
trie = NewTrie()
trie := NewTrie()
// Feed it some fodder: only 'minio' and 'miny-os' should trip the matcher.
trie.Insert("minio")

View File

@@ -26,7 +26,6 @@ func TestMinimum(t *testing.T) {
type testCase struct {
listval []int
expected int
pass bool
}
testCases := []testCase{
{listval: []int{3, 4, 15}, expected: 3},