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