File: rm.go

package info (click to toggle)
golang-github-containers-buildah 1.41.4%2Bds1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,152 kB
  • sloc: sh: 2,569; makefile: 241; perl: 187; asm: 16; awk: 12; ansic: 1
file content (91 lines) | stat: -rw-r--r-- 2,332 bytes parent folder | download | duplicates (2)
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
package main

import (
	"errors"
	"fmt"
	"os"

	buildahcli "github.com/containers/buildah/pkg/cli"
	"github.com/containers/buildah/util"
	"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 := "removing container"
	if len(args) == 0 && !iopts.all {
		return errors.New("container ID must be specified")
	}
	if len(args) > 0 && iopts.all {
		return errors.New("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 fmt.Errorf("reading build containers: %w", err)
		}

		for _, builder := range builders {
			id := builder.ContainerID
			if err = builder.Delete(); err != nil {
				lastError = util.WriteError(os.Stderr, fmt.Errorf("%s %q: %w", delContainerErrStr, builder.Container, err), 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, fmt.Errorf("%s %q: %w", delContainerErrStr, name, err), lastError)
				continue
			}
			id := builder.ContainerID
			if err = builder.Delete(); err != nil {
				lastError = util.WriteError(os.Stderr, fmt.Errorf("%s %q: %w", delContainerErrStr, name, err), lastError)
				continue
			}
			fmt.Printf("%s\n", id)
		}
	}
	return lastError
}