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