Don Newton | 2bdfd3f | 2019-04-08 17:06:33 -0400 | [diff] [blame] | 1 | /* |
| 2 | * Copyright 2018-present Open Networking Foundation |
| 3 | |
| 4 | * 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 |
| 7 | |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | * 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 | */ |
| 16 | |
| 17 | package util |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "strings" |
| 22 | ) |
| 23 | |
| 24 | func 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 | } |