From f7f101d57ef8cbf2d8723a18b7d723c5c5dd04b6 Mon Sep 17 00:00:00 2001 From: Daniel Nephin Date: Mon, 11 Sep 2017 14:55:05 -0400 Subject: [PATCH] Add gosimple linter Update gometalinter Signed-off-by: Daniel Nephin --- api/server/httputils/write_log_stream.go | 11 +-- api/server/router/swarm/cluster_routes.go | 12 +-- api/types/filters/parse_test.go | 4 +- api/types/time/timestamp.go | 4 +- builder/dockerfile/bflag_test.go | 8 +- builder/dockerfile/internals.go | 10 +-- builder/dockerfile/parser/parser.go | 4 +- builder/remotecontext/detect_test.go | 2 +- builder/remotecontext/remote.go | 2 +- client/container_commit.go | 2 +- client/hijack.go | 2 +- cmd/dockerd/daemon.go | 2 +- container/view.go | 5 +- contrib/docker-device-tool/device_tool.go | 9 -- .../cluster/executor/container/attachment.go | 12 +-- daemon/config/config_unix_test.go | 19 ++-- daemon/exec/exec.go | 2 +- daemon/graphdriver/aufs/aufs_test.go | 89 +++++++------------ daemon/graphdriver/devmapper/deviceset.go | 15 ++-- daemon/graphdriver/devmapper/driver.go | 26 +++--- daemon/graphdriver/fsdiff.go | 2 +- .../graphdriver/graphtest/graphbench_unix.go | 6 +- daemon/graphdriver/overlay/overlay.go | 5 +- daemon/graphdriver/vfs/driver.go | 5 +- daemon/graphdriver/zfs/zfs.go | 2 +- daemon/images.go | 6 +- daemon/logger/factory.go | 2 +- daemon/logger/jsonfilelog/read.go | 3 +- daemon/logger/ring.go | 1 - daemon/logger/splunk/splunk_test.go | 21 ++--- daemon/metrics.go | 1 - daemon/network.go | 2 +- daemon/oci_linux.go | 1 + daemon/reload_test.go | 9 +- daemon/top_unix.go | 1 + distribution/push_v2.go | 7 +- hack/dockerfile/binaries-commits | 2 +- hack/validate/gometalinter.json | 5 +- image/fs_test.go | 11 +-- image/tarexport/load.go | 3 +- libcontainerd/client_linux.go | 5 +- pkg/authorization/authz.go | 2 +- pkg/devicemapper/devmapper.go | 6 +- pkg/discovery/kv/kv_test.go | 2 - pkg/loopback/ioctl.go | 10 +-- pkg/pools/pools_test.go | 21 ++--- pkg/signal/signal_linux_test.go | 2 +- reference/store_test.go | 6 +- registry/config.go | 4 +- registry/registry_test.go | 9 +- runconfig/hostconfig.go | 2 +- runconfig/hostconfig_test.go | 4 +- 52 files changed, 137 insertions(+), 271 deletions(-) diff --git a/api/server/httputils/write_log_stream.go b/api/server/httputils/write_log_stream.go index fd024e196e..e90e610da6 100644 --- a/api/server/httputils/write_log_stream.go +++ b/api/server/httputils/write_log_stream.go @@ -17,20 +17,13 @@ import ( // WriteLogStream writes an encoded byte stream of log messages from the // messages channel, multiplexing them with a stdcopy.Writer if mux is true -func WriteLogStream(ctx context.Context, w io.Writer, msgs <-chan *backend.LogMessage, config *types.ContainerLogsOptions, mux bool) { +func WriteLogStream(_ context.Context, w io.Writer, msgs <-chan *backend.LogMessage, config *types.ContainerLogsOptions, mux bool) { wf := ioutils.NewWriteFlusher(w) defer wf.Close() wf.Flush() - // this might seem like doing below is clear: - // var outStream io.Writer = wf - // however, this GREATLY DISPLEASES golint, and if you do that, it will - // fail CI. we need outstream to be type writer because if we mux streams, - // we will need to reassign all of the streams to be stdwriters, which only - // conforms to the io.Writer interface. - var outStream io.Writer - outStream = wf + outStream := io.Writer(wf) errStream := outStream sysErrStream := errStream if mux { diff --git a/api/server/router/swarm/cluster_routes.go b/api/server/router/swarm/cluster_routes.go index 7bd3aff182..55743a6218 100644 --- a/api/server/router/swarm/cluster_routes.go +++ b/api/server/router/swarm/cluster_routes.go @@ -427,11 +427,7 @@ func (sr *swarmRouter) updateSecret(ctx context.Context, w http.ResponseWriter, } id := vars["id"] - if err := sr.backend.UpdateSecret(id, version, secret); err != nil { - return err - } - - return nil + return sr.backend.UpdateSecret(id, version, secret) } func (sr *swarmRouter) getConfigs(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error { @@ -498,9 +494,5 @@ func (sr *swarmRouter) updateConfig(ctx context.Context, w http.ResponseWriter, } id := vars["id"] - if err := sr.backend.UpdateConfig(id, version, config); err != nil { - return err - } - - return nil + return sr.backend.UpdateConfig(id, version, config) } diff --git a/api/types/filters/parse_test.go b/api/types/filters/parse_test.go index c5dd2bc3db..5279054854 100644 --- a/api/types/filters/parse_test.go +++ b/api/types/filters/parse_test.go @@ -182,7 +182,7 @@ func TestArgsMatchKVList(t *testing.T) { } for args, field := range matches { - if args.MatchKVList(field, sources) != true { + if !args.MatchKVList(field, sources) { t.Fatalf("Expected true for %v on %v, got false", sources, args) } } @@ -202,7 +202,7 @@ func TestArgsMatchKVList(t *testing.T) { } for args, field := range differs { - if args.MatchKVList(field, sources) != false { + if args.MatchKVList(field, sources) { t.Fatalf("Expected false for %v on %v, got true", sources, args) } } diff --git a/api/types/time/timestamp.go b/api/types/time/timestamp.go index 9aa9702dad..ed9c1168b7 100644 --- a/api/types/time/timestamp.go +++ b/api/types/time/timestamp.go @@ -29,10 +29,8 @@ func GetTimestamp(value string, reference time.Time) (string, error) { } var format string - var parseInLocation bool - // if the string has a Z or a + or three dashes use parse otherwise use parseinlocation - parseInLocation = !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) + parseInLocation := !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) if strings.Contains(value, ".") { if parseInLocation { diff --git a/builder/dockerfile/bflag_test.go b/builder/dockerfile/bflag_test.go index ac07e48c14..4ea10fff4b 100644 --- a/builder/dockerfile/bflag_test.go +++ b/builder/dockerfile/bflag_test.go @@ -34,10 +34,10 @@ func TestBuilderFlags(t *testing.T) { t.Fatalf("Test3 of %q was supposed to work: %s", bf.Args, err) } - if flStr1.IsUsed() == true { + if flStr1.IsUsed() { t.Fatal("Test3 - str1 was not used!") } - if flBool1.IsUsed() == true { + if flBool1.IsUsed() { t.Fatal("Test3 - bool1 was not used!") } @@ -58,10 +58,10 @@ func TestBuilderFlags(t *testing.T) { if flBool1.IsTrue() { t.Fatal("Bool1 was supposed to default to: false") } - if flStr1.IsUsed() == true { + if flStr1.IsUsed() { t.Fatal("Str1 was not used!") } - if flBool1.IsUsed() == true { + if flBool1.IsUsed() { t.Fatal("Bool1 was not used!") } diff --git a/builder/dockerfile/internals.go b/builder/dockerfile/internals.go index b18118ce36..5424e75841 100644 --- a/builder/dockerfile/internals.go +++ b/builder/dockerfile/internals.go @@ -206,10 +206,7 @@ func lookupUser(userStr, filepath string) (int, error) { return uid, nil } users, err := lcUser.ParsePasswdFileFilter(filepath, func(u lcUser.User) bool { - if u.Name == userStr { - return true - } - return false + return u.Name == userStr }) if err != nil { return 0, err @@ -228,10 +225,7 @@ func lookupGroup(groupStr, filepath string) (int, error) { return gid, nil } groups, err := lcUser.ParseGroupFileFilter(filepath, func(g lcUser.Group) bool { - if g.Name == groupStr { - return true - } - return false + return g.Name == groupStr }) if err != nil { return 0, err diff --git a/builder/dockerfile/parser/parser.go b/builder/dockerfile/parser/parser.go index 7f07ff2150..4003cba465 100644 --- a/builder/dockerfile/parser/parser.go +++ b/builder/dockerfile/parser/parser.go @@ -143,7 +143,7 @@ func (d *Directive) possibleParserDirective(line string) error { if len(tecMatch) != 0 { for i, n := range tokenEscapeCommand.SubexpNames() { if n == "escapechar" { - if d.escapeSeen == true { + if d.escapeSeen { return errors.New("only one escape parser directive can be used") } d.escapeSeen = true @@ -159,7 +159,7 @@ func (d *Directive) possibleParserDirective(line string) error { if len(tpcMatch) != 0 { for i, n := range tokenPlatformCommand.SubexpNames() { if n == "platform" { - if d.platformSeen == true { + if d.platformSeen { return errors.New("only one platform parser directive can be used") } d.platformSeen = true diff --git a/builder/remotecontext/detect_test.go b/builder/remotecontext/detect_test.go index 6b47ac2274..d5dfa495bb 100644 --- a/builder/remotecontext/detect_test.go +++ b/builder/remotecontext/detect_test.go @@ -21,7 +21,7 @@ const ( const shouldStayFilename = "should_stay" func extractFilenames(files []os.FileInfo) []string { - filenames := make([]string, len(files), len(files)) + filenames := make([]string, len(files)) for i, file := range files { filenames[i] = file.Name() diff --git a/builder/remotecontext/remote.go b/builder/remotecontext/remote.go index 6733ff9e54..6c4073bd4c 100644 --- a/builder/remotecontext/remote.go +++ b/builder/remotecontext/remote.go @@ -116,7 +116,7 @@ func inspectResponse(ct string, r io.Reader, clen int64) (string, io.ReadCloser, plen = maxPreambleLength } - preamble := make([]byte, plen, plen) + preamble := make([]byte, plen) rlen, err := r.Read(preamble) if rlen == 0 { return ct, ioutil.NopCloser(r), errors.New("empty response") diff --git a/client/container_commit.go b/client/container_commit.go index 531d796ee7..b3b16abfd1 100644 --- a/client/container_commit.go +++ b/client/container_commit.go @@ -39,7 +39,7 @@ func (cli *Client) ContainerCommit(ctx context.Context, container string, option for _, change := range options.Changes { query.Add("changes", change) } - if options.Pause != true { + if !options.Pause { query.Set("pause", "0") } diff --git a/client/hijack.go b/client/hijack.go index dc754fca7d..d04cebdcf4 100644 --- a/client/hijack.go +++ b/client/hijack.go @@ -70,7 +70,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 } diff --git a/cmd/dockerd/daemon.go b/cmd/dockerd/daemon.go index c2f3781d88..1c55d9993f 100644 --- a/cmd/dockerd/daemon.go +++ b/cmd/dockerd/daemon.go @@ -467,7 +467,7 @@ func loadDaemonCliConfig(opts *daemonOptions) (*config.Config, error) { return nil, err } - if conf.V2Only == false { + if !conf.V2Only { logrus.Warnf(`The "disable-legacy-registry" option is deprecated and wil be removed in Docker v17.12. Interacting with legacy (v1) registries will no longer be supported in Docker v17.12"`) } diff --git a/container/view.go b/container/view.go index 8d885268c2..164827c550 100644 --- a/container/view.go +++ b/container/view.go @@ -203,10 +203,7 @@ func (db *memDB) ReserveName(name, containerID string) error { // Once released, a name can be reserved again func (db *memDB) ReleaseName(name string) error { return db.withTxn(func(txn *memdb.Txn) error { - if err := txn.Delete(memdbNamesTable, nameAssociation{name: name}); err != nil { - return err - } - return nil + return txn.Delete(memdbNamesTable, nameAssociation{name: name}) }) } diff --git a/contrib/docker-device-tool/device_tool.go b/contrib/docker-device-tool/device_tool.go index 8f6251582a..905b689581 100644 --- a/contrib/docker-device-tool/device_tool.go +++ b/contrib/docker-device-tool/device_tool.go @@ -90,14 +90,12 @@ func main() { fmt.Printf("Sector size: %d\n", status.SectorSize) fmt.Printf("Data use: %d of %d (%.1f %%)\n", status.Data.Used, status.Data.Total, 100.0*float64(status.Data.Used)/float64(status.Data.Total)) fmt.Printf("Metadata use: %d of %d (%.1f %%)\n", status.Metadata.Used, status.Metadata.Total, 100.0*float64(status.Metadata.Used)/float64(status.Metadata.Total)) - break case "list": ids := devices.List() sort.Strings(ids) for _, id := range ids { fmt.Println(id) } - break case "device": if flag.NArg() < 2 { usage() @@ -113,7 +111,6 @@ func main() { fmt.Printf("Size in Sectors: %d\n", status.SizeInSectors) fmt.Printf("Mapped Sectors: %d\n", status.MappedSectors) fmt.Printf("Highest Mapped Sector: %d\n", status.HighestMappedSector) - break case "resize": if flag.NArg() < 2 { usage() @@ -131,7 +128,6 @@ func main() { os.Exit(1) } - break case "snap": if flag.NArg() < 3 { usage() @@ -142,7 +138,6 @@ func main() { fmt.Println("Can't create snap device: ", err) os.Exit(1) } - break case "remove": if flag.NArg() < 2 { usage() @@ -153,7 +148,6 @@ func main() { fmt.Println("Can't remove device: ", err) os.Exit(1) } - break case "mount": if flag.NArg() < 3 { usage() @@ -164,13 +158,10 @@ func main() { fmt.Println("Can't mount device: ", err) os.Exit(1) } - break default: fmt.Printf("Unknown command %s\n", args[0]) usage() os.Exit(1) } - - return } diff --git a/daemon/cluster/executor/container/attachment.go b/daemon/cluster/executor/container/attachment.go index 54f95a1fbf..2aab47e462 100644 --- a/daemon/cluster/executor/container/attachment.go +++ b/daemon/cluster/executor/container/attachment.go @@ -40,11 +40,7 @@ func (nc *networkAttacherController) Update(ctx context.Context, t *api.Task) er func (nc *networkAttacherController) Prepare(ctx context.Context) error { // Make sure all the networks that the task needs are created. - if err := nc.adapter.createNetworks(ctx); err != nil { - return err - } - - return nil + return nc.adapter.createNetworks(ctx) } func (nc *networkAttacherController) Start(ctx context.Context) error { @@ -69,11 +65,7 @@ func (nc *networkAttacherController) Terminate(ctx context.Context) error { func (nc *networkAttacherController) Remove(ctx context.Context) error { // Try removing the network referenced in this task in case this // task is the last one referencing it - if err := nc.adapter.removeNetworks(ctx); err != nil { - return err - } - - return nil + return nc.adapter.removeNetworks(ctx) } func (nc *networkAttacherController) Close() error { diff --git a/daemon/config/config_unix_test.go b/daemon/config/config_unix_test.go index 5987e77e00..fedf757eb4 100644 --- a/daemon/config/config_unix_test.go +++ b/daemon/config/config_unix_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/docker/docker/opts" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/gotestyourself/gotestyourself/fs" "github.com/spf13/pflag" "github.com/stretchr/testify/assert" @@ -14,7 +14,7 @@ import ( ) func TestGetConflictFreeConfiguration(t *testing.T) { - configFileData := string([]byte(` + configFileData := ` { "debug": true, "default-ulimits": { @@ -27,7 +27,7 @@ func TestGetConflictFreeConfiguration(t *testing.T) { "log-opts": { "tag": "test_tag" } - }`)) + }` file := fs.NewFile(t, "docker-config", fs.WithContent(configFileData)) defer file.Remove() @@ -55,7 +55,7 @@ func TestGetConflictFreeConfiguration(t *testing.T) { } func TestDaemonConfigurationMerge(t *testing.T) { - configFileData := string([]byte(` + configFileData := ` { "debug": true, "default-ulimits": { @@ -68,7 +68,7 @@ func TestDaemonConfigurationMerge(t *testing.T) { "log-opts": { "tag": "test_tag" } - }`)) + }` file := fs.NewFile(t, "docker-config", fs.WithContent(configFileData)) defer file.Remove() @@ -115,10 +115,7 @@ func TestDaemonConfigurationMerge(t *testing.T) { } func TestDaemonConfigurationMergeShmSize(t *testing.T) { - data := string([]byte(` - { - "default-shm-size": "1g" - }`)) + data := `{"default-shm-size": "1g"}` file := fs.NewFile(t, "docker-config", fs.WithContent(data)) defer file.Remove() @@ -133,7 +130,5 @@ func TestDaemonConfigurationMergeShmSize(t *testing.T) { require.NoError(t, err) expectedValue := 1 * 1024 * 1024 * 1024 - if cc.ShmSize.Value() != int64(expectedValue) { - t.Fatalf("expected default shm size %d, got %d", expectedValue, cc.ShmSize.Value()) - } + assert.Equal(t, int64(expectedValue), cc.ShmSize.Value()) } diff --git a/daemon/exec/exec.go b/daemon/exec/exec.go index 2348ad8fd5..f4efb4d54e 100644 --- a/daemon/exec/exec.go +++ b/daemon/exec/exec.go @@ -75,7 +75,7 @@ type Store struct { // NewStore initializes a new exec store. func NewStore() *Store { - return &Store{commands: make(map[string]*Config, 0)} + return &Store{commands: make(map[string]*Config)} } // Commands returns the exec configurations in the store. diff --git a/daemon/graphdriver/aufs/aufs_test.go b/daemon/graphdriver/aufs/aufs_test.go index 532074eee6..31f88e729f 100644 --- a/daemon/graphdriver/aufs/aufs_test.go +++ b/daemon/graphdriver/aufs/aufs_test.go @@ -18,6 +18,8 @@ import ( "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/stringid" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( @@ -179,9 +181,8 @@ func TestCleanupWithNoDirs(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) - if err := d.Cleanup(); err != nil { - t.Fatal(err) - } + err := d.Cleanup() + assert.NoError(t, err) } func TestCleanupWithDir(t *testing.T) { @@ -201,18 +202,12 @@ func TestMountedFalseResponse(t *testing.T) { d := newDriver(t) defer os.RemoveAll(tmp) - if err := d.Create("1", "", nil); err != nil { - t.Fatal(err) - } + err := d.Create("1", "", nil) + require.NoError(t, err) response, err := d.mounted(d.getDiffPath("1")) - if err != nil { - t.Fatal(err) - } - - if response != false { - t.Fatal("Response if dir id 1 is mounted should be false") - } + require.NoError(t, err) + assert.False(t, response) } func TestMountedTrueResponse(t *testing.T) { @@ -220,26 +215,17 @@ func TestMountedTrueResponse(t *testing.T) { defer os.RemoveAll(tmp) defer d.Cleanup() - if err := d.Create("1", "", nil); err != nil { - t.Fatal(err) - } - if err := d.Create("2", "1", nil); err != nil { - t.Fatal(err) - } + err := d.Create("1", "", nil) + require.NoError(t, err) + err = d.Create("2", "1", nil) + require.NoError(t, err) - _, err := d.Get("2", "") - if err != nil { - t.Fatal(err) - } + _, err = d.Get("2", "") + require.NoError(t, err) response, err := d.mounted(d.pathCache["2"]) - if err != nil { - t.Fatal(err) - } - - if response != true { - t.Fatal("Response if dir id 2 is mounted should be true") - } + require.NoError(t, err) + assert.True(t, response) } func TestMountWithParent(t *testing.T) { @@ -574,9 +560,8 @@ func TestStatus(t *testing.T) { } status := d.Status() - if status == nil || len(status) == 0 { - t.Fatal("Status should not be nil or empty") - } + assert.Len(t, status, 4) + rootDir := status[0] dirs := status[2] if rootDir[0] != "Root Dir" { @@ -677,27 +662,19 @@ func testMountMoreThan42Layers(t *testing.T, mountPath string) { } current = hash(current) - if err := d.CreateReadWrite(current, parent, nil); err != nil { - t.Logf("Current layer %d", i) - t.Error(err) - } + err := d.CreateReadWrite(current, parent, nil) + require.NoError(t, err, "current layer %d", i) + point, err := d.Get(current, "") - if err != nil { - t.Logf("Current layer %d", i) - t.Error(err) - } + require.NoError(t, err, "current layer %d", i) + f, err := os.Create(path.Join(point, current)) - if err != nil { - t.Logf("Current layer %d", i) - t.Error(err) - } + require.NoError(t, err, "current layer %d", i) f.Close() if i%10 == 0 { - if err := os.Remove(path.Join(point, parent)); err != nil { - t.Logf("Current layer %d", i) - t.Error(err) - } + err := os.Remove(path.Join(point, parent)) + require.NoError(t, err, "current layer %d", i) expected-- } last = current @@ -705,20 +682,14 @@ func testMountMoreThan42Layers(t *testing.T, mountPath string) { // Perform the actual mount for the top most image point, err := d.Get(last, "") - if err != nil { - t.Error(err) - } + require.NoError(t, err) files, err := ioutil.ReadDir(point) - if err != nil { - t.Error(err) - } - if len(files) != expected { - t.Errorf("Expected %d got %d", expected, len(files)) - } + require.NoError(t, err) + assert.Len(t, files, expected) } func TestMountMoreThan42Layers(t *testing.T) { - os.RemoveAll(tmpOuter) + defer os.RemoveAll(tmpOuter) testMountMoreThan42Layers(t, tmp) } diff --git a/daemon/graphdriver/devmapper/deviceset.go b/daemon/graphdriver/devmapper/deviceset.go index 32b35c9acd..4b50d95368 100644 --- a/daemon/graphdriver/devmapper/deviceset.go +++ b/daemon/graphdriver/devmapper/deviceset.go @@ -1254,14 +1254,13 @@ func (devices *DeviceSet) setupBaseImage() error { } func setCloseOnExec(name string) { - if fileInfos, _ := ioutil.ReadDir("/proc/self/fd"); fileInfos != nil { - for _, i := range fileInfos { - link, _ := os.Readlink(filepath.Join("/proc/self/fd", i.Name())) - if link == name { - fd, err := strconv.Atoi(i.Name()) - if err == nil { - unix.CloseOnExec(fd) - } + fileInfos, _ := ioutil.ReadDir("/proc/self/fd") + for _, i := range fileInfos { + link, _ := os.Readlink(filepath.Join("/proc/self/fd", i.Name())) + if link == name { + fd, err := strconv.Atoi(i.Name()) + if err == nil { + unix.CloseOnExec(fd) } } } diff --git a/daemon/graphdriver/devmapper/driver.go b/daemon/graphdriver/devmapper/driver.go index 02ee0124f1..c7756ecc3b 100644 --- a/daemon/graphdriver/devmapper/driver.go +++ b/daemon/graphdriver/devmapper/driver.go @@ -69,18 +69,18 @@ func (d *Driver) Status() [][2]string { status := [][2]string{ {"Pool Name", s.PoolName}, - {"Pool Blocksize", fmt.Sprintf("%s", units.HumanSize(float64(s.SectorSize)))}, - {"Base Device Size", fmt.Sprintf("%s", units.HumanSize(float64(s.BaseDeviceSize)))}, + {"Pool Blocksize", units.HumanSize(float64(s.SectorSize))}, + {"Base Device Size", units.HumanSize(float64(s.BaseDeviceSize))}, {"Backing Filesystem", s.BaseDeviceFS}, {"Data file", s.DataFile}, {"Metadata file", s.MetadataFile}, - {"Data Space Used", fmt.Sprintf("%s", units.HumanSize(float64(s.Data.Used)))}, - {"Data Space Total", fmt.Sprintf("%s", units.HumanSize(float64(s.Data.Total)))}, - {"Data Space Available", fmt.Sprintf("%s", units.HumanSize(float64(s.Data.Available)))}, - {"Metadata Space Used", fmt.Sprintf("%s", units.HumanSize(float64(s.Metadata.Used)))}, - {"Metadata Space Total", fmt.Sprintf("%s", units.HumanSize(float64(s.Metadata.Total)))}, - {"Metadata Space Available", fmt.Sprintf("%s", units.HumanSize(float64(s.Metadata.Available)))}, - {"Thin Pool Minimum Free Space", fmt.Sprintf("%s", units.HumanSize(float64(s.MinFreeSpace)))}, + {"Data Space Used", units.HumanSize(float64(s.Data.Used))}, + {"Data Space Total", units.HumanSize(float64(s.Data.Total))}, + {"Data Space Available", units.HumanSize(float64(s.Data.Available))}, + {"Metadata Space Used", units.HumanSize(float64(s.Metadata.Used))}, + {"Metadata Space Total", units.HumanSize(float64(s.Metadata.Total))}, + {"Metadata Space Available", units.HumanSize(float64(s.Metadata.Available))}, + {"Thin Pool Minimum Free Space", units.HumanSize(float64(s.MinFreeSpace))}, {"Udev Sync Supported", fmt.Sprintf("%v", s.UdevSyncSupported)}, {"Deferred Removal Enabled", fmt.Sprintf("%v", s.DeferredRemoveEnabled)}, {"Deferred Deletion Enabled", fmt.Sprintf("%v", s.DeferredDeleteEnabled)}, @@ -159,13 +159,7 @@ func (d *Driver) Remove(id string) error { if err := d.DeviceSet.DeleteDevice(id, false); err != nil { return fmt.Errorf("failed to remove device %s: %v", id, err) } - - mp := path.Join(d.home, "mnt", id) - if err := system.EnsureRemoveAll(mp); err != nil { - return err - } - - return nil + return system.EnsureRemoveAll(path.Join(d.home, "mnt", id)) } // Get mounts a device with given id into the root filesystem diff --git a/daemon/graphdriver/fsdiff.go b/daemon/graphdriver/fsdiff.go index e8c7ff27a4..6f4258e8e6 100644 --- a/daemon/graphdriver/fsdiff.go +++ b/daemon/graphdriver/fsdiff.go @@ -94,7 +94,7 @@ func (gdw *NaiveDiffDriver) Diff(id, parent string) (arch io.ReadCloser, err err // are extracted from tar's with full second precision on modified time. // We need this hack here to make sure calls within same second receive // correct result. - time.Sleep(startTime.Truncate(time.Second).Add(time.Second).Sub(time.Now())) + time.Sleep(time.Until(startTime.Truncate(time.Second).Add(time.Second))) return err }), nil } diff --git a/daemon/graphdriver/graphtest/graphbench_unix.go b/daemon/graphdriver/graphtest/graphbench_unix.go index def822b9a1..aa833e8a83 100644 --- a/daemon/graphdriver/graphtest/graphbench_unix.go +++ b/daemon/graphdriver/graphtest/graphbench_unix.go @@ -3,13 +3,13 @@ package graphtest import ( - "bytes" "io" "io/ioutil" "path/filepath" "testing" "github.com/docker/docker/pkg/stringid" + "github.com/stretchr/testify/require" ) // DriverBenchExists benchmarks calls to exist @@ -251,9 +251,7 @@ func DriverBenchDeepLayerRead(b *testing.B, layerCount int, drivername string, d } b.StopTimer() - if bytes.Compare(c, content) != 0 { - b.Fatalf("Wrong content in file %v, expected %v", c, content) - } + require.Equal(b, content, c) b.StartTimer() } } diff --git a/daemon/graphdriver/overlay/overlay.go b/daemon/graphdriver/overlay/overlay.go index 0d14b045f9..a4b03cfd44 100644 --- a/daemon/graphdriver/overlay/overlay.go +++ b/daemon/graphdriver/overlay/overlay.go @@ -269,10 +269,7 @@ func (d *Driver) Create(id, parent string, opts *graphdriver.CreateOpts) (retErr // Toplevel images are just a "root" dir if parent == "" { - if err := idtools.MkdirAs(path.Join(dir, "root"), 0755, rootUID, rootGID); err != nil { - return err - } - return nil + return idtools.MkdirAndChown(path.Join(dir, "root"), 0755, idtools.IDPair{rootUID, rootGID}) } parentDir := d.dir(parent) diff --git a/daemon/graphdriver/vfs/driver.go b/daemon/graphdriver/vfs/driver.go index 15a4de3606..f67ada3582 100644 --- a/daemon/graphdriver/vfs/driver.go +++ b/daemon/graphdriver/vfs/driver.go @@ -103,10 +103,7 @@ func (d *Driver) dir(id string) string { // Remove deletes the content from the directory for a given id. func (d *Driver) Remove(id string) error { - if err := system.EnsureRemoveAll(d.dir(id)); err != nil { - return err - } - return nil + return system.EnsureRemoveAll(d.dir(id)) } // Get returns the directory for the given id. diff --git a/daemon/graphdriver/zfs/zfs.go b/daemon/graphdriver/zfs/zfs.go index 729099a6cd..1bfdfbc7da 100644 --- a/daemon/graphdriver/zfs/zfs.go +++ b/daemon/graphdriver/zfs/zfs.go @@ -416,5 +416,5 @@ func (d *Driver) Put(id string) error { func (d *Driver) Exists(id string) bool { d.Lock() defer d.Unlock() - return d.filesystemsCache[d.zfsPath(id)] == true + return d.filesystemsCache[d.zfsPath(id)] } diff --git a/daemon/images.go b/daemon/images.go index 9be6e0ec30..f4110ce789 100644 --- a/daemon/images.go +++ b/daemon/images.go @@ -301,12 +301,10 @@ func (daemon *Daemon) SquashImage(id, parent string) (string, error) { } defer daemon.stores[img.Platform()].layerStore.Release(newL) - var newImage image.Image - newImage = *img + newImage := *img newImage.RootFS = nil - var rootFS image.RootFS - rootFS = *parentImg.RootFS + rootFS := *parentImg.RootFS rootFS.DiffIDs = append(rootFS.DiffIDs, newL.DiffID()) newImage.RootFS = &rootFS diff --git a/daemon/logger/factory.go b/daemon/logger/factory.go index 32001590d9..2ef3bf8799 100644 --- a/daemon/logger/factory.go +++ b/daemon/logger/factory.go @@ -93,7 +93,7 @@ func (lf *logdriverFactory) getLogOptValidator(name string) LogOptValidator { lf.m.Lock() defer lf.m.Unlock() - c, _ := lf.optValidator[name] + c := lf.optValidator[name] return c } diff --git a/daemon/logger/jsonfilelog/read.go b/daemon/logger/jsonfilelog/read.go index 32425b5128..25fc99a984 100644 --- a/daemon/logger/jsonfilelog/read.go +++ b/daemon/logger/jsonfilelog/read.go @@ -137,8 +137,7 @@ func newSectionReader(f *os.File) (*io.SectionReader, error) { } func tailFile(f io.ReadSeeker, logWatcher *logger.LogWatcher, tail int, since time.Time) { - var rdr io.Reader - rdr = f + rdr := io.Reader(f) if tail > 0 { ls, err := tailfile.TailFile(f, tail) if err != nil { diff --git a/daemon/logger/ring.go b/daemon/logger/ring.go index dea8f6b6a4..c89897cfde 100644 --- a/daemon/logger/ring.go +++ b/daemon/logger/ring.go @@ -202,7 +202,6 @@ func (r *messageRing) Close() { r.closed = true r.wait.Broadcast() r.mu.Unlock() - return } // Drain drains all messages from the queue. diff --git a/daemon/logger/splunk/splunk_test.go b/daemon/logger/splunk/splunk_test.go index cbe9a55bf9..2e63b969d1 100644 --- a/daemon/logger/splunk/splunk_test.go +++ b/daemon/logger/splunk/splunk_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/docker/docker/daemon/logger" + "github.com/stretchr/testify/require" ) // Validate options @@ -125,7 +126,7 @@ func TestDefault(t *testing.T) { splunkLoggerDriver.nullMessage.Source != "" || splunkLoggerDriver.nullMessage.SourceType != "" || splunkLoggerDriver.nullMessage.Index != "" || - splunkLoggerDriver.gzipCompression != false || + splunkLoggerDriver.gzipCompression || splunkLoggerDriver.postMessagesFrequency != defaultPostMessagesFrequency || splunkLoggerDriver.postMessagesBatchSize != defaultPostMessagesBatchSize || splunkLoggerDriver.bufferMaximum != defaultBufferMaximum || @@ -255,7 +256,7 @@ func TestInlineFormatWithNonDefaultOptions(t *testing.T) { splunkLoggerDriver.nullMessage.Source != "mysource" || splunkLoggerDriver.nullMessage.SourceType != "mysourcetype" || splunkLoggerDriver.nullMessage.Index != "myindex" || - splunkLoggerDriver.gzipCompression != true || + !splunkLoggerDriver.gzipCompression || splunkLoggerDriver.gzipCompressionLevel != gzip.DefaultCompression || splunkLoggerDriver.postMessagesFrequency != defaultPostMessagesFrequency || splunkLoggerDriver.postMessagesBatchSize != defaultPostMessagesBatchSize || @@ -355,7 +356,7 @@ func TestJsonFormat(t *testing.T) { splunkLoggerDriver.nullMessage.Source != "" || splunkLoggerDriver.nullMessage.SourceType != "" || splunkLoggerDriver.nullMessage.Index != "" || - splunkLoggerDriver.gzipCompression != true || + !splunkLoggerDriver.gzipCompression || splunkLoggerDriver.gzipCompressionLevel != gzip.BestSpeed || splunkLoggerDriver.postMessagesFrequency != defaultPostMessagesFrequency || splunkLoggerDriver.postMessagesBatchSize != defaultPostMessagesBatchSize || @@ -448,14 +449,10 @@ func TestRawFormat(t *testing.T) { } hostname, err := info.Hostname() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) loggerDriver, err := New(info) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if !hec.connectionVerified { t.Fatal("By default connection should be verified") @@ -472,7 +469,7 @@ func TestRawFormat(t *testing.T) { splunkLoggerDriver.nullMessage.Source != "" || splunkLoggerDriver.nullMessage.SourceType != "" || splunkLoggerDriver.nullMessage.Index != "" || - splunkLoggerDriver.gzipCompression != false || + splunkLoggerDriver.gzipCompression || splunkLoggerDriver.postMessagesFrequency != defaultPostMessagesFrequency || splunkLoggerDriver.postMessagesBatchSize != defaultPostMessagesBatchSize || splunkLoggerDriver.bufferMaximum != defaultBufferMaximum || @@ -586,7 +583,7 @@ func TestRawFormatWithLabels(t *testing.T) { splunkLoggerDriver.nullMessage.Source != "" || splunkLoggerDriver.nullMessage.SourceType != "" || splunkLoggerDriver.nullMessage.Index != "" || - splunkLoggerDriver.gzipCompression != false || + splunkLoggerDriver.gzipCompression || splunkLoggerDriver.postMessagesFrequency != defaultPostMessagesFrequency || splunkLoggerDriver.postMessagesBatchSize != defaultPostMessagesBatchSize || splunkLoggerDriver.bufferMaximum != defaultBufferMaximum || @@ -698,7 +695,7 @@ func TestRawFormatWithoutTag(t *testing.T) { splunkLoggerDriver.nullMessage.Source != "" || splunkLoggerDriver.nullMessage.SourceType != "" || splunkLoggerDriver.nullMessage.Index != "" || - splunkLoggerDriver.gzipCompression != false || + splunkLoggerDriver.gzipCompression || splunkLoggerDriver.postMessagesFrequency != defaultPostMessagesFrequency || splunkLoggerDriver.postMessagesBatchSize != defaultPostMessagesBatchSize || splunkLoggerDriver.bufferMaximum != defaultBufferMaximum || diff --git a/daemon/metrics.go b/daemon/metrics.go index 8cd363fb11..44228e7db4 100644 --- a/daemon/metrics.go +++ b/daemon/metrics.go @@ -169,5 +169,4 @@ func pluginStopMetricsCollection(p plugingetter.CompatPlugin) { logrus.WithError(err).WithField("name", p.Name()).WithField("socket", sockPath).Error("error unmounting metrics socket for plugin") } } - return } diff --git a/daemon/network.go b/daemon/network.go index 62fe951cbb..411c1f9284 100644 --- a/daemon/network.go +++ b/daemon/network.go @@ -115,6 +115,7 @@ var ( func (daemon *Daemon) startIngressWorker() { ingressJobsChannel = make(chan *ingressJob, 100) go func() { + // nolint: gosimple for { select { case r := <-ingressJobsChannel: @@ -232,7 +233,6 @@ func (daemon *Daemon) releaseIngress(id string) { logrus.Errorf("Failed to delete ingress network %s: %v", n.ID(), err) return } - return } // SetNetworkBootstrapKeys sets the bootstrap keys. diff --git a/daemon/oci_linux.go b/daemon/oci_linux.go index 9cf6674dfe..3d411bb251 100644 --- a/daemon/oci_linux.go +++ b/daemon/oci_linux.go @@ -29,6 +29,7 @@ import ( "github.com/sirupsen/logrus" ) +// nolint: gosimple var ( deviceCgroupRuleRegex = regexp.MustCompile("^([acb]) ([0-9]+|\\*):([0-9]+|\\*) ([rwm]{1,3})$") ) diff --git a/daemon/reload_test.go b/daemon/reload_test.go index bf11b6bd56..a4bba80168 100644 --- a/daemon/reload_test.go +++ b/daemon/reload_test.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker/pkg/discovery" _ "github.com/docker/docker/pkg/discovery/memory" "github.com/docker/docker/registry" + "github.com/stretchr/testify/assert" ) func TestDaemonReloadLabels(t *testing.T) { @@ -85,15 +86,11 @@ func TestDaemonReloadAllowNondistributableArtifacts(t *testing.T) { for _, value := range serviceConfig.AllowNondistributableArtifactsCIDRs { actual = append(actual, value.String()) } - for _, value := range serviceConfig.AllowNondistributableArtifactsHostnames { - actual = append(actual, value) - } + actual = append(actual, serviceConfig.AllowNondistributableArtifactsHostnames...) sort.Strings(registries) sort.Strings(actual) - if !reflect.DeepEqual(registries, actual) { - t.Fatalf("expected %v, got %v\n", registries, actual) - } + assert.Equal(t, registries, actual) } func TestDaemonReloadMirrors(t *testing.T) { diff --git a/daemon/top_unix.go b/daemon/top_unix.go index ec2b1da8b7..22e88b702e 100644 --- a/daemon/top_unix.go +++ b/daemon/top_unix.go @@ -16,6 +16,7 @@ func validatePSArgs(psArgs string) error { // NOTE: \\s does not detect unicode whitespaces. // So we use fieldsASCII instead of strings.Fields in parsePSOutput. // See https://github.com/docker/docker/pull/24358 + // nolint: gosimple re := regexp.MustCompile("\\s+([^\\s]*)=\\s*(PID[^\\s]*)") for _, group := range re.FindAllStringSubmatch(psArgs, -1) { if len(group) >= 3 { diff --git a/distribution/push_v2.go b/distribution/push_v2.go index 5ceac8b7ea..1dfa881b48 100644 --- a/distribution/push_v2.go +++ b/distribution/push_v2.go @@ -395,12 +395,7 @@ func (pd *v2PushDescriptor) Upload(ctx context.Context, progressOutput progress. defer layerUpload.Close() // upload the blob - desc, err := pd.uploadUsingSession(ctx, progressOutput, diffID, layerUpload) - if err != nil { - return desc, err - } - - return desc, nil + return pd.uploadUsingSession(ctx, progressOutput, diffID, layerUpload) } func (pd *v2PushDescriptor) SetRemoteDescriptor(descriptor distribution.Descriptor) { diff --git a/hack/dockerfile/binaries-commits b/hack/dockerfile/binaries-commits index 3c465a4073..4338a3b48b 100644 --- a/hack/dockerfile/binaries-commits +++ b/hack/dockerfile/binaries-commits @@ -10,4 +10,4 @@ LIBNETWORK_COMMIT=7b2b1feb1de4817d522cc372af149ff48d25028e VNDR_COMMIT=9909bb2b8a0b7ea464527b376dc50389c90df587 # Linting -GOMETALINTER_COMMIT=5507b26af3204e949ffe50ec08ee73e5847938e1 +GOMETALINTER_COMMIT=bfcc1d6942136fd86eb6f1a6fb328de8398fbd80 diff --git a/hack/validate/gometalinter.json b/hack/validate/gometalinter.json index c43ddec892..baa531e443 100644 --- a/hack/validate/gometalinter.json +++ b/hack/validate/gometalinter.json @@ -9,15 +9,14 @@ "api/types/container/container_.*", "integration-cli/" ], - "Skip": [ - "integration-cli/" - ], + "Skip": ["integration-cli/"], "Enable": [ "deadcode", "gofmt", "goimports", "golint", + "gosimple", "ineffassign", "interfacer", "unconvert", diff --git a/image/fs_test.go b/image/fs_test.go index 5464ab5171..2672524039 100644 --- a/image/fs_test.go +++ b/image/fs_test.go @@ -1,7 +1,6 @@ package image import ( - "bytes" "crypto/rand" "crypto/sha256" "encoding/hex" @@ -12,7 +11,7 @@ import ( "testing" "github.com/docker/docker/internal/testutil" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/stretchr/testify/assert" ) @@ -112,9 +111,7 @@ func TestFSMetadataGetSet(t *testing.T) { actual, err := store.GetMetadata(tc.id, tc.key) assert.NoError(t, err) - if bytes.Compare(actual, tc.value) != 0 { - t.Fatalf("Metadata expected %q, got %q", tc.value, actual) - } + assert.Equal(t, tc.value, actual) } _, err = store.GetMetadata(id2, "tkey2") @@ -183,9 +180,7 @@ func TestFSGetSet(t *testing.T) { for _, tc := range tcases { data, err := store.Get(tc.expected) assert.NoError(t, err) - if bytes.Compare(data, tc.input) != 0 { - t.Fatalf("expected data %q, got %q", tc.input, data) - } + assert.Equal(t, tc.input, data) } } diff --git a/image/tarexport/load.go b/image/tarexport/load.go index 480400cd64..8bb1ac166b 100644 --- a/image/tarexport/load.go +++ b/image/tarexport/load.go @@ -82,8 +82,7 @@ func (l *tarexporter) Load(inTar io.ReadCloser, outStream io.Writer, quiet bool) if err := checkCompatibleOS(img.OS); err != nil { return err } - var rootFS image.RootFS - rootFS = *img.RootFS + rootFS := *img.RootFS rootFS.DiffIDs = nil if expected, actual := len(m.Layers), len(img.RootFS.DiffIDs); expected != actual { diff --git a/libcontainerd/client_linux.go b/libcontainerd/client_linux.go index 6c3460a8c9..12808fd0c1 100644 --- a/libcontainerd/client_linux.go +++ b/libcontainerd/client_linux.go @@ -296,10 +296,7 @@ func (clnt *client) UpdateResources(containerID string, resources Resources) err Pid: InitFriendlyName, Resources: (*containerd.UpdateResource)(&resources), }) - if err != nil { - return err - } - return nil + return err } func (clnt *client) getExitNotifier(containerID string) *exitNotifier { diff --git a/pkg/authorization/authz.go b/pkg/authorization/authz.go index 924908af9b..3bd2fc0bf6 100644 --- a/pkg/authorization/authz.go +++ b/pkg/authorization/authz.go @@ -158,7 +158,7 @@ func sendBody(url string, header http.Header) bool { // headers returns flatten version of the http headers excluding authorization func headers(header http.Header) map[string]string { - v := make(map[string]string, 0) + v := make(map[string]string) for k, values := range header { // Skip authorization headers if strings.EqualFold(k, "Authorization") || strings.EqualFold(k, "X-Registry-Config") || strings.EqualFold(k, "X-Registry-Auth") { diff --git a/pkg/devicemapper/devmapper.go b/pkg/devicemapper/devmapper.go index 6a0ac24647..48618765fb 100644 --- a/pkg/devicemapper/devmapper.go +++ b/pkg/devicemapper/devmapper.go @@ -351,8 +351,7 @@ func RemoveDeviceDeferred(name string) error { // disable udev dm rules and delete the symlink under /dev/mapper by itself, // even if the removal is deferred by the kernel. cookie := new(uint) - var flags uint16 - flags = DmUdevDisableLibraryFallback + flags := uint16(DmUdevDisableLibraryFallback) if err := task.setCookie(cookie, flags); err != nil { return fmt.Errorf("devicemapper: Can not set cookie: %s", err) } @@ -465,8 +464,7 @@ func CreatePool(poolName string, dataFile, metadataFile *os.File, poolBlockSize } cookie := new(uint) - var flags uint16 - flags = DmUdevDisableSubsystemRulesFlag | DmUdevDisableDiskRulesFlag | DmUdevDisableOtherRulesFlag + flags := uint16(DmUdevDisableSubsystemRulesFlag | DmUdevDisableDiskRulesFlag | DmUdevDisableOtherRulesFlag) if err := task.setCookie(cookie, flags); err != nil { return fmt.Errorf("devicemapper: Can't set cookie %s", err) } diff --git a/pkg/discovery/kv/kv_test.go b/pkg/discovery/kv/kv_test.go index dab3939dd0..adc5c289a4 100644 --- a/pkg/discovery/kv/kv_test.go +++ b/pkg/discovery/kv/kv_test.go @@ -11,7 +11,6 @@ import ( "github.com/docker/docker/pkg/discovery" "github.com/docker/libkv" "github.com/docker/libkv/store" - "github.com/go-check/check" ) @@ -130,7 +129,6 @@ func (s *Mock) AtomicDelete(key string, previous *store.KVPair) (bool, error) { // Close mock func (s *Mock) Close() { - return } func (ds *DiscoverySuite) TestInitializeWithCerts(c *check.C) { diff --git a/pkg/loopback/ioctl.go b/pkg/loopback/ioctl.go index fa744f0a69..84fcea669c 100644 --- a/pkg/loopback/ioctl.go +++ b/pkg/loopback/ioctl.go @@ -17,10 +17,7 @@ func ioctlLoopCtlGetFree(fd uintptr) (int, error) { } func ioctlLoopSetFd(loopFd, sparseFd uintptr) error { - if err := unix.IoctlSetInt(int(loopFd), LoopSetFd, int(sparseFd)); err != nil { - return err - } - return nil + return unix.IoctlSetInt(int(loopFd), LoopSetFd, int(sparseFd)) } func ioctlLoopSetStatus64(loopFd uintptr, loopInfo *loopInfo64) error { @@ -47,8 +44,5 @@ func ioctlLoopGetStatus64(loopFd uintptr) (*loopInfo64, error) { } func ioctlLoopSetCapacity(loopFd uintptr, value int) error { - if err := unix.IoctlSetInt(int(loopFd), LoopSetCapacity, value); err != nil { - return err - } - return nil + return unix.IoctlSetInt(int(loopFd), LoopSetCapacity, value) } diff --git a/pkg/pools/pools_test.go b/pkg/pools/pools_test.go index d71cb99ac7..544c499957 100644 --- a/pkg/pools/pools_test.go +++ b/pkg/pools/pools_test.go @@ -6,6 +6,9 @@ import ( "io" "strings" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestBufioReaderPoolGetWithNoReaderShouldCreateOne(t *testing.T) { @@ -92,22 +95,16 @@ func TestBufioWriterPoolPutAndGet(t *testing.T) { buf := new(bytes.Buffer) bw := bufio.NewWriter(buf) writer := BufioWriter32KPool.Get(bw) - if writer == nil { - t.Fatalf("BufioReaderPool should not return a nil writer.") - } + require.NotNil(t, writer) + written, err := writer.Write([]byte("foobar")) - if err != nil { - t.Fatal(err) - } - if written != 6 { - t.Fatalf("Should have written 6 bytes, but wrote %v bytes", written) - } + require.NoError(t, err) + assert.Equal(t, 6, written) + // Make sure we Flush all the way ? writer.Flush() bw.Flush() - if len(buf.Bytes()) != 6 { - t.Fatalf("The buffer should contain 6 bytes ('foobar') but contains %v ('%v')", buf.Bytes(), string(buf.Bytes())) - } + assert.Len(t, buf.Bytes(), 6) // Reset the buffer buf.Reset() BufioWriter32KPool.Put(writer) diff --git a/pkg/signal/signal_linux_test.go b/pkg/signal/signal_linux_test.go index 32c056fe49..da0e010545 100644 --- a/pkg/signal/signal_linux_test.go +++ b/pkg/signal/signal_linux_test.go @@ -41,7 +41,7 @@ func TestCatchAll(t *testing.T) { } func TestStopCatch(t *testing.T) { - signal, _ := SignalMap["HUP"] + signal := SignalMap["HUP"] channel := make(chan os.Signal, 1) CatchAll(channel) go func() { diff --git a/reference/store_test.go b/reference/store_test.go index 59567b5f63..72a19d6b86 100644 --- a/reference/store_test.go +++ b/reference/store_test.go @@ -306,19 +306,19 @@ func TestAddDeleteGet(t *testing.T) { } // Delete a few references - if deleted, err := store.Delete(ref1); err != nil || deleted != true { + if deleted, err := store.Delete(ref1); err != nil || !deleted { t.Fatal("Delete failed") } if _, err := store.Get(ref1); err != ErrDoesNotExist { t.Fatal("Expected ErrDoesNotExist from Get") } - if deleted, err := store.Delete(ref5); err != nil || deleted != true { + if deleted, err := store.Delete(ref5); err != nil || !deleted { t.Fatal("Delete failed") } if _, err := store.Get(ref5); err != ErrDoesNotExist { t.Fatal("Expected ErrDoesNotExist from Get") } - if deleted, err := store.Delete(nameOnly); err != nil || deleted != true { + if deleted, err := store.Delete(nameOnly); err != nil || !deleted { t.Fatal("Delete failed") } if _, err := store.Get(nameOnly); err != ErrDoesNotExist { diff --git a/registry/config.go b/registry/config.go index 70efb4330f..8014b913a7 100644 --- a/registry/config.go +++ b/registry/config.go @@ -75,7 +75,7 @@ func newServiceConfig(options ServiceOptions) *serviceConfig { config := &serviceConfig{ ServiceConfig: registrytypes.ServiceConfig{ InsecureRegistryCIDRs: make([]*registrytypes.NetIPNet, 0), - IndexConfigs: make(map[string]*registrytypes.IndexInfo, 0), + IndexConfigs: make(map[string]*registrytypes.IndexInfo), // Hack: Bypass setting the mirrors to IndexConfigs since they are going away // and Mirrors are only for the official registry anyways. }, @@ -171,7 +171,7 @@ func (config *serviceConfig) LoadInsecureRegistries(registries []string) error { originalIndexInfos := config.ServiceConfig.IndexConfigs config.ServiceConfig.InsecureRegistryCIDRs = make([]*registrytypes.NetIPNet, 0) - config.ServiceConfig.IndexConfigs = make(map[string]*registrytypes.IndexInfo, 0) + config.ServiceConfig.IndexConfigs = make(map[string]*registrytypes.IndexInfo) skip: for _, r := range registries { diff --git a/registry/registry_test.go b/registry/registry_test.go index d89c46c2c0..eef319966b 100644 --- a/registry/registry_test.go +++ b/registry/registry_test.go @@ -14,6 +14,7 @@ import ( "github.com/docker/distribution/registry/client/transport" "github.com/docker/docker/api/types" registrytypes "github.com/docker/docker/api/types/registry" + "github.com/stretchr/testify/assert" ) var ( @@ -747,16 +748,12 @@ func TestSearchRepositories(t *testing.T) { func TestTrustedLocation(t *testing.T) { for _, url := range []string{"http://example.com", "https://example.com:7777", "http://docker.io", "http://test.docker.com", "https://fakedocker.com"} { req, _ := http.NewRequest("GET", url, nil) - if trustedLocation(req) == true { - t.Fatalf("'%s' shouldn't be detected as a trusted location", url) - } + assert.False(t, trustedLocation(req)) } for _, url := range []string{"https://docker.io", "https://test.docker.com:80"} { req, _ := http.NewRequest("GET", url, nil) - if trustedLocation(req) == false { - t.Fatalf("'%s' should be detected as a trusted location", url) - } + assert.True(t, trustedLocation(req)) } } diff --git a/runconfig/hostconfig.go b/runconfig/hostconfig.go index 3a90c84498..cfc5383f02 100644 --- a/runconfig/hostconfig.go +++ b/runconfig/hostconfig.go @@ -68,7 +68,7 @@ func validateNetContainerMode(c *container.Config, hc *container.HostConfig) err return ErrConflictContainerNetworkAndMac } - if hc.NetworkMode.IsContainer() && (len(hc.PortBindings) > 0 || hc.PublishAllPorts == true) { + if hc.NetworkMode.IsContainer() && (len(hc.PortBindings) > 0 || hc.PublishAllPorts) { return ErrConflictNetworkPublishPorts } diff --git a/runconfig/hostconfig_test.go b/runconfig/hostconfig_test.go index b461c16f0c..76c3fa2cee 100644 --- a/runconfig/hostconfig_test.go +++ b/runconfig/hostconfig_test.go @@ -195,9 +195,7 @@ func TestDecodeHostConfig(t *testing.T) { t.Fatal(fmt.Errorf("Error parsing %s: %v", f, err)) } - if c.Privileged != false { - t.Fatalf("Expected privileged false, found %v\n", c.Privileged) - } + assert.False(t, c.Privileged) if l := len(c.Binds); l != 1 { t.Fatalf("Expected 1 bind, found %d\n", l)