github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/cmd/juju/model/get.go (about)

     1  // Copyright 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package model
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  
    10  	"github.com/juju/cmd"
    11  	"launchpad.net/gnuflag"
    12  
    13  	"github.com/juju/juju/cmd/modelcmd"
    14  )
    15  
    16  func NewGetCommand() cmd.Command {
    17  	return modelcmd.Wrap(&getCommand{})
    18  }
    19  
    20  // getCommand is able to output either the entire environment or
    21  // the requested value in a format of the user's choosing.
    22  type getCommand struct {
    23  	modelcmd.ModelCommandBase
    24  	api GetEnvironmentAPI
    25  	key string
    26  	out cmd.Output
    27  }
    28  
    29  const getModelHelpDoc = `
    30  By default, all configuration (keys and values) for the model are
    31  displayed if a key is not specified.
    32  By default, the model is the current model.
    33  
    34  Examples:
    35  
    36      juju get-model-config default-series
    37      juju get-model-config -m mymodel type
    38  
    39  See also: list-models
    40            set-model-config
    41            unset-model-config
    42  `
    43  
    44  func (c *getCommand) Info() *cmd.Info {
    45  	return &cmd.Info{
    46  		Name:    "get-model-config",
    47  		Args:    "[<model key>]",
    48  		Purpose: "Displays configuration settings for a model.",
    49  		Doc:     strings.TrimSpace(getModelHelpDoc),
    50  	}
    51  }
    52  
    53  func (c *getCommand) SetFlags(f *gnuflag.FlagSet) {
    54  	c.out.AddFlags(f, "smart", cmd.DefaultFormatters)
    55  }
    56  
    57  func (c *getCommand) Init(args []string) (err error) {
    58  	c.key, err = cmd.ZeroOrOneArgs(args)
    59  	return
    60  }
    61  
    62  type GetEnvironmentAPI interface {
    63  	Close() error
    64  	ModelGet() (map[string]interface{}, error)
    65  }
    66  
    67  func (c *getCommand) getAPI() (GetEnvironmentAPI, error) {
    68  	if c.api != nil {
    69  		return c.api, nil
    70  	}
    71  	return c.NewAPIClient()
    72  }
    73  
    74  func (c *getCommand) Run(ctx *cmd.Context) error {
    75  	client, err := c.getAPI()
    76  	if err != nil {
    77  		return err
    78  	}
    79  	defer client.Close()
    80  
    81  	attrs, err := client.ModelGet()
    82  	if err != nil {
    83  		return err
    84  	}
    85  
    86  	if c.key != "" {
    87  		if value, found := attrs[c.key]; found {
    88  			return c.out.Write(ctx, value)
    89  		}
    90  		return fmt.Errorf("key %q not found in %q model.", c.key, attrs["name"])
    91  	}
    92  	// If key is empty, write out the whole lot.
    93  	return c.out.Write(ctx, attrs)
    94  }