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