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