github.com/vmware/govmomi@v0.43.0/govc/tags/ls.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 "io" 24 "text/tabwriter" 25 26 "github.com/vmware/govmomi/govc/cli" 27 "github.com/vmware/govmomi/govc/flags" 28 "github.com/vmware/govmomi/vapi/tags" 29 ) 30 31 type ls struct { 32 *flags.ClientFlag 33 *flags.OutputFlag 34 c string 35 } 36 37 func init() { 38 cli.Register("tags.ls", &ls{}) 39 } 40 41 func (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) { 42 cmd.ClientFlag, ctx = flags.NewClientFlag(ctx) 43 cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx) 44 cmd.ClientFlag.Register(ctx, f) 45 cmd.OutputFlag.Register(ctx, f) 46 f.StringVar(&cmd.c, "c", "", "Category name") 47 } 48 49 func (cmd *ls) Process(ctx context.Context) error { 50 if err := cmd.ClientFlag.Process(ctx); err != nil { 51 return err 52 } 53 return nil 54 } 55 56 func (cmd *ls) Description() string { 57 return `List tags. 58 59 Examples: 60 govc tags.ls 61 govc tags.ls -c k8s-zone 62 govc tags.ls -json | jq . 63 govc tags.ls -c k8s-region -json | jq .` 64 } 65 66 type lsResult []tags.Tag 67 68 func (r lsResult) Write(w io.Writer) error { 69 tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0) 70 71 for i := range r { 72 fmt.Fprintf(tw, "%s\t%s\n", r[i].Name, r[i].CategoryID) 73 } 74 75 return tw.Flush() 76 } 77 78 func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error { 79 c, err := cmd.RestClient() 80 if err != nil { 81 return err 82 } 83 84 m := tags.NewManager(c) 85 var res lsResult 86 87 if cmd.c == "" { 88 res, err = m.GetTags(ctx) 89 } else { 90 res, err = m.GetTagsForCategory(ctx, cmd.c) 91 } 92 93 if err != nil { 94 return err 95 } 96 97 categories, err := m.GetCategories(ctx) 98 if err != nil { 99 return err 100 } 101 cats := make(map[string]tags.Category) 102 for _, category := range categories { 103 cats[category.ID] = category 104 } 105 106 for i, tag := range res { 107 res[i].CategoryID = cats[tag.CategoryID].Name 108 } 109 110 return cmd.WriteResult(res) 111 }