summaryrefslogtreecommitdiffstats
path: root/cli_helpers/tabular_output/delimited_output_adapter.py
blob: 098e528c748c17ca7ef8c4c9287d0ef764491239 (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
# -*- coding: utf-8 -*-
"""A delimited data output adapter (e.g. CSV, TSV)."""

from __future__ import unicode_literals
import contextlib

from cli_helpers.compat import csv, StringIO
from cli_helpers.utils import filter_dict_by_key
from .preprocessors import bytes_to_string, override_missing_value

supported_formats = ('csv', 'csv-tab')
preprocessors = (override_missing_value, bytes_to_string)


class linewriter(object):
    def __init__(self):
        self.reset()

    def reset(self):
        self.line = None

    def write(self, d):
        self.line = d


def adapter(data, headers, table_format='csv', **kwargs):
    """Wrap the formatting inside a function for TabularOutputFormatter."""
    keys = ('dialect', 'delimiter', 'doublequote', 'escapechar',
            'quotechar', 'quoting', 'skipinitialspace', 'strict')
    if table_format == 'csv':
        delimiter = ','
    elif table_format == 'csv-tab':
        delimiter = '\t'
    else:
        raise ValueError('Invalid table_format specified.')

    ckwargs = {'delimiter': delimiter, 'lineterminator': ''}
    ckwargs.update(filter_dict_by_key(kwargs, keys))

    l = linewriter()
    writer = csv.writer(l, **ckwargs)
    writer.writerow(headers)
    yield l.line

    for row in data:
        l.reset()
        writer.writerow(row)
        yield l.line