-
Notifications
You must be signed in to change notification settings - Fork 18
/
zone.go
97 lines (77 loc) · 2.05 KB
/
zone.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package cmd
import (
"fmt"
"sort"
"strings"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
)
const (
zoneHelp = "zone NAME|ID (ch-dk-2|ch-gva-2|at-vie-1|de-fra-1|bg-sof-1|de-muc-1)"
)
// allZones represents the list of known Exoscale zones, in case we need it without performing API lookup.
var allZones = []string{
"at-vie-1",
"bg-sof-1",
"ch-dk-2",
"ch-gva-2",
"de-fra-1",
"de-muc-1",
}
type zoneListItemOutput struct {
ID string `json:"id"`
Name string `json:"name"`
}
type zoneListOutput []zoneListItemOutput
func (o *zoneListOutput) toJSON() { outputJSON(o) }
func (o *zoneListOutput) toText() { outputText(o) }
func (o *zoneListOutput) toTable() { outputTable(o) }
func (o zoneListOutput) Len() int { return len(o) }
func (o zoneListOutput) Swap(x, y int) { o[x], o[y] = o[y], o[x] }
func (o zoneListOutput) Less(x, y int) bool { return o[x].Name < o[y].Name }
func init() {
RootCmd.AddCommand(&cobra.Command{
Use: "zone",
Aliases: []string{"zones"},
Short: "List all available zones",
Long: fmt.Sprintf(`This command lists available Exoscale zones.
Supported output template annotations: %s`,
strings.Join(outputterTemplateAnnotations(&zoneListOutput{}), ", ")),
RunE: func(cmd *cobra.Command, args []string) error {
return output(listZones())
},
})
}
func listZones() (outputter, error) {
zones, err := cs.ListWithContext(gContext, &egoscale.Zone{})
if err != nil {
return nil, err
}
out := zoneListOutput{}
for _, key := range zones {
zone := key.(*egoscale.Zone)
out = append(out, zoneListItemOutput{
ID: zone.ID.String(),
Name: zone.Name,
})
}
sort.Sort(out)
return &out, nil
}
func getZoneByNameOrID(name string) (*egoscale.Zone, error) {
zone := &egoscale.Zone{}
id, err := egoscale.ParseUUID(name)
if err != nil {
zone.Name = name
} else {
zone.ID = id
}
resp, err := cs.GetWithContext(gContext, zone)
if err != nil {
if err == egoscale.ErrNotFound {
return nil, fmt.Errorf("invalid zone %q", name)
}
return nil, err
}
return resp.(*egoscale.Zone), nil
}