/
products.go
73 lines (60 loc) 路 1.86 KB
/
products.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
// Copyright (C) 2015 Scaleway. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.md file.
package commands
import (
"fmt"
"sort"
"github.com/dustin/go-humanize"
"github.com/scaleway/scaleway-cli/pkg/api"
)
// ProductsArgs are flags for the `RunProducts` function
type ProductsArgs struct {
Short bool
Products []string
}
// DisplayServerFunc
type displayServerFunc func(CommandContext, *api.ScalewayProductsServers)
// RunProducts is the handler for 'scw products'
func RunProducts(ctx CommandContext, args ProductsArgs) error {
for _, product := range args.Products {
switch product {
case "servers":
products, err := ctx.API.GetProductsServers()
if err != nil {
return fmt.Errorf("Unable to fetch products from the Scaleway API: %v", err)
}
var displayFunc displayServerFunc = DisplayServerFull
if args.Short {
displayFunc = DisplayServerShort
}
displayFunc(ctx, products)
default:
return fmt.Errorf("Unknow product '%v'", product)
}
}
return nil
}
// DisplayServerShort only display the product name
func DisplayServerShort(ctx CommandContext, products *api.ScalewayProductsServers) {
for name := range products.Servers {
fmt.Fprintf(ctx.Stdout, "%v\n", name)
}
}
// DisplayServerFull only display the server product information
func DisplayServerFull(ctx CommandContext, products *api.ScalewayProductsServers) {
fmt.Fprintf(ctx.Stdout, "%-12s %8s %8s %8s %10s\n",
"COMMERCIAL TYPE", "ARCH", "CPUs", "RAM", "BAREMETAL")
names := make([]string, len(products.Servers))
i := 0
for k := range products.Servers {
names[i] = k
i++
}
sort.Strings(names)
for _, name := range names {
offer := products.Servers[name]
fmt.Fprintf(ctx.Stdout, "%-15s %8s %8d %8s %10t\n",
name, offer.Arch, offer.Ncpus, humanize.Bytes(offer.Ram), offer.Baremetal)
}
}