github.com/vmware/govmomi@v0.37.1/govc/flags/virtual_app.go (about) 1 /* 2 Copyright (c) 2015 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 "flag" 22 "fmt" 23 "os" 24 25 "github.com/vmware/govmomi/object" 26 ) 27 28 type VirtualAppFlag struct { 29 common 30 31 *DatacenterFlag 32 *SearchFlag 33 34 name string 35 app *object.VirtualApp 36 } 37 38 var virtualAppFlagKey = flagKey("virtualApp") 39 40 func NewVirtualAppFlag(ctx context.Context) (*VirtualAppFlag, context.Context) { 41 if v := ctx.Value(virtualAppFlagKey); v != nil { 42 return v.(*VirtualAppFlag), ctx 43 } 44 45 v := &VirtualAppFlag{} 46 v.DatacenterFlag, ctx = NewDatacenterFlag(ctx) 47 v.SearchFlag, ctx = NewSearchFlag(ctx, SearchVirtualApps) 48 ctx = context.WithValue(ctx, virtualAppFlagKey, v) 49 return v, ctx 50 } 51 52 func (flag *VirtualAppFlag) Register(ctx context.Context, f *flag.FlagSet) { 53 flag.RegisterOnce(func() { 54 flag.DatacenterFlag.Register(ctx, f) 55 flag.SearchFlag.Register(ctx, f) 56 57 env := "GOVC_VAPP" 58 value := os.Getenv(env) 59 usage := fmt.Sprintf("Virtual App [%s]", env) 60 f.StringVar(&flag.name, "vapp", value, usage) 61 }) 62 } 63 64 func (flag *VirtualAppFlag) Process(ctx context.Context) error { 65 return flag.ProcessOnce(func() error { 66 if err := flag.DatacenterFlag.Process(ctx); err != nil { 67 return err 68 } 69 if err := flag.SearchFlag.Process(ctx); err != nil { 70 return err 71 } 72 return nil 73 }) 74 } 75 76 func (flag *VirtualAppFlag) VirtualApp() (*object.VirtualApp, error) { 77 ctx := context.TODO() 78 79 if flag.app != nil { 80 return flag.app, nil 81 } 82 83 // Use search flags if specified. 84 if flag.SearchFlag.IsSet() { 85 app, err := flag.SearchFlag.VirtualApp() 86 if err != nil { 87 return nil, err 88 } 89 90 flag.app = app 91 return flag.app, nil 92 } 93 94 // Never look for a default virtual app. 95 if flag.name == "" { 96 return nil, nil 97 } 98 99 finder, err := flag.Finder() 100 if err != nil { 101 return nil, err 102 } 103 104 flag.app, err = finder.VirtualApp(ctx, flag.name) 105 return flag.app, err 106 }