summaryrefslogtreecommitdiffstats
path: root/lmi/scripts/common/formatter/__init__.py
blob: 3ded2170adc6477ece20a90c132a669366455b08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
# Copyright (c) 2013, Red Hat, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and documentation are
# those of the authors and should not be interpreted as representing official
# policies, either expressed or implied, of the FreeBSD Project.
#
# Authors: Michal Minar <miminar@redhat.com>
#
"""
Subpackage with formatter classes used to render and output results.

Each formatter has a :py:meth:`Formatter.produce_output` method taking one
argument which gets rendered and printed to output stream. Each formatter
expects different argument, please refer to doc string of particular class.
"""

import itertools
import locale
import os
import pywbem

from lmi.scripts.common import errors
from lmi.scripts.common.formatter import command as fcmd

def get_terminal_width():
    """
    Get the number of columns of current terminal if attached to it. It
    defaults to 79 characters.

    :returns: Number of columns of attached terminal.
    :rtype: integer
    """
    try:
        term_cols = int(os.popen('stty size', 'r').read().split()[1])
    except (IOError, OSError, ValueError):
        term_cols = 79  # fallback
    return term_cols

class Formatter(object):
    """
    Base formatter class.

    It produces string representation of given argument and prints it.

    This formatter supports following commands:

        * :py:class:`~.command.NewHostCommand`.

    :param file stream: Output stream.
    :param integer padding: Number of leading spaces to print at each line.
    :param boolean no_headings: If table headings should be omitted.
    """

    def __init__(self, stream, padding=0, no_headings=False):
        if not isinstance(padding, (int, long)):
            raise TypeError("padding must be an integer")
        if padding < 0:
            padding = 0
        self.out = stream
        self.padding = padding
        self.no_headings = no_headings
        #: counter of hosts printed
        self.host_counter = 0
        #: counter of tables produced for current host
        self.table_counter = 0
        #: counter of lines producted for current table
        self.line_counter = 0

    @property
    def encoding(self):
        """
        Try to determine encoding for output terminal.

        :returns: Encoding used to encode unicode strings.
        :rtype: string
        """
        enc = getattr(self.out, 'encoding')
        if not enc:
            enc = locale.getpreferredencoding()
        return enc

    def render_value(self, val):
        """
        Rendering function for single value.

        :param val: Any value to render.
        :returns: Value converted to its string representation.
        :rtype: str
        """
        if isinstance(val, unicode):
            return val.encode(self.encoding)
        if not isinstance(val, str):
            val = str(val)
        return val

    def print_line(self, line, *args, **kwargs):
        """
        Prints single line. Output message is prefixed with ``padding`` spaces,
        formated and printed to output stream.

        :param string line: Message to print, it can contain markers for
            other arguments to include according to ``format_spec`` language.
            Please refer to ``Format Specification Mini-Language`` in python
            documentation.
        :param list args: Positional arguments to ``format()`` function of
            ``line`` argument.
        :param dictionary kwargs: Keyword arguments to ``format()`` function.
        """
        line = ' ' * self.padding + line.format(*args, **kwargs)
        self.out.write(line.encode(self.encoding))
        self.out.write("\n")
        self.line_counter += 1

    def print_host(self, hostname):
        """
        Prints header for new host.

        :param string hostname: Hostname to print.
        """
        if (  self.host_counter > 0
           or self.table_counter > 0
           or self.line_counter > 0):
            self.out.write("\n")
        term_width = get_terminal_width()
        self.out.write("="*term_width + "\n")
        self.out.write("Host: %s\n" % hostname)
        self.out.write("="*term_width + "\n")
        self.host_counter += 1
        self.table_counter = 0
        self.line_counter = 0

    def produce_output(self, data):
        """
        Render and print given data.

        Data can be also instance of
        :py:class:`~.command.FormatterCommand`, see
        documentation of this class for list of
        allowed commands.

        This shall be overridden by subclasses.

        :param data: Any value to print. Subclasses may specify their
            requirements for this argument. It can be also am instance of
            :py:class:`~.command.FormatterCommand`.
        """
        self.print_line(str(data))
        self.line_counter += 1

class ListFormatter(Formatter):
    """
    Base formatter taking care of list of items. It renders input data in a
    form of table with mandatory column names at the beginning followed by
    items, one occupying single line (row).

    This formatter supports following commands:
        * :py:class:`~.command.NewHostCommand`
        * :py:class:`~.command.NewTableCommand`
        * :py:class:`~.command.NewTableHeaderCommand`

    The command must be provided as content of one row. This row is then not
    printed and the command is executed.

    This class should be subclassed to provide nice output.
    """
    def __init__(self, stream, padding=0, no_headings=False):
        super(ListFormatter, self).__init__(stream, padding, no_headings)
        self.column_names = None

    def print_text_row(self, row):
        """
        Print data row without any header.

        :param tuple row: Data to print.
        """
        self.out.write(" "*self.padding + self.render_value(row) + "\n")
        self.line_counter += 1

    def print_row(self, data):
        """
        Print data row. Optionaly print header, if requested.

        :param tuple data: Data to print.
        """
        if self.line_counter == 0 and not self.no_headings:
            self.print_header()
        self.print_text_row(data)

    def print_table_title(self, title):
        """
        Prints title of next tale.

        :param string title: Title to print.
        """
        if self.table_counter > 0 or self.line_counter > 0:
            self.out.write('\n')
        self.out.write("%s:\n" % title)
        self.table_counter += 1
        self.line_counter = 0

    def print_header(self):
        """ Print table header. """
        if self.no_headings:
            return
        if self.column_names:
            self.print_text_row(self.column_names)

    def produce_output(self, rows):
        """
        Prints list of rows.

        There can be a :py:class:`~.command.FormatterCommand` instance instead
        of a row. See documentation of this class for list of allowed commands.

        :param rows:  List of rows to print.
        :type rows: list, generator or :py:class:`.command.FormatterCommand`
        """
        for row in rows:
            if isinstance(row, fcmd.NewHostCommand):
                self.print_host(row.hostname)
            elif isinstance(row, fcmd.NewTableCommand):
                self.print_table_title(row.title)
            elif isinstance(row, fcmd.NewTableHeaderCommand):
                self.column_names = row.columns
            else:
                self.print_row(row)

class TableFormatter(ListFormatter):
    """
    Print nice human-readable table to terminal.

    To print the table nicely aligned, the whole table must be populated first.
    Therefore this formatter stores all rows locally and does not print
    them until the table is complete. Column sizes are computed afterwards
    and the table is printed at once.

    This formatter supports following commands:
        * :py:class:`~.command.NewHostCommand`
        * :py:class:`~.command.NewTableCommand`
        * :py:class:`~.command.NewTableHeaderCommand`

    The command must be provided as content of one row. This row is then not
    printed and the command is executed.
    """
    def __init__(self, stream, padding=0, no_headings=False):
        super(TableFormatter, self).__init__(stream, padding, no_headings)
        self.stash = []

    def print_text_row(self, row, column_size):
        for i in xrange(len(row)):
            size = column_size[i]
            # Convert to unicode to compute correct length of utf-8 strings
            # (e.g. with fancy trees with utf-8 graphics).
            item = unicode(row[i])
            if i < len(row) - 1:
                item = item.ljust(size)
            self.out.write(self.render_value(item))
            self.out.write(" ")
        self.out.write("\n")
        self.line_counter += 1

    def print_stash(self):
        if not self.stash:
            return

        # Compute column sizes
        column_sizes = []
        for i in xrange(len(self.column_names)):
            column_sizes.append(len(self.column_names[i]))
        for row in self.stash:
            for i in xrange(len(row)):
                row_length = len(unicode(row[i]))
                if column_sizes[i] < row_length:
                    column_sizes[i] = row_length

        # print headers
        if not self.no_headings:
            self.print_text_row(self.column_names, column_sizes)
        # print stashed rows
        for row in self.stash:
            self.print_text_row(row, column_sizes)
        self.stash = []

    def print_row(self, data):
        """
        Print data row.

        :param tuple data: Data to print.
        """
        self.stash.append(data)

    def print_host(self, hostname):
        """
        Prints header for new host.

        :param string hostname: Hostname to print.
        """
        self.print_stash()
        super(TableFormatter, self).print_host(hostname)

    def print_table_title(self, title):
        """
        Prints title of next tale.

        :param string title: Title to print.
        """
        self.print_stash()
        if self.table_counter > 0 or self.line_counter > 0:
            self.out.write('\n')
        self.out.write("%s:\n" % title)
        self.table_counter += 1
        self.line_counter = 0

    def produce_output(self, rows):
        """
        Prints list of rows.

        There can be :py:class:`~.command.FormatterCommand` instance instead of
        a row. See documentation of this class for list of allowed commands.

        :param rows: List of rows to print.
        :type rows: list or generator
        """
        super(TableFormatter, self).produce_output(rows)
        self.print_stash()

class CsvFormatter(ListFormatter):
    """
    Renders data in a csv (Comma-separated values) format.

    This formatter supports following commands:
        * :py:class:`~.command.NewHostCommand`
        * :py:class:`~.command.NewTableCommand`
        * :py:class:`~.command.NewTableHeaderCommand`
    """

    def render_value(self, val):
        if isinstance(val, basestring):
            if isinstance(val, unicode):
                val.encode(self.encoding)
            val = '"%s"' % val.replace('"', '""')
        elif val is None:
            val = ''
        else:
            val = str(val)
        return val

    def print_text_row(self, row):
        self.print_line(",".join(self.render_value(v) for v in row))
        self.line_counter += 1

class SingleFormatter(Formatter):
    """
    Meant to render and print attributes of single object. Attributes are
    rendered as a list of assignments of values to variables (attribute names).

    This formatter supports following commands:
        * :py:class:`~.command.NewHostCommand`
    """

    def produce_output(self, data):
        """
        Render and print attributes of single item.

        There can be a :py:class:`~.command.FormatterCommand` instance instead
        of a data. See documentation of this class for list of allowed
        commands.

        :param data: Is either a pair of property names with list of values or
            a dictionary with property names as keys. Using the pair allows to
            order the data the way it should be printing. In the latter case
            the properties will be sorted by the property names.
        :type data: tuple or dict
        """
        if isinstance(data, fcmd.NewHostCommand):
            self.print_host(data.hostname)
            return

        if not isinstance(data, (tuple, dict)):
            raise ValueError("data must be tuple or dict")

        if isinstance(data, tuple):
            if not len(data) == 2:
                raise ValueError(
                    "data must contain: (list of columns, list of rows)")
            dataiter = itertools.izip(data[0], data[1])
        else:
            dataiter = itertools.imap(
                    lambda k: (k, self.render_value(data[k])),
                    sorted(data.keys()))
        for name, value in dataiter:
            self.print_line("{0}={1}", name, value)
            self.line_counter += 1

class ShellFormatter(SingleFormatter):
    """
    Specialization of :py:class:`SingleFormatter` having its output executable
    as a shell script.

    This formatter supports following commands:
        * :py:class:`~.command.NewHostCommand`
    """

    def render_value(self, val):
        if isinstance(val, basestring):
            if isinstance(val, unicode):
                val.encode(self.encoding)
            val = "'%s'" % val.replace("'", "\\'")
        elif val is None:
            val = ''
        else:
            val = str(val)
        return val

class ErrorFormatter(ListFormatter):
    """
    Render error strings for particular host. Supported commands:
        * :py:class:`~.command.NewHostCommand`
    """
    def __init__(self, stream, padding=4):
        super(ErrorFormatter, self).__init__(stream, padding)

    def print_row(self, data):
        if isinstance(data, Exception):
            if isinstance(data, pywbem.CIMError):
                self.print_text_row("%s: %s" % (data.args[1], data.message))
            elif not isinstance(data, errors.LmiFailed):
                self.print_text_row("(%s) %s" % (data.__class__.__name__,
                    str(data)))
            else:
                self.print_text_row(data)
        else:
            self.print_text_row(data)

    def print_host(self, hostname):
        self.out.write("host %s\n" % hostname)
        self.host_counter += 1
        self.table_counter = 0
        self.line_counter = 0

    def produce_output(self, rows):
        for row in rows:
            if isinstance(row, fcmd.NewHostCommand):
                self.print_host(row.hostname)
            elif isinstance(row, fcmd.NewTableCommand):
                self.print_table_title(row.title)
            else:
                self.print_row(row)