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