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