github.com/vmware/govmomi@v0.43.0/govc/env/command.go (about) 1 /* 2 Copyright (c) 2016 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 env 18 19 import ( 20 "context" 21 "flag" 22 "fmt" 23 "io" 24 "strings" 25 26 "github.com/vmware/govmomi/govc/cli" 27 "github.com/vmware/govmomi/govc/flags" 28 ) 29 30 type env struct { 31 *flags.OutputFlag 32 *flags.ClientFlag 33 34 extra bool 35 } 36 37 func init() { 38 cli.Register("env", &env{}) 39 } 40 41 func (cmd *env) Register(ctx context.Context, f *flag.FlagSet) { 42 cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx) 43 cmd.OutputFlag.Register(ctx, f) 44 45 cmd.ClientFlag, ctx = flags.NewClientFlag(ctx) 46 cmd.ClientFlag.Register(ctx, f) 47 48 f.BoolVar(&cmd.extra, "x", false, "Output variables for each GOVC_URL component") 49 } 50 51 func (cmd *env) Process(ctx context.Context) error { 52 if err := cmd.OutputFlag.Process(ctx); err != nil { 53 return err 54 } 55 if err := cmd.ClientFlag.Process(ctx); err != nil { 56 return err 57 } 58 return nil 59 } 60 61 func (cmd *env) Description() string { 62 return `Output the environment variables for this client. 63 64 If credentials are included in the url, they are split into separate variables. 65 Useful as bash scripting helper to parse GOVC_URL.` 66 } 67 68 func (cmd *env) Run(ctx context.Context, f *flag.FlagSet) error { 69 env := envResult(cmd.ClientFlag.Environ(cmd.extra)) 70 71 if f.NArg() > 1 { 72 return flag.ErrHelp 73 } 74 75 // Option to just output the value, example use: 76 // password=$(govc env GOVC_PASSWORD) 77 if f.NArg() == 1 { 78 var output []string 79 80 prefix := fmt.Sprintf("%s=", f.Arg(0)) 81 82 for _, e := range env { 83 if strings.HasPrefix(e, prefix) { 84 output = append(output, e[len(prefix):]) 85 break 86 } 87 } 88 89 return cmd.WriteResult(envResult(output)) 90 } 91 92 return cmd.WriteResult(env) 93 } 94 95 type envResult []string 96 97 func (r envResult) Write(w io.Writer) error { 98 for _, e := range r { 99 fmt.Println(e) 100 } 101 102 return nil 103 }