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