6e7bae98d30646e9620e1536040ecdd902063968
[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 shell syntax.
14 """
15
16 from . import base
17 from cliff import columns
18
19 import argparse
20 import six
21
22
23 class ShellFormatter(base.SingleFormatter):
24
25     def add_argument_group(self, parser):
26         group = parser.add_argument_group(
27             title='shell formatter',
28             description='a format a UNIX shell can parse (variable="value")',
29         )
30         group.add_argument(
31             '--variable',
32             action='append',
33             default=[],
34             dest='variables',
35             metavar='VARIABLE',
36             help=argparse.SUPPRESS,
37         )
38         group.add_argument(
39             '--prefix',
40             action='store',
41             default='',
42             dest='prefix',
43             help='add a prefix to all variable names',
44         )
45
46     def emit_one(self, column_names, data, stdout, parsed_args):
47         variable_names = [c.lower().replace(' ', '_')
48                           for c in column_names
49                           ]
50         desired_columns = parsed_args.variables
51         for name, value in zip(variable_names, data):
52             if name in desired_columns or not desired_columns:
53                 value = (six.text_type(value.machine_readable())
54                          if isinstance(value, columns.FormattableColumn)
55                          else value)
56                 if isinstance(value, six.string_types):
57                     value = value.replace('"', '\\"')
58                 if isinstance(name, six.string_types):
59                     # Colons and dashes may appear as a resource property but
60                     # are invalid to use in a shell, replace them with an
61                     # underscore.
62                     name = name.replace(':', '_')
63                     name = name.replace('-', '_')
64                 stdout.write('%s%s="%s"\n' % (parsed_args.prefix, name, value))
65         return