github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/worker/uniter/jujuc/relation-ids.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  	"sort"
     9  
    10  	"launchpad.net/gnuflag"
    11  
    12  	"github.com/juju/juju/cmd"
    13  )
    14  
    15  // RelationIdsCommand implements the relation-ids command.
    16  type RelationIdsCommand struct {
    17  	cmd.CommandBase
    18  	ctx  Context
    19  	Name string
    20  	out  cmd.Output
    21  }
    22  
    23  func NewRelationIdsCommand(ctx Context) cmd.Command {
    24  	return &RelationIdsCommand{ctx: ctx}
    25  }
    26  
    27  func (c *RelationIdsCommand) Info() *cmd.Info {
    28  	args := "<name>"
    29  	doc := ""
    30  	if r, found := c.ctx.HookRelation(); found {
    31  		args = "[<name>]"
    32  		doc = fmt.Sprintf("Current default relation name is %q.", r.Name())
    33  	}
    34  	return &cmd.Info{
    35  		Name:    "relation-ids",
    36  		Args:    args,
    37  		Purpose: "list all relation ids with the given relation name",
    38  		Doc:     doc,
    39  	}
    40  }
    41  
    42  func (c *RelationIdsCommand) SetFlags(f *gnuflag.FlagSet) {
    43  	c.out.AddFlags(f, "smart", cmd.DefaultFormatters)
    44  }
    45  
    46  func (c *RelationIdsCommand) Init(args []string) error {
    47  	if r, found := c.ctx.HookRelation(); found {
    48  		c.Name = r.Name()
    49  	}
    50  	if len(args) > 0 {
    51  		c.Name = args[0]
    52  		args = args[1:]
    53  	} else if c.Name == "" {
    54  		return fmt.Errorf("no relation name specified")
    55  	}
    56  	return cmd.CheckEmpty(args)
    57  }
    58  
    59  func (c *RelationIdsCommand) Run(ctx *cmd.Context) error {
    60  	result := []string{}
    61  	for _, id := range c.ctx.RelationIds() {
    62  		if r, found := c.ctx.Relation(id); found && r.Name() == c.Name {
    63  			result = append(result, r.FakeId())
    64  		}
    65  	}
    66  	sort.Strings(result)
    67  	return c.out.Write(ctx, result)
    68  }