github.com/vmware/govmomi@v0.37.2/govc/tags/rm.go (about)

     1  /*
     2  Copyright (c) 2018 VMware, Inc. All Rights Reserved.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  	http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package tags
    18  
    19  import (
    20  	"context"
    21  	"flag"
    22  	"fmt"
    23  
    24  	"github.com/vmware/govmomi/govc/cli"
    25  	"github.com/vmware/govmomi/govc/flags"
    26  	"github.com/vmware/govmomi/vapi/tags"
    27  )
    28  
    29  type rm struct {
    30  	*flags.ClientFlag
    31  
    32  	cat   string
    33  	force bool
    34  }
    35  
    36  func init() {
    37  	cli.Register("tags.rm", &rm{})
    38  }
    39  
    40  func (cmd *rm) Register(ctx context.Context, f *flag.FlagSet) {
    41  	cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
    42  	cmd.ClientFlag.Register(ctx, f)
    43  
    44  	f.StringVar(&cmd.cat, "c", "", "Tag category")
    45  	f.BoolVar(&cmd.force, "f", false, "Delete tag regardless of attached objects")
    46  }
    47  
    48  func (cmd *rm) Usage() string {
    49  	return "NAME"
    50  }
    51  
    52  func (cmd *rm) Description() string {
    53  	return `Delete tag NAME.
    54  
    55  Fails if tag is attached to any object, unless the '-f' flag is provided.
    56  
    57  Examples:
    58    govc tags.rm k8s-zone-us-ca1
    59    govc tags.rm -f -c k8s-zone us-ca2`
    60  }
    61  
    62  func (cmd *rm) Run(ctx context.Context, f *flag.FlagSet) error {
    63  	if f.NArg() != 1 {
    64  		return flag.ErrHelp
    65  	}
    66  
    67  	tagID := f.Arg(0)
    68  
    69  	c, err := cmd.RestClient()
    70  	if err != nil {
    71  		return err
    72  	}
    73  
    74  	m := tags.NewManager(c)
    75  	if !cmd.force {
    76  		objs, err := m.ListAttachedObjects(ctx, tagID)
    77  		if err != nil {
    78  			return err
    79  		}
    80  		if len(objs) > 0 {
    81  			return fmt.Errorf("tag %s has %d attached objects", tagID, len(objs))
    82  		}
    83  	}
    84  	tag, err := m.GetTagForCategory(ctx, tagID, cmd.cat)
    85  	if err != nil {
    86  		return err
    87  	}
    88  	return m.DeleteTag(ctx, tag)
    89  }