github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/worker/uniter/jujuc/config-get.go (about)

     1  // Copyright 2012, 2013 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jujuc
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"launchpad.net/gnuflag"
    10  
    11  	"github.com/juju/juju/cmd"
    12  )
    13  
    14  // ConfigGetCommand implements the config-get command.
    15  type ConfigGetCommand struct {
    16  	cmd.CommandBase
    17  	ctx Context
    18  	Key string // The key to show. If empty, show all.
    19  	All bool
    20  	out cmd.Output
    21  }
    22  
    23  func NewConfigGetCommand(ctx Context) cmd.Command {
    24  	return &ConfigGetCommand{ctx: ctx}
    25  }
    26  
    27  func (c *ConfigGetCommand) Info() *cmd.Info {
    28  	doc := `
    29  When no <key> is supplied, all keys with values or defaults are printed. If
    30  --all is set, all known keys are printed; those without defaults or values are
    31  reported as null. <key> and --all are mutually exclusive.
    32  `
    33  	return &cmd.Info{
    34  		Name:    "config-get",
    35  		Args:    "[<key>]",
    36  		Purpose: "print service configuration",
    37  		Doc:     doc,
    38  	}
    39  }
    40  
    41  func (c *ConfigGetCommand) SetFlags(f *gnuflag.FlagSet) {
    42  	c.out.AddFlags(f, "smart", cmd.DefaultFormatters)
    43  	f.BoolVar(&c.All, "a", false, "print all keys")
    44  	f.BoolVar(&c.All, "all", false, "")
    45  }
    46  
    47  func (c *ConfigGetCommand) Init(args []string) error {
    48  	if args == nil {
    49  		return nil
    50  	}
    51  	c.Key = args[0]
    52  	if c.Key != "" && c.All {
    53  		return fmt.Errorf("cannot use argument --all together with key %q", c.Key)
    54  	}
    55  
    56  	return cmd.CheckEmpty(args[1:])
    57  }
    58  
    59  func (c *ConfigGetCommand) Run(ctx *cmd.Context) error {
    60  	settings, err := c.ctx.ConfigSettings()
    61  	if err != nil {
    62  		return err
    63  	}
    64  	var value interface{}
    65  	if c.Key == "" {
    66  		if !c.All {
    67  			for k, v := range settings {
    68  				if v == nil {
    69  					delete(settings, k)
    70  				}
    71  			}
    72  		}
    73  		value = settings
    74  	} else {
    75  		value, _ = settings[c.Key]
    76  	}
    77  	return c.out.Write(ctx, value)
    78  }