github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/worker/uniter/jujuc/relation-set.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 "strings" 9 10 "launchpad.net/gnuflag" 11 12 "github.com/juju/juju/cmd" 13 ) 14 15 // RelationSetCommand implements the relation-set command. 16 type RelationSetCommand struct { 17 cmd.CommandBase 18 ctx Context 19 RelationId int 20 Settings map[string]string 21 formatFlag string // deprecated 22 } 23 24 func NewRelationSetCommand(ctx Context) cmd.Command { 25 return &RelationSetCommand{ctx: ctx, Settings: map[string]string{}} 26 } 27 28 func (c *RelationSetCommand) Info() *cmd.Info { 29 return &cmd.Info{ 30 Name: "relation-set", 31 Args: "key=value [key=value ...]", 32 Purpose: "set relation settings", 33 } 34 } 35 36 func (c *RelationSetCommand) SetFlags(f *gnuflag.FlagSet) { 37 f.Var(newRelationIdValue(c.ctx, &c.RelationId), "r", "specify a relation by id") 38 f.StringVar(&c.formatFlag, "format", "", "deprecated format flag") 39 } 40 41 func (c *RelationSetCommand) Init(args []string) error { 42 if c.RelationId == -1 { 43 return fmt.Errorf("no relation id specified") 44 } 45 for _, kv := range args { 46 parts := strings.SplitN(kv, "=", 2) 47 if len(parts) != 2 || len(parts[0]) == 0 { 48 return fmt.Errorf(`expected "key=value", got %q`, kv) 49 } 50 c.Settings[parts[0]] = parts[1] 51 } 52 return nil 53 } 54 55 func (c *RelationSetCommand) Run(ctx *cmd.Context) (err error) { 56 if c.formatFlag != "" { 57 fmt.Fprintf(ctx.Stderr, "--format flag deprecated for command %q", c.Info().Name) 58 } 59 r, found := c.ctx.Relation(c.RelationId) 60 if !found { 61 return fmt.Errorf("unknown relation id") 62 } 63 settings, err := r.Settings() 64 for k, v := range c.Settings { 65 if v != "" { 66 settings.Set(k, v) 67 } else { 68 settings.Delete(k) 69 } 70 } 71 return nil 72 }