github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/worker/uniter/runner/jujuc/leader-get.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jujuc
     5  
     6  import (
     7  	"strings"
     8  
     9  	"github.com/juju/cmd"
    10  	"github.com/juju/errors"
    11  	"github.com/juju/gnuflag"
    12  
    13  	jujucmd "github.com/juju/juju/cmd"
    14  )
    15  
    16  // leaderGetCommand implements the leader-get command.
    17  type leaderGetCommand struct {
    18  	cmd.CommandBase
    19  	ctx Context
    20  	key string
    21  	out cmd.Output
    22  }
    23  
    24  // NewLeaderGetCommand returns a new leaderGetCommand with the given context.
    25  func NewLeaderGetCommand(ctx Context) (cmd.Command, error) {
    26  	return &leaderGetCommand{ctx: ctx}, nil
    27  }
    28  
    29  // Info is part of the cmd.Command interface.
    30  func (c *leaderGetCommand) Info() *cmd.Info {
    31  	doc := `
    32  leader-get prints the value of a leadership setting specified by key. If no key
    33  is given, or if the key is "-", all keys and values will be printed.
    34  `
    35  	return jujucmd.Info(&cmd.Info{
    36  		Name:    "leader-get",
    37  		Args:    "[<key>]",
    38  		Purpose: "print application leadership settings",
    39  		Doc:     doc,
    40  	})
    41  }
    42  
    43  // SetFlags is part of the cmd.Command interface.
    44  func (c *leaderGetCommand) SetFlags(f *gnuflag.FlagSet) {
    45  	c.out.AddFlags(f, "smart", cmd.DefaultFormatters)
    46  }
    47  
    48  // Init is part of the cmd.Command interface.
    49  func (c *leaderGetCommand) Init(args []string) error {
    50  	c.key = ""
    51  	if len(args) == 0 {
    52  		return nil
    53  	}
    54  	key := args[0]
    55  	if key == "-" {
    56  		key = ""
    57  	} else if strings.Contains(key, "=") {
    58  		return errors.Errorf("invalid key %q", key)
    59  	}
    60  	c.key = key
    61  	return cmd.CheckEmpty(args[1:])
    62  }
    63  
    64  // Run is part of the cmd.Command interface.
    65  func (c *leaderGetCommand) Run(ctx *cmd.Context) error {
    66  	settings, err := c.ctx.LeaderSettings()
    67  	if err != nil {
    68  		return errors.Annotatef(err, "cannot read leadership settings")
    69  	}
    70  	if c.key == "" {
    71  		return c.out.Write(ctx, settings)
    72  	}
    73  	if value, ok := settings[c.key]; ok {
    74  		return c.out.Write(ctx, value)
    75  	}
    76  	return c.out.Write(ctx, nil)
    77  }