github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/worker/uniter/runner/jujuc/relation-list.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  
     9  	"github.com/juju/cmd"
    10  	"github.com/juju/errors"
    11  	"github.com/juju/gnuflag"
    12  )
    13  
    14  // RelationListCommand implements the relation-list command.
    15  type RelationListCommand struct {
    16  	cmd.CommandBase
    17  	ctx             Context
    18  	RelationId      int
    19  	relationIdProxy gnuflag.Value
    20  	out             cmd.Output
    21  }
    22  
    23  func NewRelationListCommand(ctx Context) (cmd.Command, error) {
    24  	c := &RelationListCommand{ctx: ctx}
    25  
    26  	rV, err := newRelationIdValue(c.ctx, &c.RelationId)
    27  	if err != nil {
    28  		return nil, errors.Trace(err)
    29  	}
    30  	c.relationIdProxy = rV
    31  
    32  	return c, nil
    33  
    34  }
    35  
    36  func (c *RelationListCommand) Info() *cmd.Info {
    37  	doc := "-r must be specified when not in a relation hook"
    38  	if _, err := c.ctx.HookRelation(); err == nil {
    39  		doc = ""
    40  	}
    41  	return &cmd.Info{
    42  		Name:    "relation-list",
    43  		Purpose: "list relation units",
    44  		Doc:     doc,
    45  	}
    46  }
    47  
    48  func (c *RelationListCommand) SetFlags(f *gnuflag.FlagSet) {
    49  	c.out.AddFlags(f, "smart", cmd.DefaultFormatters)
    50  	f.Var(c.relationIdProxy, "r", "specify a relation by id")
    51  	f.Var(c.relationIdProxy, "relation", "")
    52  }
    53  
    54  func (c *RelationListCommand) Init(args []string) (err error) {
    55  	if c.RelationId == -1 {
    56  		return fmt.Errorf("no relation id specified")
    57  	}
    58  	return cmd.CheckEmpty(args)
    59  }
    60  
    61  func (c *RelationListCommand) Run(ctx *cmd.Context) error {
    62  	r, err := c.ctx.Relation(c.RelationId)
    63  	if err != nil {
    64  		return errors.Trace(err)
    65  	}
    66  	unitNames := r.UnitNames()
    67  	if unitNames == nil {
    68  		unitNames = []string{}
    69  	}
    70  	return c.out.Write(ctx, unitNames)
    71  }