github.com/alex123012/deckhouse-controller-tools@v0.0.0-20230510090815-d594daf1af8c/pkg/genall/help/pretty/table.go (about)

     1  /*
     2  Copyright 2019 The Kubernetes Authors.
     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 pretty
    18  
    19  // TableCalculator calculates column widths (with optional padding)
    20  // for a table based on the maximum required column width.
    21  type TableCalculator struct {
    22  	cellSizesByCol [][]int
    23  
    24  	Padding  int
    25  	MaxWidth int
    26  }
    27  
    28  // AddRowSizes registers a new row with cells of the given sizes.
    29  func (c *TableCalculator) AddRowSizes(cellSizes ...int) {
    30  	if len(cellSizes) > len(c.cellSizesByCol) {
    31  		for range cellSizes[len(c.cellSizesByCol):] {
    32  			c.cellSizesByCol = append(c.cellSizesByCol, []int(nil))
    33  		}
    34  	}
    35  	for i, size := range cellSizes {
    36  		c.cellSizesByCol[i] = append(c.cellSizesByCol[i], size)
    37  	}
    38  }
    39  
    40  // ColumnWidths calculates the appropriate column sizes given the
    41  // previously registered rows.
    42  func (c *TableCalculator) ColumnWidths() []int {
    43  	maxColWidths := make([]int, len(c.cellSizesByCol))
    44  
    45  	for colInd, cellSizes := range c.cellSizesByCol {
    46  		max := 0
    47  		for _, cellSize := range cellSizes {
    48  			if max < cellSize {
    49  				max = cellSize
    50  			}
    51  		}
    52  		maxColWidths[colInd] = max
    53  	}
    54  
    55  	actualMaxWidth := c.MaxWidth - c.Padding
    56  	for i, width := range maxColWidths {
    57  		if actualMaxWidth > 0 && width > actualMaxWidth {
    58  			maxColWidths[i] = actualMaxWidth
    59  		}
    60  		maxColWidths[i] += c.Padding
    61  	}
    62  
    63  	return maxColWidths
    64  }