github.com/alibaba/sealer@v0.8.6-0.20220430115802-37a2bdaa8173/sealer/cmd/rmi.go (about)

     1  // Copyright © 2021 Alibaba Group Holding Ltd.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cmd
    16  
    17  import (
    18  	"errors"
    19  	"strings"
    20  
    21  	v1 "github.com/alibaba/sealer/types/api/v1"
    22  	"github.com/alibaba/sealer/utils/platform"
    23  
    24  	"github.com/spf13/cobra"
    25  
    26  	"github.com/alibaba/sealer/pkg/image"
    27  	"github.com/alibaba/sealer/pkg/image/utils"
    28  )
    29  
    30  type removeImageFlag struct {
    31  	platform string
    32  }
    33  
    34  var opts removeImageFlag
    35  
    36  // rmiCmd represents the rmi command
    37  var rmiCmd = &cobra.Command{
    38  	Use:     "rmi",
    39  	Short:   "remove local images by name",
    40  	Example: `sealer rmi registry.cn-qingdao.aliyuncs.com/sealer-io/kubernetes:v1.19.8`,
    41  	Args:    cobra.MinimumNArgs(1),
    42  	RunE: func(cmd *cobra.Command, args []string) error {
    43  		return runRemove(args)
    44  	},
    45  	ValidArgsFunction: utils.ImageListFuncForCompletion,
    46  }
    47  
    48  func runRemove(images []string) error {
    49  	imageService, err := image.NewImageService()
    50  	if err != nil {
    51  		return err
    52  	}
    53  	var errs []string
    54  	var targetPlatforms []*v1.Platform
    55  
    56  	if opts.platform != "" {
    57  		tp, err := platform.ParsePlatforms(opts.platform)
    58  		if err != nil {
    59  			return err
    60  		}
    61  		targetPlatforms = tp
    62  	}
    63  
    64  	for _, img := range images {
    65  		if err := imageService.Delete(img, targetPlatforms); err != nil {
    66  			errs = append(errs, err.Error())
    67  		}
    68  	}
    69  	if len(errs) > 0 {
    70  		msg := strings.Join(errs, "\n")
    71  		return errors.New(msg)
    72  	}
    73  
    74  	return nil
    75  }
    76  
    77  func init() {
    78  	opts = removeImageFlag{}
    79  	rootCmd.AddCommand(rmiCmd)
    80  	rmiCmd.Flags().StringVar(&opts.platform, "platform", "", "set cloud image platform")
    81  }