github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/worker/uniter/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 "launchpad.net/gnuflag" 10 11 "launchpad.net/juju-core/cmd" 12 "launchpad.net/juju-core/state/api/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 c.out.AddFlags(f, "smart", cmd.DefaultFormatters) 49 f.Var(newRelationIdValue(c.ctx, &c.RelationId), "r", "specify a relation by id") 50 } 51 52 func (c *RelationGetCommand) Init(args []string) error { 53 if c.RelationId == -1 { 54 return fmt.Errorf("no relation id specified") 55 } 56 c.Key = "" 57 if len(args) > 0 { 58 if c.Key = args[0]; c.Key == "-" { 59 c.Key = "" 60 } 61 args = args[1:] 62 } 63 if name, found := c.ctx.RemoteUnitName(); found { 64 c.UnitName = name 65 } 66 if len(args) > 0 { 67 c.UnitName = args[0] 68 args = args[1:] 69 } 70 if c.UnitName == "" { 71 return fmt.Errorf("no unit id specified") 72 } 73 return cmd.CheckEmpty(args) 74 } 75 76 func (c *RelationGetCommand) Run(ctx *cmd.Context) error { 77 r, found := c.ctx.Relation(c.RelationId) 78 if !found { 79 return fmt.Errorf("unknown relation id") 80 } 81 var settings params.RelationSettings 82 if c.UnitName == c.ctx.UnitName() { 83 node, err := r.Settings() 84 if err != nil { 85 return err 86 } 87 settings = node.Map() 88 } else { 89 var err error 90 settings, err = r.ReadSettings(c.UnitName) 91 if err != nil { 92 return err 93 } 94 } 95 if c.Key == "" { 96 return c.out.Write(ctx, settings) 97 } 98 if value, ok := settings[c.Key]; ok { 99 return c.out.Write(ctx, value) 100 } 101 return c.out.Write(ctx, nil) 102 }