-
Notifications
You must be signed in to change notification settings - Fork 491
/
unit-get.go
76 lines (66 loc) · 1.87 KB
/
unit-get.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package jujuc
import (
"fmt"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/gnuflag"
"github.com/juju/juju/apiserver/params"
jujucmd "github.com/juju/juju/cmd"
)
// UnitGetCommand implements the unit-get command.
type UnitGetCommand struct {
cmd.CommandBase
ctx Context
Key string
out cmd.Output
}
func NewUnitGetCommand(ctx Context) (cmd.Command, error) {
return &UnitGetCommand{ctx: ctx}, nil
}
func (c *UnitGetCommand) Info() *cmd.Info {
return jujucmd.Info(&cmd.Info{
Name: "unit-get",
Args: "<setting>",
Purpose: "print public-address or private-address",
})
}
func (c *UnitGetCommand) SetFlags(f *gnuflag.FlagSet) {
c.out.AddFlags(f, "smart", cmd.DefaultFormatters.Formatters())
}
func (c *UnitGetCommand) Init(args []string) error {
if args == nil {
return errors.New("no setting specified")
}
if args[0] != "private-address" && args[0] != "public-address" {
return fmt.Errorf("unknown setting %q", args[0])
}
c.Key = args[0]
return cmd.CheckEmpty(args[1:])
}
func (c *UnitGetCommand) Run(ctx *cmd.Context) error {
var value string
var err error
if c.Key == "private-address" {
var networkInfos map[string]params.NetworkInfoResult
networkInfos, err = c.ctx.NetworkInfo([]string{""}, -1)
if err == nil {
if networkInfos[""].Error != nil {
err = errors.Trace(networkInfos[""].Error)
}
}
// If we haven't found the address the NetworkInfo-way fall back to old, spaceless method
if err != nil || len(networkInfos[""].Info) == 0 || len(networkInfos[""].Info[0].Addresses) == 0 {
value, err = c.ctx.PrivateAddress()
} else {
value = networkInfos[""].Info[0].Addresses[0].Address
}
} else {
value, err = c.ctx.PublicAddress()
}
if err != nil {
return errors.Trace(err)
}
return c.out.Write(ctx, value)
}