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