From 6c355a7c9393982e648d79701a6c33ea0911a33a Mon Sep 17 00:00:00 2001
From: xingweizheng <xingweizheng@huawei.com>
Date: Sat, 28 Aug 2021 21:55:14 +0800
Subject: [PATCH 13/20] clean code: staticcheck fix of S1020, S1023, SA9003,
 S1002 and some U1000

---
 builder/dockerfile/add_copy_test.go  |  1 -
 builder/dockerfile/builder.go        |  2 +-
 builder/dockerfile/builder_test.go   |  7 ++-----
 builder/dockerfile/container/help.go |  2 +-
 builder/dockerfile/parser/command.go |  4 ++--
 builder/dockerfile/parser/parser.go  | 14 +++++++-------
 builder/dockerfile/parser/util.go    |  1 -
 builder/dockerfile/stage_builder.go  |  2 +-
 cmd/cli/logout_test.go               |  3 +--
 daemon/info.go                       |  4 ++--
 daemon/remove.go                     |  6 +++---
 image/image.go                       | 12 ++++++------
 pkg/logger/logger.go                 |  2 +-
 pkg/manifest/list.go                 |  2 +-
 pkg/opts/opts.go                     |  2 +-
 pkg/stack/stack.go                   |  2 +-
 util/cipher.go                       |  6 +++---
 util/common.go                       |  2 +-
 18 files changed, 34 insertions(+), 40 deletions(-)

diff --git a/builder/dockerfile/add_copy_test.go b/builder/dockerfile/add_copy_test.go
index 05fac1f3..8873872a 100644
--- a/builder/dockerfile/add_copy_test.go
+++ b/builder/dockerfile/add_copy_test.go
@@ -158,7 +158,6 @@ func TestResolveCopySource(t *testing.T) {
 		isAdd      bool
 		rawSources []string
 		dest       string
-		contextDir string
 	}
 	tests := []struct {
 		name       string
diff --git a/builder/dockerfile/builder.go b/builder/dockerfile/builder.go
index cbd1e589..1e1e24dc 100644
--- a/builder/dockerfile/builder.go
+++ b/builder/dockerfile/builder.go
@@ -559,7 +559,7 @@ func (b *Builder) export(imageID string) error {
 }
 
 func (b *Builder) applyTag(imageID string) error {
-	tags := make([]string, 0, 0)
+	tags := make([]string, 0)
 	if b.buildOpts.Tag != "" {
 		tags = append(tags, b.buildOpts.Tag)
 	}
diff --git a/builder/dockerfile/builder_test.go b/builder/dockerfile/builder_test.go
index 3b7513be..60668e1e 100644
--- a/builder/dockerfile/builder_test.go
+++ b/builder/dockerfile/builder_test.go
@@ -21,7 +21,6 @@ import (
 	"os"
 	"path/filepath"
 	"reflect"
-	"regexp"
 	"strings"
 	"testing"
 
@@ -725,8 +724,7 @@ func TestGetFlagsAndArgs(t *testing.T) {
 // FROM alpine@digest@digest <- fail
 func TestResolveImageName(t *testing.T) {
 	type args struct {
-		s   string
-		reg *regexp.Regexp
+		s string
 	}
 	tests := []struct {
 		name    string
@@ -882,8 +880,7 @@ func TestResolveImageName(t *testing.T) {
 // FROM $imageName@${digest}$${digest2} <- fail
 func TestResolveImageNameWithArgs(t *testing.T) {
 	type args struct {
-		s   string
-		reg *regexp.Regexp
+		s string
 	}
 	tests := []struct {
 		name        string
diff --git a/builder/dockerfile/container/help.go b/builder/dockerfile/container/help.go
index 475b479d..c2d5bd87 100644
--- a/builder/dockerfile/container/help.go
+++ b/builder/dockerfile/container/help.go
@@ -69,7 +69,7 @@ func (ref *Reference) createConfigsAndManifests() (docker.Image, docker.Manifest
 }
 
 func (ref *Reference) getContainerLayers() ([]string, error) {
-	layers := make([]string, 0, 0)
+	layers := make([]string, 0)
 	layerID := ref.layerID
 	layer, err := ref.store.Layer(layerID)
 	if err != nil {
diff --git a/builder/dockerfile/parser/command.go b/builder/dockerfile/parser/command.go
index 1d62303d..635159ee 100644
--- a/builder/dockerfile/parser/command.go
+++ b/builder/dockerfile/parser/command.go
@@ -322,7 +322,7 @@ func extractFlags(line *parser.Line, cmd string) (string, error) {
 	flagRegs := cmdFlagRegs[cmd]
 	parts := strings.Fields(line.Raw)
 
-	existFlags := make(map[string]bool, 0)
+	existFlags := make(map[string]bool)
 	var i int
 	for ; i <= len(parts)-1; i++ {
 		if !strings.HasPrefix(parts[i], "--") {
@@ -545,7 +545,7 @@ func parseKeyValue(line *parser.Line) error {
 }
 
 func parseKeyEqualValuePairs(str string) []string {
-	kvPairs := make([]string, 0, 0)
+	kvPairs := make([]string, 0)
 
 	for i := 0; i <= len(str)-1; i++ {
 		word := []byte{}
diff --git a/builder/dockerfile/parser/parser.go b/builder/dockerfile/parser/parser.go
index a21a3f59..650c5e5c 100644
--- a/builder/dockerfile/parser/parser.go
+++ b/builder/dockerfile/parser/parser.go
@@ -109,7 +109,7 @@ func newRowLine(num int, content string) *rowLine {
 
 // preprocess the Dockerfile and get the effective physical line
 func preProcess(r io.Reader) []*rowLine {
-	rowLines := make([]*rowLine, 0, 0)
+	rowLines := make([]*rowLine, 0)
 	scanner := bufio.NewScanner(r)
 	lineNum := 1
 	for scanner.Scan() {
@@ -134,7 +134,7 @@ func format(rows []*rowLine, d *directive) ([]*parser.Line, error) {
 		text := rows[i].content
 		line := &parser.Line{
 			Begin: rows[i].lineNum,
-			Flags: make(map[string]string, 0),
+			Flags: make(map[string]string),
 		}
 
 		var logicLine string
@@ -193,7 +193,7 @@ func constructPages(lines []*parser.Line, onbuild bool) ([]*parser.Page, error)
 
 	var (
 		pageMap     = make(map[string]*parser.Page)
-		pages       = make([]*parser.Page, 0, 0)
+		pages       = make([]*parser.Page, 0)
 		currentPage *parser.Page
 		pageNum     int
 	)
@@ -204,7 +204,7 @@ func constructPages(lines []*parser.Line, onbuild bool) ([]*parser.Page, error)
 		}
 		if onbuild && currentPage == nil {
 			currentPage = &parser.Page{
-				Lines: make([]*parser.Line, 0, 0),
+				Lines: make([]*parser.Line, 0),
 				Begin: line.Begin,
 				End:   line.End,
 			}
@@ -227,7 +227,7 @@ func constructPages(lines []*parser.Line, onbuild bool) ([]*parser.Page, error)
 				Name:  name,
 				Begin: line.Begin,
 				End:   line.End,
-				Lines: make([]*parser.Line, 0, 0),
+				Lines: make([]*parser.Line, 0),
 			}
 			// page name comes from the last cell from "FROM {image} AS {name}
 			// or named it with the index of stage in this dockerfile
@@ -266,7 +266,7 @@ func constructPages(lines []*parser.Line, onbuild bool) ([]*parser.Page, error)
 // truncHeadingArgs Handle those ARGs before first FROM in the file
 // returns the truncated lines and converted heading args
 func truncHeadingArgs(lines *[]*parser.Line, onbuild bool) ([]string, error) {
-	args := make([]string, 0, 0)
+	args := make([]string, 0)
 	if onbuild {
 		return args, nil
 	}
@@ -295,7 +295,7 @@ const ignoreFile = ".dockerignore"
 // ParseIgnore parses the .dockerignore file in the provide dir, which
 // must be the context directory
 func (df *dockerfile) ParseIgnore(dir string) ([]string, error) {
-	var ignores = make([]string, 0, 0)
+	var ignores = make([]string, 0)
 
 	fullPath := path.Join(dir, ignoreFile)
 	if _, err := os.Stat(fullPath); err != nil {
diff --git a/builder/dockerfile/parser/util.go b/builder/dockerfile/parser/util.go
index bac13fbd..b8867f7f 100644
--- a/builder/dockerfile/parser/util.go
+++ b/builder/dockerfile/parser/util.go
@@ -136,7 +136,6 @@ func (r *resolver) noDollar() {
 	// not "\$", this must be hyphen between args, such as '/' in "hub/image" or '_' in 'module_arch'
 	r.resolved += string(r.origin[r.idx])
 	r.idx++
-	return
 }
 
 func (r *resolver) noBrace() error {
diff --git a/builder/dockerfile/stage_builder.go b/builder/dockerfile/stage_builder.go
index 23f488cb..f01bad54 100644
--- a/builder/dockerfile/stage_builder.go
+++ b/builder/dockerfile/stage_builder.go
@@ -330,7 +330,7 @@ func (s *stageBuilder) updateStageBuilder() error {
 		onbuildData = append(onbuildData, []byte(fmt.Sprintf("%s\n", item))...)
 	}
 	// OnBuild is handled, clean it here so that we can add new ONBUILDs on cmd builder if needed
-	s.docker.Config.OnBuild = make([]string, 0, 0)
+	s.docker.Config.OnBuild = make([]string, 0)
 
 	p, err := parser.NewParser(parser.DefaultParser)
 	if err != nil {
diff --git a/cmd/cli/logout_test.go b/cmd/cli/logout_test.go
index f5f09057..1328c2a1 100644
--- a/cmd/cli/logout_test.go
+++ b/cmd/cli/logout_test.go
@@ -157,9 +157,8 @@ func TestNewLogoutCmd(t *testing.T) {
 			cmd.SetArgs(strings.Split(tt.args, " "))
 			err := cmd.Execute()
 			if err != nil {
-
+				assert.ErrorContains(t, err, tt.errString)
 			}
-			assert.ErrorContains(t, err, tt.errString)
 		})
 	}
 }
diff --git a/daemon/info.go b/daemon/info.go
index 8462be1b..cfc658c1 100644
--- a/daemon/info.go
+++ b/daemon/info.go
@@ -108,8 +108,8 @@ func (b *Backend) Info(ctx context.Context, req *pb.InfoRequest) (*pb.InfoRespon
 }
 
 func getRegistryInfo() ([]string, []string, []string, error) {
-	registriesInsecure := make([]string, 0, 0)
-	registriesBlock := make([]string, 0, 0)
+	registriesInsecure := make([]string, 0)
+	registriesBlock := make([]string, 0)
 	systemContext := image.GetSystemContext()
 
 	registriesSearch, err := sysregistriesv2.UnqualifiedSearchRegistries(systemContext)
diff --git a/daemon/remove.go b/daemon/remove.go
index 89e68cfc..4d90bf53 100644
--- a/daemon/remove.go
+++ b/daemon/remove.go
@@ -73,7 +73,7 @@ func (b *Backend) Remove(req *pb.RemoveRequest, stream pb.Control_RemoveServer)
 				continue
 			}
 
-			if removed == true {
+			if removed {
 				imageString := fmt.Sprintf("Untagged image: %v", imageID)
 				logrus.Debug(imageString)
 				if err = stream.Send(&pb.RemoveResponse{LayerMessage: imageString}); err != nil {
@@ -118,7 +118,7 @@ func (b *Backend) Remove(req *pb.RemoveRequest, stream pb.Control_RemoveServer)
 }
 
 func untagImage(imageID string, store storage.Store, image *storage.Image) (bool, error) {
-	newNames := make([]string, 0, 0)
+	newNames := make([]string, 0)
 	removed := false
 	for _, imgName := range image.Names {
 		if imgName == imageID {
@@ -128,7 +128,7 @@ func untagImage(imageID string, store storage.Store, image *storage.Image) (bool
 		newNames = append(newNames, imgName)
 	}
 
-	if removed == true {
+	if removed {
 		if err := store.SetNames(image.ID, newNames); err != nil {
 			return false, errors.Wrapf(err, "remove name %v from image %v error", imageID, image.ID)
 		}
diff --git a/image/image.go b/image/image.go
index e06d2530..1f3944d1 100644
--- a/image/image.go
+++ b/image/image.go
@@ -287,19 +287,19 @@ func createScratchV2Image() *docker.Image {
 			ContainerConfig: docker.Config{},
 			Config: &docker.Config{
 				ExposedPorts: make(docker.PortSet),
-				Env:          make([]string, 0, 0),
-				Cmd:          make([]string, 0, 0),
+				Env:          make([]string, 0),
+				Cmd:          make([]string, 0),
 				Healthcheck:  nil,
 				Volumes:      make(map[string]struct{}),
-				Entrypoint:   make([]string, 0, 0),
-				OnBuild:      make([]string, 0, 0),
+				Entrypoint:   make([]string, 0),
+				OnBuild:      make([]string, 0),
 				Labels:       make(map[string]string),
 				StopTimeout:  nil,
-				Shell:        make([]string, 0, 0),
+				Shell:        make([]string, 0),
 			},
 		},
 		RootFS:  &docker.RootFS{},
-		History: make([]docker.History, 0, 0),
+		History: make([]docker.History, 0),
 	}
 }
 
diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go
index 2e4dbdd1..1d9a61df 100644
--- a/pkg/logger/logger.go
+++ b/pkg/logger/logger.go
@@ -45,7 +45,7 @@ type Logger struct {
 // NewRunTimer return an instance of RunTimer
 func NewRunTimer() *RunTimer {
 	return &RunTimer{
-		commands: make([]string, 0, 0),
+		commands: make([]string, 0),
 		cmdMap:   make(map[string]time.Duration),
 	}
 }
diff --git a/pkg/manifest/list.go b/pkg/manifest/list.go
index bc6037fc..10907e1d 100644
--- a/pkg/manifest/list.go
+++ b/pkg/manifest/list.go
@@ -53,7 +53,7 @@ func NewManifestList() *List {
 			SchemaVersion: container.SchemaVersion,
 			MediaType:     manifest.DockerV2ListMediaType,
 		},
-		instances: make(map[digest.Digest]string, 0),
+		instances: make(map[digest.Digest]string),
 	}
 }
 
diff --git a/pkg/opts/opts.go b/pkg/opts/opts.go
index 4664d50d..8fb3b308 100644
--- a/pkg/opts/opts.go
+++ b/pkg/opts/opts.go
@@ -61,7 +61,7 @@ func (opts *ListOpts) Type() string {
 
 // NewListOpts creates a new ListOpts
 func NewListOpts(validator validatorFunc) ListOpts {
-	values := make(map[string]string, 0)
+	values := make(map[string]string)
 	return ListOpts{
 		Values:    values,
 		validator: validator,
diff --git a/pkg/stack/stack.go b/pkg/stack/stack.go
index b2100ce6..8343b6b0 100644
--- a/pkg/stack/stack.go
+++ b/pkg/stack/stack.go
@@ -64,7 +64,7 @@ func dumpStack(path string) {
 	)
 
 	for {
-		stackBuf = make([]byte, bufSize, bufSize)
+		stackBuf = make([]byte, bufSize)
 		stackSize = runtime.Stack(stackBuf, true)
 		// if these two sizes equal, which means the allocated buf is not large enough to carry all
 		// stacks back, so enlarge the buf and try again
diff --git a/util/cipher.go b/util/cipher.go
index 8e62e76b..b2aea2a9 100644
--- a/util/cipher.go
+++ b/util/cipher.go
@@ -61,7 +61,7 @@ func GenerateCryptoKey(s int) ([]byte, error) {
 	} else {
 		size = aesKeyLenLowerBound
 	}
-	key := make([]byte, size, size)
+	key := make([]byte, size)
 	if _, err := io.ReadFull(rand.Reader, key); err != nil {
 		return nil, errGenCryptoKey
 	}
@@ -105,7 +105,7 @@ func EncryptAES(data string, aeskey string) (string, error) {
 		return "", errors.Errorf("generate rand data for iv failed: %v", err)
 	}
 	mode := cipher.NewCFBEncrypter(block, iv)
-	encryptData := make([]byte, len(plainText), len(plainText))
+	encryptData := make([]byte, len(plainText))
 	mode.XORKeyStream(encryptData, plainText)
 	encryptData = append(iv, encryptData...)
 
@@ -134,7 +134,7 @@ func DecryptAES(data string, aeskey string) (string, error) {
 	}
 
 	decrypter := cipher.NewCFBDecrypter(block, cipherText[:block.BlockSize()])
-	decryptData := make([]byte, len(cipherText)-block.BlockSize(), len(cipherText)-block.BlockSize())
+	decryptData := make([]byte, len(cipherText)-block.BlockSize())
 	decrypter.XORKeyStream(decryptData, cipherText[block.BlockSize():])
 
 	return string(decryptData), nil
diff --git a/util/common.go b/util/common.go
index d0cd9d06..00b1b941 100644
--- a/util/common.go
+++ b/util/common.go
@@ -44,7 +44,7 @@ func CopyMapStringString(m map[string]string) map[string]string {
 
 // CopyStrings copies all strings in a slice to a new slice
 func CopyStrings(str []string) []string {
-	result := make([]string, len(str), len(str))
+	result := make([]string, len(str))
 	copy(result, str)
 	return result
 }
-- 
2.31.1

