Debian Codegraph @

cylc/flow/terminal.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16
17 """Functionality to assist working with terminals"""
18
19 import inspect
20 import json
21 import logging
22 import os
23 import sys
24 from functools import wraps
25 from subprocess import PIPE, Popen # nosec
26 from textwrap import wrap
27 from typing import (
28 TYPE_CHECKING,
29 Any,
30 Callable,
31 Dict,
32 List,
33 Optional,
34 Sequence,
35 TypeVar,
36 Union,
37 cast,
38 overload,
39 )
40
41 from ansimarkup import parse as cparse
42 from colorama import init as color_init
43
44 import cylc.flow.flags
45 from cylc.flow import CYLC_LOG
46 from cylc.flow.exceptions import CylcError
47 from cylc.flow.loggingutil import CylcLogFormatter
48 from cylc.flow.parsec.exceptions import ParsecError
49
50
51 if TYPE_CHECKING:
52 from optparse import OptionParser, Values
53
54 T = TypeVar('T')
55 StrFunc = Callable[[str], str]
56
57
58 # CLI exception message format
59 EXC_EXIT = cparse('<red><bold>{name}: </bold>{exc}</red>')
60
61 # default grey colour (do not use "dim", it is not sufficiently portable)
62 DIM = 'fg 248'
63
64 # turn input into a global() for testing purposes
65 input = input # noqa
66
67
68 def is_terminal():
69 """Determine if running in (and printing to) a terminal."""
70 # Return False if stdout or stderr not going to a terminal.
71 return (
72 (
73 hasattr(sys.stderr, 'isatty') and sys.stderr.isatty()
74 ) and (
75 hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
76 )
77 )
78
79
80 def get_width(default=80):
81 """Return the terminal width or `default` if it is not determinable."""
82 # stty can have different install locs so don't use absolute path
83 proc = Popen(['stty', 'size'], stdout=PIPE, stderr=PIPE) # nosec
84 if proc.wait():
85 return default
86 try:
87 return int(proc.communicate()[0].split()[1]) or default
88 except (IndexError, ValueError):
89 return default
90
91
92 def print_contents(contents, padding=5, char='.', indent=0):
93 title_width = max(
94 len(title)
95 for title, _ in contents
96 )
97 width = get_width(default=0)
98 if width < title_width + 20 - indent - padding:
99 width = title_width + 20 - indent - padding
100 desc_width = width - title_width - padding - 2 - indent
101 indent = ' ' * indent
102 for title, desc in contents:
103 desc_lines = wrap(desc or '', desc_width) or ['']
104 print(
105 f'{indent}'
106 f'{title} {char * (padding + title_width - len(title))} '
107 f'{desc_lines[0]}'
108 )
109 for line in desc_lines[1:]:
110 print(f'{indent} {" " * title_width}{" " * padding}{line}')
111
112
113 def format_grid(rows, gutter=2):
114 """Format gridded text.
115
116 This takes a 2D table of text and formats it to the maximum width of each
117 column and adds a bit of space between them.
118
119 Args:
120 rows:
121 2D list containing the text to format.
122 gutter:
123 The width of the gutter between columns.
124
125 Examples:
126 >>> format_grid([
127 ... ['a', 'b', 'ccccc'],
128 ... ['ddddd', 'e', 'f'],
129 ... ])
130 ['a b ccccc ',
131 'ddddd e f ']
132
133 >>> format_grid([])
134 []
135
136 """
137 if not rows:
138 return rows
139 templ = [
140 '{col:%d}' % (max(
141 len(row[ind])
142 for row in rows
143 ) + gutter)
144 for ind in range(len(rows[0]))
145 ]
146 lines = []
147 for row in rows:
148 ret = ''
149 for ind, col in enumerate(row):
150 ret += templ[ind].format(col=col)
151 lines.append(ret)
152 return lines
153
154
155 def supports_color() -> bool:
156 """Determine if running in a terminal which supports color.
157
158 See equivalent code in Django:
159 https://github.com/django/django/blob/master/django/core/management/color.py
160 """
161 if not is_terminal():
162 return False
163 if sys.platform in {'Pocket PC', 'win32'}:
164 return False
165 if 'ANSICON' in os.environ:
166 return False
167 return True
168
169
170 def should_use_color(opts: 'Optional[Values]') -> bool:
171 """Determine whether to use color based on the options supplied."""
172 return opts is not None and hasattr(opts, 'color') and (
173 opts.color == 'always'
174 or (opts.color == 'auto' and supports_color())
175 )
176
177
178 def ansi_log(name=CYLC_LOG, stream='stderr'):
179 """Configure log formatter for terminal usage.
180
181 Re-configures the formatter of any logging handlers pointing at the
182 specified stream.
183
184 Args:
185 name (str): Logger name.
186 stream (str): Either stdout or stderr.
187
188 """
189 stream_name = f'<{stream}>'
190 for handler in logging.getLogger(name).handlers:
191 if (
192 getattr(handler, 'formatter', None)
193 and isinstance(handler.formatter, CylcLogFormatter)
194 and isinstance(handler, logging.StreamHandler)
195 and handler.stream.name == stream_name
196 ):
197 handler.formatter.configure(color=True, max_width=get_width())
198
199
200 def parse_dirty_json(stdout):
201 """Parse JSON from a string from dirty output.
202
203 This is designed to handle cases where users have trash like this in their
204 shell profile files::
205
206 echo "[Hello $USER]"
207
208 Examples:
209 Prevents stdout trash from corrupting following json:
210 >>> parse_dirty_json('''
211 ... some mess here
212 ... ["some json here"]
213 ... ''')
214 ['some json here']
215
216 Ignores stdout trash which looks like json:
217 >>> parse_dirty_json('''
218 ... ["something which isn't meant to be json here"]
219 ... {"something": "which is intended to be json here"}
220 ... ''')
221 {'something': 'which is intended to be json here'}
222
223 Any stdout trash must be followed by a newline though:
224 >>> parse_dirty_json('''
225 ... this approach can't handle everything [
226 ... "nicely"
227 ... ]
228 ... ''')
229 Traceback (most recent call last):
230 ValueError: this approach can't handle everything [
231 "nicely"
232 ]
233
234 Other:
235 >>> parse_dirty_json('')
236 Traceback (most recent call last):
237 ValueError
238
239
240 """
241 stdout = stdout.strip()
242 orig = stdout
243 while stdout:
244 try:
245 return json.loads(stdout)
246 except ValueError:
247 try:
248 stdout = stdout.split('\n', 1)[1]
249 except IndexError:
250 break
251 raise ValueError(orig)
252
253
254 def cli_function(
255 parser_function: 'Optional[Callable[..., OptionParser]]' = None,
256 **parser_kwargs: Any
257 ):
258 """Decorator for CLI entry points.
259
260 Catches "known" errors and suppresses [full] traceback.
261
262 """
263 def inner(wrapped_function: Callable):
264 @wraps(wrapped_function)
265 def wrapper(*api_args: str) -> None:
266 """The function that we actually call.
267
268 Args:
269 api_args (tuple|list):
270 CLI arguments as specified via Python rather than
271 sys.argv directly.
272 If specified these will be passed to the option parser.
273
274 """
275 try:
276 use_color = False
277 wrapped_args, wrapped_kwargs = [], {}
278 if parser_function:
279 parser = parser_function()
280 opts, args = parser.parse_args(
281 list(api_args),
282 **parser_kwargs
283 )
284 use_color = should_use_color(opts)
285 wrapped_args = [parser, opts, *args]
286 if 'color' in inspect.signature(wrapped_function).parameters:
287 wrapped_kwargs['color'] = use_color
288
289 # configure Cylc to use colour
290 # TODO: re-enable autoreset
291 # (https://github.com/cylc/cylc-flow/issues/6076)
292 color_init(autoreset=False, strip=not use_color)
293 if use_color:
294 ansi_log()
295
296 try:
297 # run the command
298 wrapped_function(*wrapped_args, **wrapped_kwargs)
299 except (CylcError, ParsecError) as exc:
300 if cylc.flow.flags.verbosity > 1:
301 # raise the full traceback
302 raise
303 # else catch "known" CylcErrors which should have sensible
304 # short summations of the issue, full traceback not
305 # necessary
306 print(
307 EXC_EXIT.format(
308 name=exc.__class__.__name__,
309 exc=exc
310 ),
311 file=sys.stderr
312 )
313 sys.exit(1)
314
315 except SystemExit as exc:
316 if exc.args and isinstance(exc.args[0], str):
317 # catch and reformat sys.exit(<str>)
318 # NOTE: sys.exit(a) is equivalent to:
319 # print(a, file=sys.stderr); sys.exit(1)
320 print(
321 EXC_EXIT.format(
322 name='ERROR',
323 exc=exc.args[0]
324 ),
325 file=sys.stderr
326 )
327 sys.exit(1)
328 raise
329 except UnicodeEncodeError as exc:
330 # this error can be raised from any code which attempts to
331 # write a UTF-8 character to a terminal which does not or is
332 # not configured to support UTF-8
333 try:
334 # double check that this error is due to a non-UTF-8
335 # compatible terminal and not an internal issue...
336 print('😭')
337 except UnicodeEncodeError:
338 # ... yep
339 print(
340 EXC_EXIT.format(
341 name='UnicodeEncodeError',
342 exc=(
343 '- A UTF-8 compatible terminal is'
344 ' required for this command.'
345 '\nTry adding ".UTF-8" onto the LANG'
346 ' environment variable e.g:'
347 '\n$ LANG=C.UTF-8'
348 f' cylc {" ".join(sys.argv[1:])}'
349 ),
350 ),
351 file=sys.stderr,
352 )
353 sys.exit(1)
354 raise exc from None
355 wrapper.parser_function = parser_function # type: ignore
356 return wrapper
357 return inner
358
359
360 @overload
361 def prompt(
362 message: str,
363 options: Sequence[str],
364 default: Optional[str] = None,
365 process: Optional['StrFunc'] = None,
366 ) -> str:
367 ...
368
369
370 @overload
371 def prompt(
372 message: str,
373 options: Dict[str, 'T'],
374 default: Optional[str] = None,
375 process: Optional['StrFunc'] = None,
376 ) -> 'T':
377 ...
378
379
380 def prompt(
381 message: str,
382 options: Union[Sequence[str], Dict[str, 'T']],
383 default: Optional[str] = None,
384 process: Optional['StrFunc'] = None,
385 ) -> Union[str, 'T']:
386 """Dead simple CLI textual prompting.
387
388 Args:
389 message:
390 The message to put before the user, don't end this with
391 punctuation.
392 options:
393 The choices the user can pick:
394 * If this is a list the option selected will be returned.
395 * If this is a dict the keys are options, the corresponding value
396 will be returned.
397 default:
398 A value to be chosen if the user presses <return> without first
399 typing anything.
400 process:
401 A function to run the user's input through before comparision.
402 E.G. string.lower.
403
404 Returns:
405 The selected option (if options is a list) else the corresponding
406 value (if options is a dict).
407
408 """
409 default_ = ''
410 if default:
411 default_ = f'[{default}] '
412 message += f': {default_}{",".join(options)}? '
413 usr = cast('str', None)
414 while usr not in options:
415 usr = input(f'{message}')
416 if default is not None and not usr:
417 usr = default
418 if process:
419 usr = process(usr)
420 if isinstance(options, dict):
421 return options[usr]
422 return usr
423
424
425 def flatten_cli_lists(lsts: List[str]) -> List[str]:
426 """Return a sorted flat list for multi-use CLI command options.
427
428 Examples:
429 # --out='a,b,c'
430 >>> flatten_cli_lists(['a,b,c'])
431 ['a', 'b', 'c']
432
433 # --out='a' --out='a,b'
434 >>> flatten_cli_lists(['a', 'b,c'])
435 ['a', 'b', 'c']
436
437 # --out='a' --out='a,b'
438 >>> flatten_cli_lists(['a', 'a,b'])
439 ['a', 'b']
440
441 # --out=' a '
442 >>> flatten_cli_lists([' a '])
443 ['a']
444
445 # --out='a, b, c , d'
446 >>> flatten_cli_lists(['a, b, c , d'])
447 ['a', 'b', 'c', 'd']
448
449 """
450 return sorted({
451 item.strip()
452 for lst in (lsts or [])
453 for item in lst.strip().split(',')
454 })