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