table.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. Copyright 2019 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package pretty
  14. // TableCalculator calculates column widths (with optional padding)
  15. // for a table based on the maximum required column width.
  16. type TableCalculator struct {
  17. cellSizesByCol [][]int
  18. Padding int
  19. MaxWidth int
  20. }
  21. // AddRowSizes registers a new row with cells of the given sizes.
  22. func (c *TableCalculator) AddRowSizes(cellSizes ...int) {
  23. if len(cellSizes) > len(c.cellSizesByCol) {
  24. for range cellSizes[len(c.cellSizesByCol):] {
  25. c.cellSizesByCol = append(c.cellSizesByCol, []int(nil))
  26. }
  27. }
  28. for i, size := range cellSizes {
  29. c.cellSizesByCol[i] = append(c.cellSizesByCol[i], size)
  30. }
  31. }
  32. // ColumnWidths calculates the appropriate column sizes given the
  33. // previously registered rows.
  34. func (c *TableCalculator) ColumnWidths() []int {
  35. maxColWidths := make([]int, len(c.cellSizesByCol))
  36. for colInd, cellSizes := range c.cellSizesByCol {
  37. max := 0
  38. for _, cellSize := range cellSizes {
  39. if max < cellSize {
  40. max = cellSize
  41. }
  42. }
  43. maxColWidths[colInd] = max
  44. }
  45. actualMaxWidth := c.MaxWidth - c.Padding
  46. for i, width := range maxColWidths {
  47. if actualMaxWidth > 0 && width > actualMaxWidth {
  48. maxColWidths[i] = actualMaxWidth
  49. }
  50. maxColWidths[i] += c.Padding
  51. }
  52. return maxColWidths
  53. }