46a7bc58f6426a5dc5e78799ab71ca66babcb2e9
[sdc/sdc-distribution-client.git] /
1 #  Licensed under the Apache License, Version 2.0 (the "License"); you may
2 #  not use this file except in compliance with the License. You may obtain
3 #  a copy of the License at
4 #
5 #       http://www.apache.org/licenses/LICENSE-2.0
6 #
7 #  Unless required by applicable law or agreed to in writing, software
8 #  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 #  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 #  License for the specific language governing permissions and limitations
11 #  under the License.
12
13 """Output formatters using csv format.
14 """
15
16 import os
17 import sys
18
19 from .base import ListFormatter
20 from cliff import columns
21
22 import six
23
24 if sys.version_info[0] == 3:
25     import csv
26 else:
27     import unicodecsv as csv
28
29
30 class CSVLister(ListFormatter):
31
32     QUOTE_MODES = {
33         'all': csv.QUOTE_ALL,
34         'minimal': csv.QUOTE_MINIMAL,
35         'nonnumeric': csv.QUOTE_NONNUMERIC,
36         'none': csv.QUOTE_NONE,
37     }
38
39     def add_argument_group(self, parser):
40         group = parser.add_argument_group('CSV Formatter')
41         group.add_argument(
42             '--quote',
43             choices=sorted(self.QUOTE_MODES.keys()),
44             dest='quote_mode',
45             default='nonnumeric',
46             help='when to include quotes, defaults to nonnumeric',
47         )
48
49     def emit_list(self, column_names, data, stdout, parsed_args):
50         writer = csv.writer(stdout,
51                             quoting=self.QUOTE_MODES[parsed_args.quote_mode],
52                             lineterminator=os.linesep,
53                             escapechar='\\',
54                             )
55         writer.writerow(column_names)
56         for row in data:
57             writer.writerow(
58                 [(six.text_type(c.machine_readable())
59                   if isinstance(c, columns.FormattableColumn)
60                   else c)
61                  for c in row]
62             )
63         return