github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/worker/uniter/runner/jujuc/relation-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 "launchpad.net/gnuflag" 11 12 "github.com/juju/juju/apiserver/params" 13 ) 14 15 // RelationGetCommand implements the relation-get command. 16 type RelationGetCommand struct { 17 cmd.CommandBase 18 ctx Context 19 RelationId int 20 Key string 21 UnitName string 22 out cmd.Output 23 } 24 25 func NewRelationGetCommand(ctx Context) cmd.Command { 26 return &RelationGetCommand{ctx: ctx} 27 } 28 29 func (c *RelationGetCommand) Info() *cmd.Info { 30 args := "<key> <unit id>" 31 doc := ` 32 relation-get prints the value of a unit's relation setting, specified by key. 33 If no key is given, or if the key is "-", all keys and values will be printed. 34 ` 35 if name, found := c.ctx.RemoteUnitName(); found { 36 args = "[<key> [<unit id>]]" 37 doc += fmt.Sprintf("Current default unit id is %q.", name) 38 } 39 return &cmd.Info{ 40 Name: "relation-get", 41 Args: args, 42 Purpose: "get relation settings", 43 Doc: doc, 44 } 45 } 46 47 func (c *RelationGetCommand) SetFlags(f *gnuflag.FlagSet) { 48 rV := newRelationIdValue(c.ctx, &c.RelationId) 49 50 c.out.AddFlags(f, "smart", cmd.DefaultFormatters) 51 f.Var(rV, "r", "specify a relation by id") 52 f.Var(rV, "relation", "") 53 } 54 55 func (c *RelationGetCommand) Init(args []string) error { 56 if c.RelationId == -1 { 57 return fmt.Errorf("no relation id specified") 58 } 59 c.Key = "" 60 if len(args) > 0 { 61 if c.Key = args[0]; c.Key == "-" { 62 c.Key = "" 63 } 64 args = args[1:] 65 } 66 if name, found := c.ctx.RemoteUnitName(); found { 67 c.UnitName = name 68 } 69 if len(args) > 0 { 70 c.UnitName = args[0] 71 args = args[1:] 72 } 73 if c.UnitName == "" { 74 return fmt.Errorf("no unit id specified") 75 } 76 return cmd.CheckEmpty(args) 77 } 78 79 func (c *RelationGetCommand) Run(ctx *cmd.Context) error { 80 r, found := c.ctx.Relation(c.RelationId) 81 if !found { 82 return fmt.Errorf("unknown relation id") 83 } 84 var settings params.Settings 85 if c.UnitName == c.ctx.UnitName() { 86 node, err := r.Settings() 87 if err != nil { 88 return err 89 } 90 settings = node.Map() 91 } else { 92 var err error 93 settings, err = r.ReadSettings(c.UnitName) 94 if err != nil { 95 return err 96 } 97 } 98 if c.Key == "" { 99 return c.out.Write(ctx, settings) 100 } 101 if value, ok := settings[c.Key]; ok { 102 return c.out.Write(ctx, value) 103 } 104 return c.out.Write(ctx, nil) 105 }