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