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