github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/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 "github.com/juju/errors" 12 "github.com/juju/gnuflag" 13 14 jujucmd "github.com/juju/juju/cmd" 15 ) 16 17 // RelationIdsCommand implements the relation-ids command. 18 type RelationIdsCommand struct { 19 cmd.CommandBase 20 ctx Context 21 Name string 22 out cmd.Output 23 } 24 25 func NewRelationIdsCommand(ctx Context) (cmd.Command, error) { 26 name := "" 27 if r, err := ctx.HookRelation(); err == nil { 28 name = r.Name() 29 } else if cause := errors.Cause(err); !errors.IsNotFound(cause) { 30 return nil, errors.Trace(err) 31 } 32 33 return &RelationIdsCommand{ctx: ctx, Name: name}, nil 34 } 35 36 func (c *RelationIdsCommand) Info() *cmd.Info { 37 args := "<name>" 38 doc := "" 39 if r, err := c.ctx.HookRelation(); err == nil { 40 // There's not much we can do about this error here. 41 args = "[<name>]" 42 doc = fmt.Sprintf("Current default relation name is %q.", r.Name()) 43 } else if !errors.IsNotFound(err) { 44 logger.Errorf("Could not retrieve hook relation: %v", err) 45 } 46 return jujucmd.Info(&cmd.Info{ 47 Name: "relation-ids", 48 Args: args, 49 Purpose: "list all relation ids with the given relation name", 50 Doc: doc, 51 }) 52 } 53 54 func (c *RelationIdsCommand) SetFlags(f *gnuflag.FlagSet) { 55 c.out.AddFlags(f, "smart", cmd.DefaultFormatters) 56 } 57 58 func (c *RelationIdsCommand) Init(args []string) error { 59 if len(args) > 0 { 60 c.Name = args[0] 61 args = args[1:] 62 } else if c.Name == "" { 63 return fmt.Errorf("no relation name specified") 64 } 65 return cmd.CheckEmpty(args) 66 } 67 68 func (c *RelationIdsCommand) Run(ctx *cmd.Context) error { 69 result := []string{} 70 ids, err := c.ctx.RelationIds() 71 if err != nil && !errors.IsNotFound(err) { 72 return errors.Trace(err) 73 } 74 for _, id := range ids { 75 r, err := c.ctx.Relation(id) 76 if err == nil && r.Name() == c.Name { 77 result = append(result, r.FakeId()) 78 } else if err != nil && !errors.IsNotFound(err) { 79 return errors.Trace(err) 80 } 81 } 82 sort.Strings(result) 83 return c.out.Write(ctx, result) 84 }