github.com/vmware/govmomi@v0.51.0/cli/storage/policy/ls.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package policy 6 7 import ( 8 "context" 9 "flag" 10 "fmt" 11 "io" 12 "text/tabwriter" 13 14 "github.com/vmware/govmomi/cli" 15 "github.com/vmware/govmomi/cli/flags" 16 "github.com/vmware/govmomi/pbm" 17 "github.com/vmware/govmomi/pbm/types" 18 ) 19 20 type ls struct { 21 *flags.ClientFlag 22 *flags.OutputFlag 23 24 id bool 25 } 26 27 func init() { 28 cli.Register("storage.policy.ls", &ls{}) 29 } 30 31 func (cmd *ls) Register(ctx context.Context, f *flag.FlagSet) { 32 cmd.ClientFlag, ctx = flags.NewClientFlag(ctx) 33 cmd.ClientFlag.Register(ctx, f) 34 35 cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx) 36 cmd.OutputFlag.Register(ctx, f) 37 38 f.BoolVar(&cmd.id, "i", false, "List policy ID only") 39 } 40 41 func (cmd *ls) Process(ctx context.Context) error { 42 if err := cmd.ClientFlag.Process(ctx); err != nil { 43 return err 44 } 45 if err := cmd.OutputFlag.Process(ctx); err != nil { 46 return err 47 } 48 return nil 49 } 50 51 func (cmd *ls) Usage() string { 52 return "[NAME]" 53 } 54 55 func (cmd *ls) Description() string { 56 return `VM Storage Policy listing. 57 58 Examples: 59 govc storage.policy.ls 60 govc storage.policy.ls "vSAN Default Storage Policy" 61 govc storage.policy.ls -i "vSAN Default Storage Policy"` 62 } 63 64 func ListProfiles(ctx context.Context, c *pbm.Client, name string) ([]types.BasePbmProfile, error) { 65 m, err := c.ProfileMap(ctx) 66 if err != nil { 67 return nil, err 68 } 69 if name == "" { 70 return m.Profile, nil 71 } 72 if p, ok := m.Name[name]; ok { 73 return []types.BasePbmProfile{p}, nil 74 } 75 return nil, fmt.Errorf("profile %q not found", name) 76 } 77 78 type lsResult struct { 79 Profile []types.BasePbmProfile `json:"profile"` 80 cmd *ls 81 } 82 83 func (r *lsResult) Write(w io.Writer) error { 84 tw := tabwriter.NewWriter(r.cmd.Out, 2, 0, 2, ' ', 0) 85 86 for i := range r.Profile { 87 p := r.Profile[i].GetPbmProfile() 88 _, _ = fmt.Fprintf(tw, "%s", p.ProfileId.UniqueId) 89 if !r.cmd.id { 90 _, _ = fmt.Fprintf(tw, "\t%s", p.Name) 91 } 92 _, _ = fmt.Fprintln(tw) 93 } 94 95 return tw.Flush() 96 } 97 98 func (cmd *ls) Run(ctx context.Context, f *flag.FlagSet) error { 99 c, err := cmd.PbmClient() 100 if err != nil { 101 return err 102 } 103 104 profiles, err := ListProfiles(ctx, c, f.Arg(0)) 105 if err != nil { 106 return err 107 } 108 109 return cmd.WriteResult(&lsResult{profiles, cmd}) 110 }