diff options
Diffstat (limited to 'cmd/podman')
30 files changed, 118 insertions, 147 deletions
diff --git a/cmd/podman/build.go b/cmd/podman/build.go index fbf85fc97..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) } } @@ -375,7 +376,8 @@ func buildCmd(c *cliconfig.BuildValues) error { }, Target: c.Target, } - return runtime.Build(getContext(), c, options, containerfiles) + _, _, err = runtime.Build(getContext(), c, options, containerfiles) + return err } // useLayers returns false if BUILDAH_LAYERS is set to "0" or "false" diff --git a/cmd/podman/cliconfig/config.go b/cmd/podman/cliconfig/config.go index 0e4315411..b261599e6 100644 --- a/cmd/podman/cliconfig/config.go +++ b/cmd/podman/cliconfig/config.go @@ -163,6 +163,7 @@ type GenerateKubeValues struct { type GenerateSystemdValues struct { PodmanCommand Name bool + New bool Files bool RestartPolicy string StopTimeout int diff --git a/cmd/podman/common.go b/cmd/podman/common.go index 5c117f6b3..9064ec219 100644 --- a/cmd/podman/common.go +++ b/cmd/podman/common.go @@ -308,7 +308,7 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { ) createFlags.String( "image-volume", cliconfig.DefaultImageVolume, - "Tells podman how to handle the builtin image volumes. The options are: 'bind', 'tmpfs', or 'ignore'", + `Tells podman how to handle the builtin image volumes ("bind"|"tmpfs"|"ignore")`, ) createFlags.Bool( "init", false, @@ -431,7 +431,7 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { ) createFlags.String( "pull", "missing", - `Pull image before creating ("always"|"missing"|"never") (default "missing")`, + `Pull image before creating ("always"|"missing"|"never")`, ) createFlags.BoolP( "quiet", "q", false, @@ -447,7 +447,7 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { ) createFlags.String( "restart", "", - "Restart policy to apply when a container exits", + `Restart policy to apply when a container exits ("always"|"no"|"on-failure")`, ) createFlags.Bool( "rm", false, @@ -492,7 +492,7 @@ func getCreateFlags(c *cliconfig.PodmanCommand) { ) createFlags.String( "systemd", "true", - `Run container in systemd mode ("true"|"false"|"always" (default "true")`, + `Run container in systemd mode ("true"|"false"|"always")`, ) createFlags.StringArray( "tmpfs", []string{}, 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/common_test.go b/cmd/podman/common_test.go deleted file mode 100644 index a24173003..000000000 --- a/cmd/podman/common_test.go +++ /dev/null @@ -1,15 +0,0 @@ -package main - -import ( - "os/user" - "testing" -) - -func skipTestIfNotRoot(t *testing.T) { - u, err := user.Current() - if err != nil { - t.Skip("Could not determine user. Running without root may cause tests to fail") - } else if u.Uid != "0" { - t.Skip("tests will fail unless run as root") - } -} diff --git a/cmd/podman/containers_prune.go b/cmd/podman/containers_prune.go index 78c50268c..cd9817e7e 100644 --- a/cmd/podman/containers_prune.go +++ b/cmd/podman/containers_prune.go @@ -40,7 +40,7 @@ func init() { pruneContainersCommand.SetHelpTemplate(HelpTemplate()) pruneContainersCommand.SetUsageTemplate(UsageTemplate()) flags := pruneContainersCommand.Flags() - flags.BoolVarP(&pruneContainersCommand.Force, "force", "f", false, "Force removal of a running container. The default is false") + flags.BoolVarP(&pruneContainersCommand.Force, "force", "f", false, "Skip interactive prompt for container removal") flags.StringArrayVar(&pruneContainersCommand.Filter, "filter", []string{}, "Provide filter values (e.g. 'until=<timestamp>')") } @@ -49,11 +49,11 @@ func pruneContainersCmd(c *cliconfig.PruneContainersValues) error { reader := bufio.NewReader(os.Stdin) fmt.Printf(`WARNING! This will remove all stopped containers. Are you sure you want to continue? [y/N] `) - ans, err := reader.ReadString('\n') + answer, err := reader.ReadString('\n') if err != nil { return errors.Wrapf(err, "error reading input") } - if strings.ToLower(ans)[0] != 'y' { + if strings.ToLower(answer)[0] != 'y' { return nil } } @@ -68,7 +68,7 @@ Are you sure you want to continue? [y/N] `) if c.GlobalIsSet("max-workers") { maxWorkers = c.GlobalFlags.MaxWorks } - ok, failures, err := runtime.Prune(getContext(), maxWorkers, c.Force, c.Filter) + ok, failures, err := runtime.Prune(getContext(), maxWorkers, c.Filter) if err != nil { if errors.Cause(err) == define.ErrNoSuchCtr { if len(c.InputArgs) > 1 { diff --git a/cmd/podman/cp.go b/cmd/podman/cp.go index 1e4491f33..205103381 100644 --- a/cmd/podman/cp.go +++ b/cmd/podman/cp.go @@ -101,18 +101,7 @@ func copyBetweenHostAndContainer(runtime *libpod.Runtime, src string, dest strin } }() - // We can't pause rootless containers. - if pause && rootless.IsRootless() { - state, err := ctr.State() - if err != nil { - return err - } - if state == define.ContainerStateRunning { - return errors.Errorf("cannot copy into running rootless container with pause set - pass --pause=false to force copying") - } - } - - if pause && !rootless.IsRootless() { + if pause { if err := ctr.Pause(); err != nil { // An invalid state error is fine. // The container isn't running or is already paused. @@ -149,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 @@ -183,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/errors_remote.go b/cmd/podman/errors_remote.go index 19df2d2d8..378f9398f 100644 --- a/cmd/podman/errors_remote.go +++ b/cmd/podman/errors_remote.go @@ -25,7 +25,7 @@ func outputError(err error) { } var ne error switch e := err.(type) { - // For some reason golang wont let me list them with commas so listing them all. + // For some reason golang won't let me list them with commas so listing them all. case *iopodman.ImageNotFound: ne = errors.New(e.Reason) case *iopodman.ContainerNotFound: @@ -48,7 +48,7 @@ func outputError(err error) { func setExitCode(err error) int { cause := errors.Cause(err) switch e := cause.(type) { - // For some reason golang wont let me list them with commas so listing them all. + // For some reason golang won't let me list them with commas so listing them all. case *iopodman.ContainerNotFound: return 1 case *iopodman.InvalidState: diff --git a/cmd/podman/generate_systemd.go b/cmd/podman/generate_systemd.go index aa202a68d..a9775f9cb 100644 --- a/cmd/podman/generate_systemd.go +++ b/cmd/podman/generate_systemd.go @@ -45,6 +45,7 @@ func init() { } flags.IntVarP(&containerSystemdCommand.StopTimeout, "timeout", "t", -1, "stop timeout override") flags.StringVar(&containerSystemdCommand.RestartPolicy, "restart-policy", "on-failure", "applicable systemd restart-policy") + flags.BoolVarP(&containerSystemdCommand.New, "new", "", false, "create a new container instead of starting an existing one") } func generateSystemdCmd(c *cliconfig.GenerateSystemdValues) error { 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/images_prune.go b/cmd/podman/images_prune.go index 2b498f83d..8f187cbd7 100644 --- a/cmd/podman/images_prune.go +++ b/cmd/podman/images_prune.go @@ -47,11 +47,11 @@ func pruneImagesCmd(c *cliconfig.PruneImagesValues) error { fmt.Printf(` WARNING! This will remove all dangling images. Are you sure you want to continue? [y/N] `) - ans, err := reader.ReadString('\n') + answer, err := reader.ReadString('\n') if err != nil { return errors.Wrapf(err, "error reading input") } - if strings.ToLower(ans)[0] != 'y' { + if strings.ToLower(answer)[0] != 'y' { return nil } } 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/main_local.go b/cmd/podman/main_local.go index bc46e4652..e5b87754b 100644 --- a/cmd/podman/main_local.go +++ b/cmd/podman/main_local.go @@ -33,7 +33,7 @@ const remote = false func init() { cgroupManager := define.SystemdCgroupsManager - cgroupHelp := "Cgroup manager to use (cgroupfs or systemd)" + cgroupHelp := `Cgroup manager to use ("cgroupfs"|"systemd")` cgroupv2, _ := cgroups.IsCgroup2UnifiedMode() if rootless.IsRootless() && !cgroupv2 { cgroupManager = "" @@ -50,12 +50,12 @@ func init() { if err := rootCmd.PersistentFlags().MarkHidden("default-mounts-file"); err != nil { logrus.Error("unable to mark default-mounts-file flag as hidden") } - rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.EventsBackend, "events-backend", "", "Events backend to use") + rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.EventsBackend, "events-backend", "", `Events backend to use ("file"|"journald"|"none")`) // Override default --help information of `--help` global flag var dummyHelp bool rootCmd.PersistentFlags().BoolVar(&dummyHelp, "help", false, "Help for podman") rootCmd.PersistentFlags().StringSliceVar(&MainGlobalOpts.HooksDir, "hooks-dir", []string{}, "Set the OCI hooks directory path (may be set multiple times)") - rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.LogLevel, "log-level", "error", "Log messages above specified level: debug, info, warn, error, fatal or panic") + rootCmd.PersistentFlags().StringVar(&MainGlobalOpts.LogLevel, "log-level", "error", `Log messages above specified level ("debug"|"info"|"warn"|"error"|"fatal"|"panic")`) rootCmd.PersistentFlags().IntVar(&MainGlobalOpts.MaxWorks, "max-workers", 0, "The maximum number of workers for parallel operations") if err := rootCmd.PersistentFlags().MarkHidden("max-workers"); err != nil { logrus.Error("unable to mark max-workers flag as hidden") 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/remoteclientconfig/configfile_test.go b/cmd/podman/remoteclientconfig/configfile_test.go index 1710ee83f..4ad2c2100 100644 --- a/cmd/podman/remoteclientconfig/configfile_test.go +++ b/cmd/podman/remoteclientconfig/configfile_test.go @@ -92,14 +92,15 @@ func TestReadRemoteConfig(t *testing.T) { {"nouser", args{reader: strings.NewReader(noUser)}, makeNoUserResult(), false}, } for _, tt := range tests { + test := tt t.Run(tt.name, func(t *testing.T) { - got, err := ReadRemoteConfig(tt.args.reader) - if (err != nil) != tt.wantErr { - t.Errorf("ReadRemoteConfig() error = %v, wantErr %v", err, tt.wantErr) + got, err := ReadRemoteConfig(test.args.reader) + if (err != nil) != test.wantErr { + t.Errorf("ReadRemoteConfig() error = %v, wantErr %v", err, test.wantErr) return } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("ReadRemoteConfig() = %v, want %v", got, tt.want) + if !reflect.DeepEqual(got, test.want) { + t.Errorf("ReadRemoteConfig() = %v, want %v", got, test.want) } }) } @@ -150,17 +151,18 @@ func TestRemoteConfig_GetDefault(t *testing.T) { {"single", fields{Connections: none}, nil, true}, } for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { + test := tt + t.Run(test.name, func(t *testing.T) { r := &RemoteConfig{ - Connections: tt.fields.Connections, + Connections: test.fields.Connections, } got, err := r.GetDefault() - if (err != nil) != tt.wantErr { - t.Errorf("RemoteConfig.GetDefault() error = %v, wantErr %v", err, tt.wantErr) + if (err != nil) != test.wantErr { + t.Errorf("RemoteConfig.GetDefault() error = %v, wantErr %v", err, test.wantErr) return } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("RemoteConfig.GetDefault() = %v, want %v", got, tt.want) + if !reflect.DeepEqual(got, test.want) { + t.Errorf("RemoteConfig.GetDefault() = %v, want %v", got, test.want) } }) } @@ -192,17 +194,18 @@ func TestRemoteConfig_GetRemoteConnection(t *testing.T) { {"none", fields{Connections: blank}, args{name: "foobar"}, nil, true}, } for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { + test := tt + t.Run(test.name, func(t *testing.T) { r := &RemoteConfig{ - Connections: tt.fields.Connections, + Connections: test.fields.Connections, } - got, err := r.GetRemoteConnection(tt.args.name) - if (err != nil) != tt.wantErr { - t.Errorf("RemoteConfig.GetRemoteConnection() error = %v, wantErr %v", err, tt.wantErr) + got, err := r.GetRemoteConnection(test.args.name) + if (err != nil) != test.wantErr { + t.Errorf("RemoteConfig.GetRemoteConnection() error = %v, wantErr %v", err, test.wantErr) return } - if !reflect.DeepEqual(got, tt.want) { - t.Errorf("RemoteConfig.GetRemoteConnection() = %v, want %v", got, tt.want) + if !reflect.DeepEqual(got, test.want) { + t.Errorf("RemoteConfig.GetRemoteConnection() = %v, want %v", got, test.want) } }) } diff --git a/cmd/podman/reset.go b/cmd/podman/reset.go index 9d16dc978..203399047 100644 --- a/cmd/podman/reset.go +++ b/cmd/podman/reset.go @@ -52,11 +52,11 @@ WARNING! This will remove: - all images - all build cache Are you sure you want to continue? [y/N] `) - ans, err := reader.ReadString('\n') + answer, err := reader.ReadString('\n') if err != nil { return errors.Wrapf(err, "error reading input") } - if strings.ToLower(ans)[0] != 'y' { + if strings.ToLower(answer)[0] != 'y' { return nil } } 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 2aca53ac9..50a64b01c 100644 --- a/cmd/podman/shared/create.go +++ b/cmd/podman/shared/create.go @@ -448,11 +448,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/intermediate.go b/cmd/podman/shared/intermediate.go index 55826625b..d1f0e602e 100644 --- a/cmd/podman/shared/intermediate.go +++ b/cmd/podman/shared/intermediate.go @@ -8,7 +8,7 @@ import ( /* attention -in this file you will see alot of struct duplication. this was done because people wanted a strongly typed +in this file you will see a lot of struct duplication. this was done because people wanted a strongly typed varlink mechanism. this resulted in us creating this intermediate layer that allows us to take the input from the cli and make an intermediate layer which can be transferred as strongly typed structures over a varlink interface. diff --git a/cmd/podman/shared/intermediate_novarlink.go b/cmd/podman/shared/intermediate_novarlink.go index 26738ce48..c6f011fe0 100644 --- a/cmd/podman/shared/intermediate_novarlink.go +++ b/cmd/podman/shared/intermediate_novarlink.go @@ -6,7 +6,7 @@ package shared /* attention -in this file you will see alot of struct duplication. this was done because people wanted a strongly typed +in this file you will see a lot of struct duplication. this was done because people wanted a strongly typed varlink mechanism. this resulted in us creating this intermediate layer that allows us to take the input from the cli and make an intermediate layer which can be transferred as strongly typed structures over a varlink interface. 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/system_prune.go b/cmd/podman/system_prune.go index 74fdcde99..21b7aa711 100644 --- a/cmd/podman/system_prune.go +++ b/cmd/podman/system_prune.go @@ -63,11 +63,11 @@ WARNING! This will remove: - all dangling images - all build cache Are you sure you want to continue? [y/N] `, volumeString) - ans, err := reader.ReadString('\n') + answer, err := reader.ReadString('\n') if err != nil { return errors.Wrapf(err, "error reading input") } - if strings.ToLower(ans)[0] != 'y' { + if strings.ToLower(answer)[0] != 'y' { return nil } } @@ -92,7 +92,7 @@ Are you sure you want to continue? [y/N] `, volumeString) rmWorkers := shared.Parallelize("rm") fmt.Println("Deleted Containers") - ok, failures, err = runtime.Prune(ctx, rmWorkers, false, []string{}) + ok, failures, err = runtime.Prune(ctx, rmWorkers, []string{}) if err != nil { if lasterr != nil { logrus.Errorf("%q", err) diff --git a/cmd/podman/tree.go b/cmd/podman/tree.go index cb1b3fc9c..69b42639d 100644 --- a/cmd/podman/tree.go +++ b/cmd/podman/tree.go @@ -56,7 +56,7 @@ func treeCmd(c *cliconfig.TreeValues) error { return errors.Wrapf(err, "error creating libpod runtime") } defer runtime.DeferredShutdown(false) - imageInfo, layerInfoMap, img, err := runtime.Tree(c) + imageInfo, layerInfoMap, img, err := runtime.Tree(c.InputArgs[0]) if err != nil { return err } @@ -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/varlink/io.podman.varlink b/cmd/podman/varlink/io.podman.varlink index ac400a467..b993457ca 100644 --- a/cmd/podman/varlink/io.podman.varlink +++ b/cmd/podman/varlink/io.podman.varlink @@ -885,7 +885,7 @@ method UntagImage(name: string, tag: string) -> (image: string) method RemoveImage(name: string, force: bool) -> (image: string) # RemoveImageWithResponse takes the name or ID of an image as well as a boolean that determines if containers using that image -# should be deleted. If the image cannot be found, an [ImageNotFound](#ImageNotFound) error will be returned. The reponse is +# should be deleted. If the image cannot be found, an [ImageNotFound](#ImageNotFound) error will be returned. The response is # in the form of a RemoveImageResponse . method RemoveImageWithResponse(name: string, force: bool) -> (response: RemoveImageResponse) 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 diff --git a/cmd/podman/volume_prune.go b/cmd/podman/volume_prune.go index daea5a4d2..48ed68509 100644 --- a/cmd/podman/volume_prune.go +++ b/cmd/podman/volume_prune.go @@ -74,11 +74,11 @@ func volumePruneCmd(c *cliconfig.VolumePruneValues) error { reader := bufio.NewReader(os.Stdin) fmt.Println("WARNING! This will remove all volumes not used by at least one container.") fmt.Print("Are you sure you want to continue? [y/N] ") - ans, err := reader.ReadString('\n') + answer, err := reader.ReadString('\n') if err != nil { return errors.Wrapf(err, "error reading input") } - if strings.ToLower(ans)[0] != 'y' { + if strings.ToLower(answer)[0] != 'y' { return nil } } |