blob: 7672eb5446f6b963543d9b823ddb5c2255aacdea [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
npujar16d6d5c2019-10-30 16:45:06 +053024// BuildTable populates input data in tabular format
Don Newton2bdfd3f2019-04-08 17:06:33 -040025func BuildTable(keys []string, rows []map[string]string) (string, error) {
26 var returnString string
27 fieldSizes := make(map[string]int)
28
29 for i := 0; i < len(rows); i++ {
30 for key, value := range rows[i] {
31 currentSize := len(value)
32 if currentSize > fieldSizes[key] {
33 fieldSizes[key] = currentSize
34 }
35
36 }
37 }
38 for i := 0; i < len(keys); i++ {
39 currentSize := len(keys[i])
40 if currentSize > fieldSizes[keys[i]] {
41 fieldSizes[keys[i]] = currentSize
42 }
43 }
44 bottom := "+"
45
46 for i := 0; i < len(rows); i++ {
47 header := "|"
48 line := "|"
49 for j := 0; j < len(keys); j++ {
50 key := keys[j]
51 value := rows[i][key]
52 if i == 0 {
53 pad := 2 + fieldSizes[key] - len(key)
54 field := fmt.Sprintf("%s%s|", strings.Repeat(" ", pad), key)
55 spacer := fmt.Sprintf("%s+", strings.Repeat("-", fieldSizes[key]+2))
56 header = header + field
57 bottom = bottom + spacer
58 }
59 pad := 2 + fieldSizes[key] - len(value)
60 field := fmt.Sprintf("%s%s|", strings.Repeat(" ", pad), value)
61 line = line + field
62
63 }
64 if i == 0 {
65 returnString = bottom + "\n" + header + "\n" + bottom + "\n"
66 }
67
68 returnString = returnString + line + "\n"
69 }
70 returnString = returnString + bottom + "\n"
71
72 return returnString, nil
73
74}