Index: go/src/infra/crimson/cmd/cmdhelper/cmdhelper.go |
diff --git a/go/src/infra/crimson/cmd/cmdhelper/cmdhelper.go b/go/src/infra/crimson/cmd/cmdhelper/cmdhelper.go |
index ddb50ad060b6cce6157583f07f44ae3e1d10e7b4..23e55e91fabd91d861fbd4bda64a34c56fb0c62b 100644 |
--- a/go/src/infra/crimson/cmd/cmdhelper/cmdhelper.go |
+++ b/go/src/infra/crimson/cmd/cmdhelper/cmdhelper.go |
@@ -342,3 +342,44 @@ func PrintIPRange(ipRanges []*crimson.IPRange, format FormatType) { |
fmt.Println(s) |
} |
} |
+ |
+// FormatHostList formats a list of hosts for pretty-printing. |
+func FormatHostList(hostList *crimson.HostList, format FormatType) ([]string, error) { |
+ var formatter Formatter |
+ |
+ switch format { |
+ case jsonFormat: |
+ jsonBytes, err := json.Marshal(hostList.Hosts) |
Vadim Sh.
2016/06/30 23:58:12
nit: consider using https://golang.org/pkg/encodin
pgervais
2016/07/01 01:01:00
Done.
|
+ if err != nil { |
+ return []string{}, err |
+ } |
+ return []string{string(jsonBytes)}, nil |
+ case textFormat: |
+ formatter = &TextFormatter{} |
+ case csvFormat: |
+ formatter = &CSVFormatter{} |
+ } |
+ rows := [][]string{{"mac", "ip", "site", "hostname", "class"}} |
+ for _, host := range hostList.Hosts { |
+ rows = append(rows, []string{ |
+ fmt.Sprintf("%s", host.MacAddr), |
+ fmt.Sprintf("%s", host.Ip), |
+ fmt.Sprintf("%s", host.Site), |
+ fmt.Sprintf("%s", host.Hostname), |
+ fmt.Sprintf("%s", host.BootClass), |
+ }) |
+ } |
+ return formatter.FormatRows(rows), nil |
+} |
+ |
+// PrintHostList pretty-prints a list of hosts. |
+func PrintHostList(hostList *crimson.HostList, format FormatType) { |
+ lines, err := FormatHostList(hostList, format) |
+ if err != nil { |
+ fmt.Fprintf(os.Stderr, "ERROR: %s", err) |
+ return |
+ } |
+ for _, s := range lines { |
+ fmt.Println(s) |
+ } |
+} |