1# Copyright (C) 2017 Amazon.com, Inc. or its affiliates
2#
3# Author: Ethan Faust <efaust@amazon.com>
4# Author: Andrew Jorgensen <ajorgens@amazon.com>
5#
6# This file is part of cloud-init. See LICENSE file for license information.
7
8
9class SimpleTable(object):
10    """A minimal implementation of PrettyTable
11    for distribution with cloud-init.
12    """
13
14    def __init__(self, fields):
15        self.fields = fields
16        self.rows = []
17
18        # initialize list of 0s the same length
19        # as the number of fields
20        self.column_widths = [0] * len(self.fields)
21        self.update_column_widths(fields)
22
23    def update_column_widths(self, values):
24        for i, value in enumerate(values):
25            self.column_widths[i] = max(
26                len(value),
27                self.column_widths[i])
28
29    def add_row(self, values):
30        if len(values) > len(self.fields):
31            raise TypeError('too many values')
32        values = [str(value) for value in values]
33        self.rows.append(values)
34        self.update_column_widths(values)
35
36    def _hdiv(self):
37        """Returns a horizontal divider for the table."""
38        return '+' + '+'.join(
39            ['-' * (w + 2) for w in self.column_widths]) + '+'
40
41    def _row(self, row):
42        """Returns a formatted row."""
43        return '|' + '|'.join(
44            [col.center(self.column_widths[i] + 2)
45                for i, col in enumerate(row)]) + '|'
46
47    def __str__(self):
48        """Returns a string representation of the table with lines around.
49
50        +-----+-----+
51        | one | two |
52        +-----+-----+
53        |  1  |  2  |
54        |  01 |  10 |
55        +-----+-----+
56        """
57        lines = [self._hdiv(), self._row(self.fields), self._hdiv()]
58        lines += [self._row(r) for r in self.rows] + [self._hdiv()]
59        return '\n'.join(lines)
60
61    def get_string(self):
62        return self.__str__()
63