/
poollistformatters.go
63 lines (56 loc) · 1.51 KB
/
poollistformatters.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
package storage
import (
"bytes"
"fmt"
"sort"
"strings"
"text/tabwriter"
"github.com/juju/errors"
)
// formatPoolListTabular returns a tabular summary of pool instances or
// errors out if parameter is not a map of PoolInfo.
func formatPoolListTabular(value interface{}) ([]byte, error) {
pools, ok := value.(map[string]PoolInfo)
if !ok {
return nil, errors.Errorf("expected value of type %T, got %T", pools, value)
}
return formatPoolsTabular(pools)
}
// formatPoolsTabular returns a tabular summary of pool instances.
func formatPoolsTabular(pools map[string]PoolInfo) ([]byte, error) {
var out bytes.Buffer
const (
// To format things into columns.
minwidth = 0
tabwidth = 1
padding = 2
padchar = ' '
flags = 0
)
tw := tabwriter.NewWriter(&out, minwidth, tabwidth, padding, padchar, flags)
print := func(values ...string) {
fmt.Fprintln(tw, strings.Join(values, "\t"))
}
print("NAME", "PROVIDER", "ATTRS")
poolNames := make([]string, 0, len(pools))
for name := range pools {
poolNames = append(poolNames, name)
}
sort.Strings(poolNames)
for _, name := range poolNames {
pool := pools[name]
// order by key for deterministic return
keys := make([]string, 0, len(pool.Attrs))
for key := range pool.Attrs {
keys = append(keys, key)
}
sort.Strings(keys)
attrs := make([]string, len(pool.Attrs))
for i, key := range keys {
attrs[i] = fmt.Sprintf("%v=%v", key, pool.Attrs[key])
}
print(name, pool.Provider, strings.Join(attrs, " "))
}
tw.Flush()
return out.Bytes(), nil
}