github.com/mattyw/juju@v0.0.0-20140610034352-732aecd63861/worker/uniter/jujuc/unit-get.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  	"errors"
     8  	"fmt"
     9  
    10  	"launchpad.net/gnuflag"
    11  
    12  	"github.com/juju/juju/cmd"
    13  )
    14  
    15  // UnitGetCommand implements the unit-get command.
    16  type UnitGetCommand struct {
    17  	cmd.CommandBase
    18  	ctx Context
    19  	Key string
    20  	out cmd.Output
    21  }
    22  
    23  func NewUnitGetCommand(ctx Context) cmd.Command {
    24  	return &UnitGetCommand{ctx: ctx}
    25  }
    26  
    27  func (c *UnitGetCommand) Info() *cmd.Info {
    28  	return &cmd.Info{
    29  		Name:    "unit-get",
    30  		Args:    "<setting>",
    31  		Purpose: "print public-address or private-address",
    32  	}
    33  }
    34  
    35  func (c *UnitGetCommand) SetFlags(f *gnuflag.FlagSet) {
    36  	c.out.AddFlags(f, "smart", cmd.DefaultFormatters)
    37  }
    38  
    39  func (c *UnitGetCommand) Init(args []string) error {
    40  	if args == nil {
    41  		return errors.New("no setting specified")
    42  	}
    43  	if args[0] != "private-address" && args[0] != "public-address" {
    44  		return fmt.Errorf("unknown setting %q", args[0])
    45  	}
    46  	c.Key = args[0]
    47  	return cmd.CheckEmpty(args[1:])
    48  }
    49  
    50  func (c *UnitGetCommand) Run(ctx *cmd.Context) error {
    51  	value, ok := "", false
    52  	if c.Key == "private-address" {
    53  		value, ok = c.ctx.PrivateAddress()
    54  	} else {
    55  		value, ok = c.ctx.PublicAddress()
    56  	}
    57  	if !ok {
    58  		return fmt.Errorf("%s not set", c.Key)
    59  	}
    60  	return c.out.Write(ctx, value)
    61  }