github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/cmd/juju/environment/get.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package environment
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  
    10  	"github.com/juju/cmd"
    11  	"launchpad.net/gnuflag"
    12  
    13  	"github.com/juju/juju/cmd/envcmd"
    14  )
    15  
    16  // GetCommand is able to output either the entire environment or
    17  // the requested value in a format of the user's choosing.
    18  type GetCommand struct {
    19  	envcmd.EnvCommandBase
    20  	api GetEnvironmentAPI
    21  	key string
    22  	out cmd.Output
    23  }
    24  
    25  const getEnvHelpDoc = `
    26  If no extra args passed on the command line, all configuration keys and values
    27  for the environment are output using the selected formatter.
    28  
    29  A single environment value can be output by adding the environment key name to
    30  the end of the command line.
    31  
    32  Example:
    33    
    34    juju environment get default-series  (returns the default series for the environment)
    35  `
    36  
    37  func (c *GetCommand) Info() *cmd.Info {
    38  	return &cmd.Info{
    39  		Name:    "get",
    40  		Args:    "[<environment key>]",
    41  		Purpose: "view environment values",
    42  		Doc:     strings.TrimSpace(getEnvHelpDoc),
    43  	}
    44  }
    45  
    46  func (c *GetCommand) SetFlags(f *gnuflag.FlagSet) {
    47  	c.out.AddFlags(f, "smart", cmd.DefaultFormatters)
    48  }
    49  
    50  func (c *GetCommand) Init(args []string) (err error) {
    51  	c.key, err = cmd.ZeroOrOneArgs(args)
    52  	return
    53  }
    54  
    55  type GetEnvironmentAPI interface {
    56  	Close() error
    57  	EnvironmentGet() (map[string]interface{}, error)
    58  }
    59  
    60  func (c *GetCommand) getAPI() (GetEnvironmentAPI, error) {
    61  	if c.api != nil {
    62  		return c.api, nil
    63  	}
    64  	return c.NewAPIClient()
    65  }
    66  
    67  func (c *GetCommand) Run(ctx *cmd.Context) error {
    68  	client, err := c.getAPI()
    69  	if err != nil {
    70  		return err
    71  	}
    72  	defer client.Close()
    73  
    74  	attrs, err := client.EnvironmentGet()
    75  	if err != nil {
    76  		return err
    77  	}
    78  
    79  	if c.key != "" {
    80  		if value, found := attrs[c.key]; found {
    81  			return c.out.Write(ctx, value)
    82  		}
    83  		return fmt.Errorf("key %q not found in %q environment.", c.key, attrs["name"])
    84  	}
    85  	// If key is empty, write out the whole lot.
    86  	return c.out.Write(ctx, attrs)
    87  }