From 67165b76753f65b6f58d471f314678ae12a4c722 Mon Sep 17 00:00:00 2001 From: Valentin Rothberg Date: Mon, 13 Jan 2020 13:01:45 +0100 Subject: make lint: enable gocritic `gocritic` is a powerful linter that helps in preventing certain kinds of errors as well as enforcing a coding style. Signed-off-by: Valentin Rothberg --- cmd/podman/build.go | 9 +++++---- cmd/podman/common_libpod.go | 7 ++++--- cmd/podman/cp.go | 16 ++++++++-------- cmd/podman/history.go | 4 ++-- cmd/podman/images.go | 10 ++++------ cmd/podman/main.go | 25 +++++++++---------------- cmd/podman/pod_ps.go | 11 ++++++----- cmd/podman/pod_stats.go | 12 ++++-------- cmd/podman/rmi.go | 2 +- cmd/podman/shared/container.go | 5 +---- cmd/podman/shared/create.go | 7 ++++--- cmd/podman/shared/pod.go | 14 ++++++++------ cmd/podman/stats.go | 11 ++++++----- cmd/podman/tree.go | 4 ++-- cmd/podman/volume_ls.go | 4 ++-- 15 files changed, 66 insertions(+), 75 deletions(-) (limited to 'cmd') diff --git a/cmd/podman/build.go b/cmd/podman/build.go index 08d3edaa3..885f2ac51 100644 --- a/cmd/podman/build.go +++ b/cmd/podman/build.go @@ -116,21 +116,22 @@ func getContainerfiles(files []string) []string { func getNsValues(c *cliconfig.BuildValues) ([]buildah.NamespaceOption, error) { var ret []buildah.NamespaceOption if c.Network != "" { - if c.Network == "host" { + switch { + case c.Network == "host": ret = append(ret, buildah.NamespaceOption{ Name: string(specs.NetworkNamespace), Host: true, }) - } else if c.Network == "container" { + case c.Network == "container": ret = append(ret, buildah.NamespaceOption{ Name: string(specs.NetworkNamespace), }) - } else if c.Network[0] == '/' { + case c.Network[0] == '/': ret = append(ret, buildah.NamespaceOption{ Name: string(specs.NetworkNamespace), Path: c.Network, }) - } else { + default: return nil, fmt.Errorf("unsupported configuration network=%s", c.Network) } } diff --git a/cmd/podman/common_libpod.go b/cmd/podman/common_libpod.go index 5deea15d3..b97ff5986 100644 --- a/cmd/podman/common_libpod.go +++ b/cmd/podman/common_libpod.go @@ -24,7 +24,8 @@ func getAllOrLatestContainers(c *cliconfig.PodmanCommand, runtime *libpod.Runtim var containers []*libpod.Container var lastError error var err error - if c.Bool("all") { + switch { + case c.Bool("all"): if filterState != -1 { var filterFuncs []libpod.ContainerFilter filterFuncs = append(filterFuncs, func(c *libpod.Container) bool { @@ -38,13 +39,13 @@ func getAllOrLatestContainers(c *cliconfig.PodmanCommand, runtime *libpod.Runtim if err != nil { return nil, errors.Wrapf(err, "unable to get %s containers", verb) } - } else if c.Bool("latest") { + case c.Bool("latest"): lastCtr, err := runtime.GetLatestContainer() if err != nil { return nil, errors.Wrapf(err, "unable to get latest container") } containers = append(containers, lastCtr) - } else { + default: args := c.InputArgs for _, i := range args { container, err := runtime.LookupContainer(i) diff --git a/cmd/podman/cp.go b/cmd/podman/cp.go index ea97752a3..205103381 100644 --- a/cmd/podman/cp.go +++ b/cmd/podman/cp.go @@ -138,25 +138,25 @@ func copyBetweenHostAndContainer(runtime *libpod.Runtime, src string, dest strin hostOwner := idtools.IDPair{UID: int(hostUID), GID: int(hostGID)} if isFromHostToCtr { - if isVol, volDestName, volName := isVolumeDestName(destPath, ctr); isVol { + if isVol, volDestName, volName := isVolumeDestName(destPath, ctr); isVol { //nolint(gocritic) path, err := pathWithVolumeMount(ctr, runtime, volDestName, volName, destPath) if err != nil { return errors.Wrapf(err, "error getting destination path from volume %s", volDestName) } destPath = path - } else if isBindMount, mount := isBindMountDestName(destPath, ctr); isBindMount { + } else if isBindMount, mount := isBindMountDestName(destPath, ctr); isBindMount { //nolint(gocritic) path, err := pathWithBindMountSource(mount, destPath) if err != nil { return errors.Wrapf(err, "error getting destination path from bind mount %s", mount.Destination) } destPath = path - } else if filepath.IsAbs(destPath) { + } else if filepath.IsAbs(destPath) { //nolint(gocritic) cleanedPath, err := securejoin.SecureJoin(mountPoint, destPath) if err != nil { return err } destPath = cleanedPath - } else { + } else { //nolint(gocritic) ctrWorkDir, err := securejoin.SecureJoin(mountPoint, ctr.WorkingDir()) if err != nil { return err @@ -172,25 +172,25 @@ func copyBetweenHostAndContainer(runtime *libpod.Runtime, src string, dest strin } } else { destOwner = idtools.IDPair{UID: os.Getuid(), GID: os.Getgid()} - if isVol, volDestName, volName := isVolumeDestName(srcPath, ctr); isVol { + if isVol, volDestName, volName := isVolumeDestName(srcPath, ctr); isVol { //nolint(gocritic) path, err := pathWithVolumeMount(ctr, runtime, volDestName, volName, srcPath) if err != nil { return errors.Wrapf(err, "error getting source path from volume %s", volDestName) } srcPath = path - } else if isBindMount, mount := isBindMountDestName(srcPath, ctr); isBindMount { + } else if isBindMount, mount := isBindMountDestName(srcPath, ctr); isBindMount { //nolint(gocritic) path, err := pathWithBindMountSource(mount, srcPath) if err != nil { return errors.Wrapf(err, "error getting source path from bind mount %s", mount.Destination) } srcPath = path - } else if filepath.IsAbs(srcPath) { + } else if filepath.IsAbs(srcPath) { //nolint(gocritic) cleanedPath, err := securejoin.SecureJoin(mountPoint, srcPath) if err != nil { return err } srcPath = cleanedPath - } else { + } else { //nolint(gocritic) cleanedPath, err := securejoin.SecureJoin(mountPoint, filepath.Join(ctr.WorkingDir(), srcPath)) if err != nil { return err diff --git a/cmd/podman/history.go b/cmd/podman/history.go index a16aac8d8..da6a3f608 100644 --- a/cmd/podman/history.go +++ b/cmd/podman/history.go @@ -115,14 +115,14 @@ func genHistoryFormat(format string, quiet bool) string { } // historyToGeneric makes an empty array of interfaces for output -func historyToGeneric(templParams []historyTemplateParams, JSONParams []*image.History) (genericParams []interface{}) { +func historyToGeneric(templParams []historyTemplateParams, jsonParams []*image.History) (genericParams []interface{}) { if len(templParams) > 0 { for _, v := range templParams { genericParams = append(genericParams, interface{}(v)) } return } - for _, v := range JSONParams { + for _, v := range jsonParams { genericParams = append(genericParams, interface{}(v)) } return diff --git a/cmd/podman/images.go b/cmd/podman/images.go index e42546a55..75cdd3465 100644 --- a/cmd/podman/images.go +++ b/cmd/podman/images.go @@ -209,7 +209,7 @@ func (i imagesOptions) setOutputFormat() string { } // imagesToGeneric creates an empty array of interfaces for output -func imagesToGeneric(templParams []imagesTemplateParams, JSONParams []imagesJSONParams) []interface{} { +func imagesToGeneric(templParams []imagesTemplateParams, jsonParams []imagesJSONParams) []interface{} { genericParams := []interface{}{} if len(templParams) > 0 { for _, v := range templParams { @@ -217,7 +217,7 @@ func imagesToGeneric(templParams []imagesTemplateParams, JSONParams []imagesJSON } return genericParams } - for _, v := range JSONParams { + for _, v := range jsonParams { genericParams = append(genericParams, interface{}(v)) } return genericParams @@ -282,10 +282,8 @@ func getImagesTemplateOutput(ctx context.Context, images []*adapter.ContainerIma if len(tag) == 71 && strings.HasPrefix(tag, "sha256:") { imageDigest = digest.Digest(tag) tag = "" - } else { - if img.Digest() != "" { - imageDigest = img.Digest() - } + } else if img.Digest() != "" { + imageDigest = img.Digest() } params := imagesTemplateParams{ Repository: repo, diff --git a/cmd/podman/main.go b/cmd/podman/main.go index c727eea85..a22b01f24 100644 --- a/cmd/podman/main.go +++ b/cmd/podman/main.go @@ -72,17 +72,13 @@ var mainCommands = []*cobra.Command{ } var rootCmd = &cobra.Command{ - Use: path.Base(os.Args[0]), - Long: "manage pods and images", - RunE: commandRunE(), - PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - return before(cmd, args) - }, - PersistentPostRunE: func(cmd *cobra.Command, args []string) error { - return after(cmd, args) - }, - SilenceUsage: true, - SilenceErrors: true, + Use: path.Base(os.Args[0]), + Long: "manage pods and images", + RunE: commandRunE(), + PersistentPreRunE: before, + PersistentPostRunE: after, + SilenceUsage: true, + SilenceErrors: true, } var MainGlobalOpts cliconfig.MainFlags @@ -160,16 +156,13 @@ func main() { } if err := rootCmd.Execute(); err != nil { outputError(err) - } else { + } else if exitCode == define.ExecErrorCodeGeneric { // The exitCode modified from define.ExecErrorCodeGeneric, // indicates an application // running inside of a container failed, as opposed to the // podman command failed. Must exit with that exit code // otherwise command exited correctly. - if exitCode == define.ExecErrorCodeGeneric { - exitCode = 0 - } - + exitCode = 0 } // Check if /etc/containers/registries.conf exists when running in diff --git a/cmd/podman/pod_ps.go b/cmd/podman/pod_ps.go index bda447c57..d7731e983 100644 --- a/cmd/podman/pod_ps.go +++ b/cmd/podman/pod_ps.go @@ -320,13 +320,14 @@ func generatePodFilterFuncs(filter, filterValue string) (func(pod *adapter.Pod) // generate the template based on conditions given func genPodPsFormat(c *cliconfig.PodPsValues) string { format := "" - if c.Format != "" { + switch { + case c.Format != "": // "\t" from the command line is not being recognized as a tab // replacing the string "\t" to a tab character if the user passes in "\t" format = strings.Replace(c.Format, `\t`, "\t", -1) - } else if c.Quiet { + case c.Quiet: format = formats.IDString - } else { + default: format = "table {{.ID}}\t{{.Name}}\t{{.Status}}\t{{.Created}}" if c.Bool("namespace") { format += "\t{{.Cgroup}}\t{{.Namespaces}}" @@ -341,14 +342,14 @@ func genPodPsFormat(c *cliconfig.PodPsValues) string { return format } -func podPsToGeneric(templParams []podPsTemplateParams, JSONParams []podPsJSONParams) (genericParams []interface{}) { +func podPsToGeneric(templParams []podPsTemplateParams, jsonParams []podPsJSONParams) (genericParams []interface{}) { if len(templParams) > 0 { for _, v := range templParams { genericParams = append(genericParams, interface{}(v)) } return } - for _, v := range JSONParams { + for _, v := range jsonParams { genericParams = append(genericParams, interface{}(v)) } return diff --git a/cmd/podman/pod_stats.go b/cmd/podman/pod_stats.go index 2f1ebd3ac..297603410 100644 --- a/cmd/podman/pod_stats.go +++ b/cmd/podman/pod_stats.go @@ -124,10 +124,8 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { for i := 0; i < t.NumField(); i++ { value := strings.ToUpper(splitCamelCase(t.Field(i).Name)) switch value { - case "CPU": - value = value + " %" - case "MEM": - value = value + " %" + case "CPU", "MEM": + value += " %" case "MEM USAGE": value = "MEM USAGE / LIMIT" } @@ -167,10 +165,8 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error { results := podContainerStatsToPodStatOut(newStats) if len(format) == 0 { outputToStdOut(results) - } else { - if err := printPSFormat(c.Format, results, headerNames); err != nil { - return err - } + } else if err := printPSFormat(c.Format, results, headerNames); err != nil { + return err } } time.Sleep(time.Second) diff --git a/cmd/podman/rmi.go b/cmd/podman/rmi.go index f4ca88ea8..caaa8984d 100644 --- a/cmd/podman/rmi.go +++ b/cmd/podman/rmi.go @@ -65,7 +65,7 @@ func rmiCmd(c *cliconfig.RmiValues) error { return errors.Errorf("when using the --all switch, you may not pass any images names or IDs") } - images := args[:] + images := args removeImage := func(img *adapter.ContainerImage) { response, err := runtime.RemoveImage(ctx, img, c.Force) diff --git a/cmd/podman/shared/container.go b/cmd/podman/shared/container.go index 5f8df2e10..9459247ed 100644 --- a/cmd/podman/shared/container.go +++ b/cmd/podman/shared/container.go @@ -650,10 +650,7 @@ func getNamespaceInfo(path string) (string, error) { // getStrFromSquareBrackets gets the string inside [] from a string. func getStrFromSquareBrackets(cmd string) string { - reg, err := regexp.Compile(`.*\[|\].*`) - if err != nil { - return "" - } + reg := regexp.MustCompile(`.*\[|\].*`) arr := strings.Split(reg.ReplaceAllLiteralString(cmd, ""), ",") return strings.Join(arr, ",") } diff --git a/cmd/podman/shared/create.go b/cmd/podman/shared/create.go index 58cf56eea..05a3f5598 100644 --- a/cmd/podman/shared/create.go +++ b/cmd/podman/shared/create.go @@ -444,11 +444,12 @@ func ParseCreateOpts(ctx context.Context, c *GenericCLIResults, runtime *libpod. // USER user := c.String("user") if user == "" { - if usernsMode.IsKeepID() { + switch { + case usernsMode.IsKeepID(): user = fmt.Sprintf("%d:%d", rootless.GetRootlessUID(), rootless.GetRootlessGID()) - } else if data == nil { + case data == nil: user = "0" - } else { + default: user = data.Config.User } } diff --git a/cmd/podman/shared/pod.go b/cmd/podman/shared/pod.go index ab6d1f144..d8d69c8fc 100644 --- a/cmd/podman/shared/pod.go +++ b/cmd/podman/shared/pod.go @@ -59,18 +59,20 @@ func CreatePodStatusResults(ctrStatuses map[string]define.ContainerStatus) (stri } } - if statuses[PodStateRunning] > 0 { + switch { + case statuses[PodStateRunning] > 0: return PodStateRunning, nil - } else if statuses[PodStatePaused] == ctrNum { + case statuses[PodStatePaused] == ctrNum: return PodStatePaused, nil - } else if statuses[PodStateStopped] == ctrNum { + case statuses[PodStateStopped] == ctrNum: return PodStateExited, nil - } else if statuses[PodStateStopped] > 0 { + case statuses[PodStateStopped] > 0: return PodStateStopped, nil - } else if statuses[PodStateErrored] > 0 { + case statuses[PodStateErrored] > 0: return PodStateErrored, nil + default: + return PodStateCreated, nil } - return PodStateCreated, nil } // GetNamespaceOptions transforms a slice of kernel namespaces diff --git a/cmd/podman/stats.go b/cmd/podman/stats.go index f53e09412..08fddc47a 100644 --- a/cmd/podman/stats.go +++ b/cmd/podman/stats.go @@ -105,9 +105,10 @@ func statsCmd(c *cliconfig.StatsValues) error { var ctrs []*libpod.Container containerFunc := runtime.GetRunningContainers - if len(c.InputArgs) > 0 { + switch { + case len(c.InputArgs) > 0: containerFunc = func() ([]*libpod.Container, error) { return runtime.GetContainersByList(c.InputArgs) } - } else if latest { + case latest: containerFunc = func() ([]*libpod.Container, error) { lastCtr, err := runtime.GetLatestContainer() if err != nil { @@ -115,7 +116,7 @@ func statsCmd(c *cliconfig.StatsValues) error { } return []*libpod.Container{lastCtr}, nil } - } else if all { + case all: containerFunc = runtime.GetAllContainers } @@ -219,14 +220,14 @@ func genStatsFormat(format string) string { } // imagesToGeneric creates an empty array of interfaces for output -func statsToGeneric(templParams []statsOutputParams, JSONParams []statsOutputParams) (genericParams []interface{}) { +func statsToGeneric(templParams []statsOutputParams, jsonParams []statsOutputParams) (genericParams []interface{}) { if len(templParams) > 0 { for _, v := range templParams { genericParams = append(genericParams, interface{}(v)) } return } - for _, v := range JSONParams { + for _, v := range jsonParams { genericParams = append(genericParams, interface{}(v)) } return diff --git a/cmd/podman/tree.go b/cmd/podman/tree.go index 566f96995..69b42639d 100644 --- a/cmd/podman/tree.go +++ b/cmd/podman/tree.go @@ -113,12 +113,12 @@ func printImageChildren(layerMap map[string]*image.LayerInfo, layerID string, pr intend := middleItem if !last { // add continueItem i.e. '|' for next iteration prefix - prefix = prefix + continueItem + prefix += continueItem } else if len(ll.ChildID) > 1 || len(ll.ChildID) == 0 { // The above condition ensure, alignment happens for node, which has more then 1 children. // If node is last in printing hierarchy, it should not be printed as middleItem i.e. ├── intend = lastItem - prefix = prefix + " " + prefix += " " } var tags string diff --git a/cmd/podman/volume_ls.go b/cmd/podman/volume_ls.go index eda5685cf..938124278 100644 --- a/cmd/podman/volume_ls.go +++ b/cmd/podman/volume_ls.go @@ -134,14 +134,14 @@ func genVolLsFormat(c *cliconfig.VolumeLsValues) string { } // Convert output to genericParams for printing -func volLsToGeneric(templParams []volumeLsTemplateParams, JSONParams []volumeLsJSONParams) (genericParams []interface{}) { +func volLsToGeneric(templParams []volumeLsTemplateParams, jsonParams []volumeLsJSONParams) (genericParams []interface{}) { if len(templParams) > 0 { for _, v := range templParams { genericParams = append(genericParams, interface{}(v)) } return } - for _, v := range JSONParams { + for _, v := range jsonParams { genericParams = append(genericParams, interface{}(v)) } return -- cgit v1.2.3-54-g00ecf