github.com/vmware/govmomi@v0.51.0/cli/flags/library.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 flags 6 7 import ( 8 "context" 9 "fmt" 10 11 "github.com/vmware/govmomi/vapi/library" 12 "github.com/vmware/govmomi/vapi/library/finder" 13 "github.com/vmware/govmomi/vapi/rest" 14 ) 15 16 // errContentLibraryMatch is an error returned when a query returns more than one result. 17 type errContentLibraryMatch struct { 18 // Type is the type of object being queried. 19 Type string 20 21 // Key is the key used to perform the query. 22 Key string 23 24 // Val is the value used to perform the query. 25 Val string 26 27 // Count is the number of objects returned. 28 Count int 29 } 30 31 // Error returns the error string. 32 func (e errContentLibraryMatch) Error() string { 33 kind := e.Type 34 if kind == "" { 35 kind = "library|item" 36 } 37 hint := "" 38 if e.Count > 1 { 39 hint = fmt.Sprintf(" (use %q ID instead of NAME)", kind) 40 } 41 return fmt.Sprintf("%q=%q matches %d items%s", e.Key, e.Val, e.Count, hint) 42 } 43 44 func ContentLibraryResult(ctx context.Context, c *rest.Client, kind string, path string) (finder.FindResult, error) { 45 res, err := finder.NewFinder(library.NewManager(c)).Find(ctx, path) 46 if err != nil { 47 return nil, err 48 } 49 if len(res) != 1 { 50 return nil, errContentLibraryMatch{Type: kind, Key: "path", Val: path, Count: len(res)} 51 } 52 return res[0], nil 53 } 54 55 // ContentLibrary attempts to find a content library with the given path, 56 // asserting 1 match of type library.Library. 57 func ContentLibrary(ctx context.Context, c *rest.Client, path string) (*library.Library, error) { 58 r, err := ContentLibraryResult(ctx, c, "library", path) 59 if err != nil { 60 return nil, err 61 } 62 lib, ok := r.GetResult().(library.Library) 63 if !ok { 64 return nil, fmt.Errorf("%q is a %T", path, r) 65 } 66 return &lib, nil 67 } 68 69 // ContentLibraryItem attempts to find a content library with the given path, 70 // asserting 1 match of type library.Item. 71 func ContentLibraryItem(ctx context.Context, c *rest.Client, path string) (*library.Item, error) { 72 r, err := ContentLibraryResult(ctx, c, "item", path) 73 if err != nil { 74 return nil, err 75 } 76 item, ok := r.GetResult().(library.Item) 77 if !ok { 78 return nil, fmt.Errorf("%q is a %T", path, r) 79 } 80 return &item, nil 81 }