Debian Codegraph @

cli_helpers/tabular_output/preprocessors.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """These preprocessor functions are used to process data prior to output."""
3
4 import string
5 from datetime import datetime
6
7 from cli_helpers import utils
8 from cli_helpers.compat import text_type, int_types, float_types, HAS_PYGMENTS, Token
9
10
11 def truncate_string(
12 data, headers, max_field_width=None, skip_multiline_string=True, **_
13 ):
14 """Truncate very long strings. Only needed for tabular
15 representation, because trying to tabulate very long data
16 is problematic in terms of performance, and does not make any
17 sense visually.
18
19 :param iterable data: An :term:`iterable` (e.g. list) of rows.
20 :param iterable headers: The column headers.
21 :param int max_field_width: Width to truncate field for display
22 :return: The processed data and headers.
23 :rtype: tuple
24 """
25 return (
26 (
27 [
28 utils.truncate_string(v, max_field_width, skip_multiline_string)
29 for v in row
30 ]
31 for row in data
32 ),
33 [
34 utils.truncate_string(h, max_field_width, skip_multiline_string)
35 for h in headers
36 ],
37 )
38
39
40 def convert_to_string(data, headers, **_):
41 """Convert all *data* and *headers* to strings.
42
43 Binary data that cannot be decoded is converted to a hexadecimal
44 representation via :func:`binascii.hexlify`.
45
46 :param iterable data: An :term:`iterable` (e.g. list) of rows.
47 :param iterable headers: The column headers.
48 :return: The processed data and headers.
49 :rtype: tuple
50
51 """
52 return (
53 ([utils.to_string(v) for v in row] for row in data),
54 [utils.to_string(h) for h in headers],
55 )
56
57
58 def convert_to_undecoded_string(data, headers, **_):
59 """Convert all *data* and *headers* to hex, if needed.
60
61 Binary data is converted to a hexadecimal representation via
62 :func:`binascii.hexlify`.
63
64 Unlike convert_to_string(), None values are left as Nones.
65
66 :param iterable data: An :term:`iterable` (e.g. list) of rows.
67 :param iterable headers: The column headers.
68 :return: The processed data and headers.
69 :rtype: tuple
70
71 """
72 return (
73 ([utils.to_undecoded_string(v) for v in row] for row in data),
74 [utils.to_undecoded_string(h) for h in headers],
75 )
76
77
78 def override_missing_value(
79 data,
80 headers,
81 style=None,
82 missing_value_token=Token.Output.Null,
83 missing_value="",
84 **_,
85 ):
86 """Override missing values in the *data* with *missing_value*.
87
88 A missing value is any value that is :data:`None`.
89
90 :param iterable data: An :term:`iterable` (e.g. list) of rows.
91 :param iterable headers: The column headers.
92 :param style: Style for missing_value.
93 :param missing_value_token: The Pygments token used for missing data.
94 :param missing_value: The default value to use for missing data.
95 :return: The processed data and headers.
96 :rtype: tuple
97
98 """
99
100 def fields():
101 for row in data:
102 processed = []
103 for field in row:
104 if field is None and style and HAS_PYGMENTS:
105 styled = utils.style_field(
106 missing_value_token, missing_value, style
107 )
108 processed.append(styled)
109 elif field is None:
110 processed.append(missing_value)
111 else:
112 processed.append(field)
113 yield processed
114
115 return (fields(), headers)
116
117
118 def override_tab_value(data, headers, new_value=" ", **_):
119 """Override tab values in the *data* with *new_value*.
120
121 :param iterable data: An :term:`iterable` (e.g. list) of rows.
122 :param iterable headers: The column headers.
123 :param new_value: The new value to use for tab.
124 :return: The processed data and headers.
125 :rtype: tuple
126
127 """
128 return (
129 (
130 [v.replace("\t", new_value) if isinstance(v, text_type) else v for v in row]
131 for row in data
132 ),
133 headers,
134 )
135
136
137 def escape_newlines(data, headers, **_):
138 """Escape newline characters (\n -> \\n, \r -> \\r)
139
140 :param iterable data: An :term:`iterable` (e.g. list) of rows.
141 :param iterable headers: The column headers.
142 :return: The processed data and headers.
143 :rtype: tuple
144
145 """
146 return (
147 (
148 [
149 (
150 v.replace("\r", r"\r").replace("\n", r"\n")
151 if isinstance(v, text_type)
152 else v
153 )
154 for v in row
155 ]
156 for row in data
157 ),
158 headers,
159 )
160
161
162 def bytes_to_string(data, headers, **_):
163 """Convert all *data* and *headers* bytes to strings.
164
165 Binary data that cannot be decoded is converted to a hexadecimal
166 representation via :func:`binascii.hexlify`.
167
168 :param iterable data: An :term:`iterable` (e.g. list) of rows.
169 :param iterable headers: The column headers.
170 :return: The processed data and headers.
171 :rtype: tuple
172
173 """
174 return (
175 ([utils.bytes_to_string(v) for v in row] for row in data),
176 [utils.bytes_to_string(h) for h in headers],
177 )
178
179
180 def align_decimals(data, headers, column_types=(), **_):
181 """Align numbers in *data* on their decimal points.
182
183 Whitespace padding is added before a number so that all numbers in a
184 column are aligned.
185
186 Outputting data before aligning the decimals::
187
188 1
189 2.1
190 10.59
191
192 Outputting data after aligning the decimals::
193
194 1
195 2.1
196 10.59
197
198 :param iterable data: An :term:`iterable` (e.g. list) of rows.
199 :param iterable headers: The column headers.
200 :param iterable column_types: The columns' type objects (e.g. int or float).
201 :return: The processed data and headers.
202 :rtype: tuple
203
204 """
205 pointpos = len(headers) * [0]
206 data = list(data)
207 for row in data:
208 for i, v in enumerate(row):
209 if column_types[i] is float and type(v) in float_types:
210 v = text_type(v)
211 pointpos[i] = max(utils.intlen(v), pointpos[i])
212
213 def results(data):
214 for row in data:
215 result = []
216 for i, v in enumerate(row):
217 if column_types[i] is float and type(v) in float_types:
218 v = text_type(v)
219 result.append((pointpos[i] - utils.intlen(v)) * " " + v)
220 else:
221 result.append(v)
222 yield result
223
224 return results(data), headers
225
226
227 def quote_whitespaces(data, headers, quotestyle="'", **_):
228 """Quote leading/trailing whitespace in *data*.
229
230 When outputing data with leading or trailing whitespace, it can be useful
231 to put quotation marks around the value so the whitespace is more
232 apparent. If one value in a column needs quoted, then all values in that
233 column are quoted to keep things consistent.
234
235 .. NOTE::
236 :data:`string.whitespace` is used to determine which characters are
237 whitespace.
238
239 :param iterable data: An :term:`iterable` (e.g. list) of rows.
240 :param iterable headers: The column headers.
241 :param str quotestyle: The quotation mark to use (defaults to ``'``).
242 :return: The processed data and headers.
243 :rtype: tuple
244
245 """
246 whitespace = tuple(string.whitespace)
247 quote = len(headers) * [False]
248 data = list(data)
249 for row in data:
250 for i, v in enumerate(row):
251 v = text_type(v)
252 if v.startswith(whitespace) or v.endswith(whitespace):
253 quote[i] = True
254
255 def results(data):
256 for row in data:
257 result = []
258 for i, v in enumerate(row):
259 quotation = quotestyle if quote[i] else ""
260 result.append(
261 "{quotestyle}{value}{quotestyle}".format(
262 quotestyle=quotation, value=v
263 )
264 )
265 yield result
266
267 return results(data), headers
268
269
270 def style_output(
271 data,
272 headers,
273 style=None,
274 header_token=Token.Output.Header,
275 odd_row_token=Token.Output.OddRow,
276 even_row_token=Token.Output.EvenRow,
277 **_,
278 ):
279 """Style the *data* and *headers* (e.g. bold, italic, and colors)
280
281 .. NOTE::
282 This requires the `Pygments <http://pygments.org/>`_ library to
283 be installed. You can install it with CLI Helpers as an extra::
284 $ pip install cli_helpers[styles]
285
286 Example usage::
287
288 from cli_helpers.tabular_output.preprocessors import style_output
289 from pygments.style import Style
290 from pygments.token import Token
291
292 class YourStyle(Style):
293 default_style = ""
294 styles = {
295 Token.Output.Header: 'bold ansibrightred',
296 Token.Output.OddRow: 'bg:#eee #111',
297 Token.Output.EvenRow: '#0f0'
298 }
299
300 headers = ('First Name', 'Last Name')
301 data = [['Fred', 'Roberts'], ['George', 'Smith']]
302
303 data, headers = style_output(data, headers, style=YourStyle)
304
305 :param iterable data: An :term:`iterable` (e.g. list) of rows.
306 :param iterable headers: The column headers.
307 :param str/pygments.style.Style style: A Pygments style. You can `create
308 your own styles <https://pygments.org/docs/styles#creating-own-styles>`_.
309 :param str header_token: The token type to be used for the headers.
310 :param str odd_row_token: The token type to be used for odd rows.
311 :param str even_row_token: The token type to be used for even rows.
312 :return: The styled data and headers.
313 :rtype: tuple
314
315 """
316 from cli_helpers.utils import filter_style_table
317
318 relevant_styles = filter_style_table(
319 style, header_token, odd_row_token, even_row_token
320 )
321 if style and HAS_PYGMENTS:
322 if relevant_styles.get(header_token):
323 headers = [
324 utils.style_field(header_token, header, style) for header in headers
325 ]
326 if relevant_styles.get(odd_row_token) or relevant_styles.get(even_row_token):
327 data = (
328 [
329 utils.style_field(
330 odd_row_token if i % 2 else even_row_token, f, style
331 )
332 for f in r
333 ]
334 for i, r in enumerate(data, 1)
335 )
336
337 return iter(data), headers
338
339
340 def format_numbers(
341 data, headers, column_types=(), integer_format=None, float_format=None, **_
342 ):
343 """Format numbers according to a format specification.
344
345 This uses Python's format specification to format numbers of the following
346 types: :class:`int`, :class:`py2:long` (Python 2), :class:`float`, and
347 :class:`~decimal.Decimal`. See the :ref:`python:formatspec` for more
348 information about the format strings.
349
350 .. NOTE::
351 A column is only formatted if all of its values are the same type
352 (except for :data:`None`).
353
354 :param iterable data: An :term:`iterable` (e.g. list) of rows.
355 :param iterable headers: The column headers.
356 :param iterable column_types: The columns' type objects (e.g. int or float).
357 :param str integer_format: The format string to use for integer columns.
358 :param str float_format: The format string to use for float columns.
359 :return: The processed data and headers.
360 :rtype: tuple
361
362 """
363 if (integer_format is None and float_format is None) or not column_types:
364 return iter(data), headers
365
366 def _format_number(field, column_type):
367 if integer_format and column_type is int and type(field) in int_types:
368 return format(field, integer_format)
369 elif float_format and column_type is float and type(field) in float_types:
370 return format(field, float_format)
371 return field
372
373 data = (
374 [_format_number(v, column_types[i]) for i, v in enumerate(row)] for row in data
375 )
376 return data, headers
377
378
379 def format_timestamps(data, headers, column_date_formats=None, **_):
380 """Format timestamps according to user preference.
381
382 This allows for per-column formatting for date, time, or datetime like data.
383
384 Add a `column_date_formats` section to your config file with separate lines for each column
385 that you'd like to specify a format using `name=format`. Use standard Python strftime
386 formatting strings
387
388 Example: `signup_date = "%Y-%m-%d"`
389
390 :param iterable data: An :term:`iterable` (e.g. list) of rows.
391 :param iterable headers: The column headers.
392 :param str column_date_format: The format strings to use for specific columns.
393 :return: The processed data and headers.
394 :rtype: tuple
395
396 """
397 if column_date_formats is None:
398 return iter(data), headers
399
400 def _format_timestamp(value, name, column_date_formats):
401 if name not in column_date_formats:
402 return value
403 try:
404 dt = datetime.fromisoformat(value)
405 return dt.strftime(column_date_formats[name])
406 except (ValueError, TypeError):
407 # not a date
408 return value
409
410 data = (
411 [
412 _format_timestamp(v, headers[i], column_date_formats)
413 for i, v in enumerate(row)
414 ]
415 for row in data
416 )
417 return data, headers