Skip to content

Commit

Permalink
Address issues reported by staticcheck
Browse files Browse the repository at this point in the history
  • Loading branch information
fsouza committed Jan 2, 2019
1 parent 8b7e5fb commit 75f371e
Show file tree
Hide file tree
Showing 14 changed files with 47 additions and 52 deletions.
4 changes: 2 additions & 2 deletions auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (
)

// ErrCannotParseDockercfg is the error returned by NewAuthConfigurations when the dockercfg cannot be parsed.
var ErrCannotParseDockercfg = errors.New("Failed to read authentication from dockercfg")
var ErrCannotParseDockercfg = errors.New("failed to read authentication from dockercfg")

// AuthConfiguration represents authentication options to use in the PushImage
// method. It represents the authentication in the Docker index server.
Expand Down Expand Up @@ -108,7 +108,7 @@ func cfgPaths(dockerConfigEnv string, homeEnv string) []string {
// - $HOME/.docker/config.json
// - $HOME/.dockercfg
func NewAuthConfigurationsFromDockerCfg() (*AuthConfigurations, error) {
err := fmt.Errorf("No docker configuration found")
err := fmt.Errorf("no docker configuration found")
var auths *AuthConfigurations

pathsToTry := cfgPaths(os.Getenv("DOCKER_CONFIG"), os.Getenv("HOME"))
Expand Down
30 changes: 13 additions & 17 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ type APIVersion []int
// <minor> and <patch> are integer numbers.
func NewAPIVersion(input string) (APIVersion, error) {
if !strings.Contains(input, ".") {
return nil, fmt.Errorf("Unable to parse version %q", input)
return nil, fmt.Errorf("unable to parse version %q", input)
}
raw := strings.Split(input, "-")
arr := strings.Split(raw[0], ".")
Expand All @@ -79,7 +79,7 @@ func NewAPIVersion(input string) (APIVersion, error) {
for i, val := range arr {
ret[i], err = strconv.Atoi(val)
if err != nil {
return nil, fmt.Errorf("Unable to parse version %q: %q is not an integer", input, val)
return nil, fmt.Errorf("unable to parse version %q: %q is not an integer", input, val)
}
}
return ret, nil
Expand Down Expand Up @@ -329,7 +329,7 @@ func NewVersionedTLSClientFromBytes(endpoint string, certPEMBlock, keyPEMBlock,
} else {
caPool := x509.NewCertPool()
if !caPool.AppendCertsFromPEM(caPEMCert) {
return nil, errors.New("Could not add RootCA pem")
return nil, errors.New("could not add RootCA pem")
}
tlsConfig.RootCAs = caPool
}
Expand Down Expand Up @@ -387,7 +387,7 @@ func (c *Client) Endpoint() string {
//
// See https://goo.gl/wYfgY1 for more details.
func (c *Client) Ping() error {
return c.PingWithContext(nil)
return c.PingWithContext(context.TODO())
}

// PingWithContext pings the docker server
Expand All @@ -414,7 +414,7 @@ func (c *Client) getServerAPIVersionString() (version string, err error) {
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("Received unexpected status %d while trying to retrieve the server version", resp.StatusCode)
return "", fmt.Errorf("received unexpected status %d while trying to retrieve the server version", resp.StatusCode)
}
var versionResponse map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&versionResponse); err != nil {
Expand Down Expand Up @@ -639,18 +639,20 @@ func handleStreamResponse(resp *http.Response, streamOptions *streamOptions) err
_, err = io.Copy(streamOptions.stdout, resp.Body)
return err
}
if st, ok := streamOptions.stdout.(interface {
io.Writer
FD() uintptr
IsTerminal() bool
}); ok {
if st, ok := streamOptions.stdout.(stream); ok {
err = jsonmessage.DisplayJSONMessagesToStream(resp.Body, st, nil)
} else {
err = jsonmessage.DisplayJSONMessagesStream(resp.Body, streamOptions.stdout, 0, false, nil)
}
return err
}

type stream interface {
io.Writer
FD() uintptr
IsTerminal() bool
}

type proxyReader struct {
io.ReadCloser
calls uint64
Expand Down Expand Up @@ -760,6 +762,7 @@ func (c *Client) hijack(method, path string, hijackOptions hijackOptions) (Close
errs := make(chan error, 1)
quit := make(chan struct{})
go func() {
//lint:ignore SA1019 this is needed here
clientconn := httputil.NewClientConn(dial, nil)
defer clientconn.Close()
clientconn.Do(req)
Expand Down Expand Up @@ -872,13 +875,6 @@ func (c *Client) getFakeNativeURL(path string) string {
return fmt.Sprintf("%s%s", urlStr, path)
}

type jsonMessage struct {
Status string `json:"status,omitempty"`
Progress string `json:"progress,omitempty"`
Error string `json:"error,omitempty"`
Stream string `json:"stream,omitempty"`
}

func queryString(opts interface{}) string {
if opts == nil {
return ""
Expand Down
4 changes: 0 additions & 4 deletions client_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,6 @@ func (c *Client) initializeNativeClient(trFunc func() *http.Transport) {
sockPath := c.endpointURL.Path

tr := trFunc()

tr.Dial = func(network, addr string) (net.Conn, error) {
return c.Dialer.Dial(unixProtocol, sockPath)
}
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return c.Dialer.Dial(unixProtocol, sockPath)
}
Expand Down
3 changes: 2 additions & 1 deletion container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2096,7 +2096,8 @@ func runStreamConnServer(t *testing.T, network, laddr string, listening chan<- s
breader := bufio.NewReader(c)
req, err := http.ReadRequest(breader)
if err != nil {
t.Fatal(err)
t.Error(err)
return
}
if path := "/containers/" + containerID + "/export"; req.URL.Path != path {
t.Errorf("wrong path. Want %q. Got %q", path, req.URL.Path)
Expand Down
2 changes: 2 additions & 0 deletions event.go
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ func (c *Client) eventHijack(startTime int64, eventChan chan *APIEvents, errChan
if err != nil {
return err
}
//lint:ignore SA1019 this is needed here
conn := httputil.NewClientConn(dial, nil)
req, err := http.NewRequest("GET", uri, nil)
if err != nil {
Expand All @@ -339,6 +340,7 @@ func (c *Client) eventHijack(startTime int64, eventChan chan *APIEvents, errChan
if err != nil {
return err
}
//lint:ignore SA1019 ClientConn is needed here
go func(res *http.Response, conn *httputil.ClientConn) {
defer conn.Close()
defer res.Body.Close()
Expand Down
4 changes: 4 additions & 0 deletions internal/archive/archive.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,8 +276,10 @@ func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, er
case Bzip2, Xz:
// archive/bzip2 does not support writing, and there is no xz support at all
// However, this is not a problem as docker only currently generates gzipped tars
//lint:ignore ST1005 this is vendored/copied code
return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
default:
//lint:ignore ST1005 this is vendored/copied code
return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension())
}
}
Expand Down Expand Up @@ -437,7 +439,9 @@ func (ta *tarAppender) addTarFile(path, name string) error {
func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error {
capability, _ := system.Lgetxattr(path, "security.capability")
if capability != nil {
//lint:ignore SA1019 this is vendored/copied code
hdr.Xattrs = make(map[string]string)
//lint:ignore SA1019 this is vendored/copied code
hdr.Xattrs["security.capability"] = string(capability)
}
return nil
Expand Down
2 changes: 1 addition & 1 deletion misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
//
// See https://goo.gl/mU7yje for more details.
func (c *Client) Version() (*Env, error) {
return c.VersionWithContext(nil)
return c.VersionWithContext(context.TODO())
}

// VersionWithContext returns version information about the docker server.
Expand Down
10 changes: 4 additions & 6 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ func (c *Client) InstallPlugins(opts InstallPluginOptions) error {
data: opts.Plugins,
context: opts.Context,
})
defer resp.Body.Close()
if err != nil {
return err
}
resp.Body.Close()
return nil
}

Expand Down Expand Up @@ -288,7 +288,6 @@ type EnablePluginOptions struct {
func (c *Client) EnablePlugin(opts EnablePluginOptions) error {
path := "/plugins/" + opts.Name + "/enable?" + queryString(opts)
resp, err := c.do("POST", path, doOptions{context: opts.Context})
defer resp.Body.Close()
if err != nil {
return err
}
Expand All @@ -312,7 +311,6 @@ type DisablePluginOptions struct {
func (c *Client) DisablePlugin(opts DisablePluginOptions) error {
path := "/plugins/" + opts.Name + "/disable"
resp, err := c.do("POST", path, doOptions{context: opts.Context})
defer resp.Body.Close()
if err != nil {
return err
}
Expand Down Expand Up @@ -340,10 +338,10 @@ func (c *Client) CreatePlugin(opts CreatePluginOptions) (string, error) {
resp, err := c.do("POST", path, doOptions{
data: opts.Path,
context: opts.Context})
defer resp.Body.Close()
if err != nil {
return "", err
}
defer resp.Body.Close()
containerNameBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
Expand All @@ -367,10 +365,10 @@ type PushPluginOptions struct {
func (c *Client) PushPlugin(opts PushPluginOptions) error {
path := "/plugins/" + opts.Name + "/push"
resp, err := c.do("POST", path, doOptions{context: opts.Context})
defer resp.Body.Close()
if err != nil {
return err
}
resp.Body.Close()
return nil
}

Expand All @@ -394,13 +392,13 @@ func (c *Client) ConfigurePlugin(opts ConfigurePluginOptions) error {
data: opts.Envs,
context: opts.Context,
})
defer resp.Body.Close()
if err != nil {
if e, ok := err.(*Error); ok && e.Status == http.StatusNotFound {
return &NoSuchPlugin{ID: opts.Name}
}
return err
}
resp.Body.Close()
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion swarm_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ func TestGetServiceLogs(t *testing.T) {
}
}

func TesGetServicetLogsNilStdoutDoesntFail(t *testing.T) {
func TestGetServicetLogsNilStdoutDoesntFail(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
prefix := []byte{1, 0, 0, 0, 0, 0, 0, 19}
w.Write(prefix)
Expand Down
7 changes: 4 additions & 3 deletions swarm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package docker

import (
"context"
"net/http"
"net/url"
"reflect"
Expand Down Expand Up @@ -176,7 +177,7 @@ func TestInspectSwarm(t *testing.T) {
t.Parallel()
fakeRT := &FakeRoundTripper{message: `{"ID": "123"}`, status: http.StatusOK}
client := newTestClient(fakeRT)
response, err := client.InspectSwarm(nil)
response, err := client.InspectSwarm(context.TODO())
if err != nil {
t.Fatal(err)
}
Expand All @@ -198,12 +199,12 @@ func TestInspectSwarm(t *testing.T) {
func TestInspectSwarmNotInSwarm(t *testing.T) {
t.Parallel()
client := newTestClient(&FakeRoundTripper{message: "", status: http.StatusNotAcceptable})
_, err := client.InspectSwarm(nil)
_, err := client.InspectSwarm(context.TODO())
if err != ErrNodeNotInSwarm {
t.Errorf("InspectSwarm: Wrong error type. Want %#v. Got %#v", ErrNodeNotInSwarm, err)
}
client = newTestClient(&FakeRoundTripper{message: "", status: http.StatusServiceUnavailable})
_, err = client.InspectSwarm(nil)
_, err = client.InspectSwarm(context.TODO())
if err != ErrNodeNotInSwarm {
t.Errorf("InspectSwarm: Wrong error type. Want %#v. Got %#v", ErrNodeNotInSwarm, err)
}
Expand Down
8 changes: 4 additions & 4 deletions testing/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,7 @@ func (s *DockerServer) findImage(id string) (string, error) {
if _, ok := s.images[id]; ok {
return id, nil
}
return "", errors.New("No such image")
return "", errors.New("no such image")
}

func (s *DockerServer) createContainer(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -941,7 +941,7 @@ func (s *DockerServer) findContainerWithLock(idOrName string, shouldLock bool) (
if cont, ok := s.containers[idOrName]; ok {
return cont, nil
}
return nil, errors.New("No such container")
return nil, errors.New("no such container")
}

func (s *DockerServer) logContainer(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -1288,7 +1288,7 @@ func (s *DockerServer) findNetwork(idOrName string) (*docker.Network, int, error
return network, i, nil
}
}
return nil, -1, errors.New("No such network")
return nil, -1, errors.New("no such network")
}

func (s *DockerServer) listNetworks(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -1386,7 +1386,7 @@ func (s *DockerServer) networksConnect(w http.ResponseWriter, r *http.Request) {
return
}

if _, found := network.Containers[container.ID]; found == true {
if _, found := network.Containers[container.ID]; found {
http.Error(w, "endpoint already exists in network", http.StatusBadRequest)
return
}
Expand Down
9 changes: 5 additions & 4 deletions testing/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2828,10 +2828,11 @@ func TestDownloadFromContainer(t *testing.T) {
recorder := httptest.NewRecorder()
request, _ := http.NewRequest("GET", fmt.Sprintf("/containers/%s/archive?path=abcd", cont.ID), nil)
server.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Errorf("DownloadFromContainer: wrong status. Want %d. Got %d.", http.StatusOK, recorder.Code)
resp := recorder.Result()
if resp.StatusCode != http.StatusOK {
t.Errorf("DownloadFromContainer: wrong status. Want %d. Got %d.", http.StatusOK, resp.StatusCode)
}
if recorder.HeaderMap.Get("Content-Type") != "application/x-tar" {
t.Errorf("DownloadFromContainer: wrong Content-Type. Want 'application/x-tar'. Got %s.", recorder.HeaderMap.Get("Content-Type"))
if resp.Header.Get("Content-Type") != "application/x-tar" {
t.Errorf("DownloadFromContainer: wrong Content-Type. Want 'application/x-tar'. Got %s.", resp.Header.Get("Content-Type"))
}
}
12 changes: 4 additions & 8 deletions testing/swarm_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,8 +364,7 @@ func TestServiceCreate(t *testing.T) {
if err != nil {
t.Fatalf("ServiceCreate error: %s", err.Error())
}
var params io.Reader
params = bytes.NewBuffer(buf)
var params io.Reader = bytes.NewBuffer(buf)
request, _ := http.NewRequest("POST", "/services/create", params)
server.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
Expand Down Expand Up @@ -460,8 +459,7 @@ func TestServiceCreateDynamicPort(t *testing.T) {
if err != nil {
t.Fatalf("ServiceCreate error: %s", err.Error())
}
var params io.Reader
params = bytes.NewBuffer(buf)
var params io.Reader = bytes.NewBuffer(buf)
request, _ := http.NewRequest("POST", "/services/create", params)
server.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
Expand Down Expand Up @@ -525,8 +523,7 @@ func TestServiceCreateNoContainers(t *testing.T) {
if err != nil {
t.Fatalf("ServiceCreate error: %s", err.Error())
}
var params io.Reader
params = bytes.NewBuffer(buf)
var params io.Reader = bytes.NewBuffer(buf)
request, _ := http.NewRequest("POST", "/services/create", params)
server.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
Expand Down Expand Up @@ -1357,8 +1354,7 @@ func addTestService(server *DockerServer) (*swarm.Service, error) {
if err != nil {
return nil, err
}
var params io.Reader
params = bytes.NewBuffer(buf)
var params io.Reader = bytes.NewBuffer(buf)
request, _ := http.NewRequest("POST", "/services/create", params)
server.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
Expand Down
2 changes: 1 addition & 1 deletion tls.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func tlsDialWithDialer(dialer *net.Dialer, network, addr string, config *tls.Con
timeout := dialer.Timeout

if !dialer.Deadline.IsZero() {
deadlineTimeout := dialer.Deadline.Sub(time.Now())
deadlineTimeout := time.Until(dialer.Deadline)
if timeout == 0 || deadlineTimeout < timeout {
timeout = deadlineTimeout
}
Expand Down

0 comments on commit 75f371e

Please sign in to comment.