spiegel_podman/cmd/podman/containers/prune.go
Paul Holzinger 8452b768ec Fix problems reported by staticcheck
`staticcheck` is a golang code analysis tool. https://staticcheck.io/

This commit fixes a lot of problems found in our code. Common problems are:
- unnecessary use of fmt.Sprintf
- duplicated imports with different names
- unnecessary check that a key exists before a delete call

There are still a lot of reported problems in the test files but I have
not looked at those.

Signed-off-by: Paul Holzinger <paul.holzinger@web.de>
2021-01-12 16:11:09 +01:00

82 lines
2.3 KiB
Go

package containers
import (
"bufio"
"context"
"fmt"
"net/url"
"os"
"strings"
"github.com/containers/common/pkg/completion"
"github.com/containers/podman/v2/cmd/podman/registry"
"github.com/containers/podman/v2/cmd/podman/utils"
"github.com/containers/podman/v2/cmd/podman/validate"
"github.com/containers/podman/v2/pkg/domain/entities"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var (
pruneDescription = `podman container prune
Removes all non running containers`
pruneCommand = &cobra.Command{
Use: "prune [options]",
Short: "Remove all non running containers",
Long: pruneDescription,
RunE: prune,
ValidArgsFunction: completion.AutocompleteNone,
Example: `podman container prune`,
Args: validate.NoArgs,
}
force bool
filter = []string{}
)
func init() {
registry.Commands = append(registry.Commands, registry.CliCommand{
Mode: []entities.EngineMode{entities.ABIMode, entities.TunnelMode},
Command: pruneCommand,
Parent: containerCmd,
})
flags := pruneCommand.Flags()
flags.BoolVarP(&force, "force", "f", false, "Do not prompt for confirmation. The default is false")
filterFlagName := "filter"
flags.StringArrayVar(&filter, filterFlagName, []string{}, "Provide filter values (e.g. 'label=<key>=<value>')")
_ = pruneCommand.RegisterFlagCompletionFunc(filterFlagName, completion.AutocompleteNone)
}
func prune(cmd *cobra.Command, args []string) error {
var (
pruneOptions = entities.ContainerPruneOptions{}
)
if !force {
reader := bufio.NewReader(os.Stdin)
fmt.Println("WARNING! This will remove all non running containers.")
fmt.Print("Are you sure you want to continue? [y/N] ")
answer, err := reader.ReadString('\n')
if err != nil {
return err
}
if strings.ToLower(answer)[0] != 'y' {
return nil
}
}
// TODO Remove once filter refactor is finished and url.Values done.
for _, f := range filter {
t := strings.SplitN(f, "=", 2)
pruneOptions.Filters = make(url.Values)
if len(t) < 2 {
return errors.Errorf("filter input must be in the form of filter=value: %s is invalid", f)
}
pruneOptions.Filters.Add(t[0], t[1])
}
responses, err := registry.ContainerEngine().ContainerPrune(context.Background(), pruneOptions)
if err != nil {
return err
}
return utils.PrintContainerPruneResults(responses, false)
}