File: rm.go

package info (click to toggle)
golang-github-containers-buildah 1.19.6%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,020 kB
  • sloc: sh: 1,957; makefile: 199; perl: 173; awk: 12; ansic: 1
file content (92 lines) | stat: -rw-r--r-- 2,358 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main

import (
	"fmt"
	"os"

	buildahcli "github.com/containers/buildah/pkg/cli"
	"github.com/containers/buildah/util"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

type rmResults struct {
	all bool
}

func init() {
	var (
		rmDescription = "\n  Removes one or more working containers, unmounting them if necessary."
		opts          rmResults
	)
	rmCommand := &cobra.Command{
		Use:     "rm",
		Aliases: []string{"delete"},
		Short:   "Remove one or more working containers",
		Long:    rmDescription,
		RunE: func(cmd *cobra.Command, args []string) error {
			return rmCmd(cmd, args, opts)
		},
		Example: `buildah rm containerID
  buildah rm containerID1 containerID2 containerID3
  buildah rm --all`,
	}
	rmCommand.SetUsageTemplate(UsageTemplate())

	flags := rmCommand.Flags()
	flags.SetInterspersed(false)
	flags.BoolVarP(&opts.all, "all", "a", false, "remove all containers")
	rootCmd.AddCommand(rmCommand)
}

func rmCmd(c *cobra.Command, args []string, iopts rmResults) error {
	delContainerErrStr := "error removing container"
	if len(args) == 0 && !iopts.all {
		return errors.Errorf("container ID must be specified")
	}
	if len(args) > 0 && iopts.all {
		return errors.Errorf("when using the --all switch, you may not pass any containers names or IDs")
	}

	if err := buildahcli.VerifyFlagsArgsOrder(args); err != nil {
		return err
	}

	store, err := getStore(c)
	if err != nil {
		return err
	}

	var lastError error
	if iopts.all {
		builders, err := openBuilders(store)
		if err != nil {
			return errors.Wrapf(err, "error reading build containers")
		}

		for _, builder := range builders {
			id := builder.ContainerID
			if err = builder.Delete(); err != nil {
				lastError = util.WriteError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, builder.Container), lastError)
				continue
			}
			fmt.Printf("%s\n", id)
		}
	} else {
		for _, name := range args {
			builder, err := openBuilder(getContext(), store, name)
			if err != nil {
				lastError = util.WriteError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, name), lastError)
				continue
			}
			id := builder.ContainerID
			if err = builder.Delete(); err != nil {
				lastError = util.WriteError(os.Stderr, errors.Wrapf(err, "%s %q", delContainerErrStr, name), lastError)
				continue
			}
			fmt.Printf("%s\n", id)
		}

	}
	return lastError
}