github.com/altoros/juju-vmware@v0.0.0-20150312064031-f19ae857ccca/worker/uniter/runner/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  
     9  	"github.com/juju/cmd"
    10  	"github.com/juju/errors"
    11  	"github.com/juju/utils/keyvalues"
    12  	"launchpad.net/gnuflag"
    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}
    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  	rV := newRelationIdValue(c.ctx, &c.RelationId)
    38  
    39  	f.Var(rV, "r", "specify a relation by id")
    40  	f.Var(rV, "relation", "")
    41  
    42  	f.StringVar(&c.formatFlag, "format", "", "deprecated format flag")
    43  }
    44  
    45  func (c *RelationSetCommand) Init(args []string) error {
    46  	if c.RelationId == -1 {
    47  		return fmt.Errorf("no relation id specified")
    48  	}
    49  	var err error
    50  	c.Settings, err = keyvalues.Parse(args, true)
    51  	return err
    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  	if err != nil {
    64  		return errors.Annotate(err, "cannot read relation settings")
    65  	}
    66  	for k, v := range c.Settings {
    67  		if v != "" {
    68  			settings.Set(k, v)
    69  		} else {
    70  			settings.Delete(k)
    71  		}
    72  	}
    73  	return nil
    74  }