blob: 8ead5fdaa5033dbd25424ce987af52d9a55599cb [file] [log] [blame]
Don Newton2bdfd3f2019-04-08 17:06:33 -04001/*
Kent Hagerman0ab4cb22019-04-24 13:13:35 -04002 * Copyright 2018-present Open Networking Foundation
Don Newton2bdfd3f2019-04-08 17:06:33 -04003
Kent Hagerman0ab4cb22019-04-24 13:13:35 -04004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Don Newton2bdfd3f2019-04-08 17:06:33 -04007
Kent Hagerman0ab4cb22019-04-24 13:13:35 -04008 * http://www.apache.org/licenses/LICENSE-2.0
Don Newton2bdfd3f2019-04-08 17:06:33 -04009
Kent Hagerman0ab4cb22019-04-24 13:13:35 -040010 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Don Newton2bdfd3f2019-04-08 17:06:33 -040016
17package util
18
19import (
20 "fmt"
21 "strings"
22)
23
24func BuildTable(keys []string, rows []map[string]string) (string, error) {
25 var returnString string
26 fieldSizes := make(map[string]int)
27
28 for i := 0; i < len(rows); i++ {
29 for key, value := range rows[i] {
30 currentSize := len(value)
31 if currentSize > fieldSizes[key] {
32 fieldSizes[key] = currentSize
33 }
34
35 }
36 }
37 for i := 0; i < len(keys); i++ {
38 currentSize := len(keys[i])
39 if currentSize > fieldSizes[keys[i]] {
40 fieldSizes[keys[i]] = currentSize
41 }
42 }
43 bottom := "+"
44
45 for i := 0; i < len(rows); i++ {
46 header := "|"
47 line := "|"
48 for j := 0; j < len(keys); j++ {
49 key := keys[j]
50 value := rows[i][key]
51 if i == 0 {
52 pad := 2 + fieldSizes[key] - len(key)
53 field := fmt.Sprintf("%s%s|", strings.Repeat(" ", pad), key)
54 spacer := fmt.Sprintf("%s+", strings.Repeat("-", fieldSizes[key]+2))
55 header = header + field
56 bottom = bottom + spacer
57 }
58 pad := 2 + fieldSizes[key] - len(value)
59 field := fmt.Sprintf("%s%s|", strings.Repeat(" ", pad), value)
60 line = line + field
61
62 }
63 if i == 0 {
64 returnString = bottom + "\n" + header + "\n" + bottom + "\n"
65 }
66
67 returnString = returnString + line + "\n"
68 }
69 returnString = returnString + bottom + "\n"
70
71 return returnString, nil
72
73}