Debian Codegraph @

src/briefcase/console.py

raw
1 from __future__ import annotations
2
3 import logging
4 import os
5 import platform
6 import re
7 import shutil
8 import sys
9 import textwrap
10 import time
11 import traceback
12 from collections.abc import Callable, Collection, Iterable, Mapping
13 from contextlib import contextmanager
14 from datetime import datetime
15 from enum import IntEnum
16 from pathlib import Path
17 from typing import Any
18
19 from rich.console import Console as RichConsole
20 from rich.control import strip_control_codes
21 from rich.highlighter import RegexHighlighter
22 from rich.markup import escape
23 from rich.progress import (
24 BarColumn,
25 Progress,
26 SpinnerColumn,
27 TextColumn,
28 TimeRemainingColumn,
29 )
30 from rich.traceback import Trace, Traceback
31
32 from briefcase import __version__
33 from briefcase.config import parse_boolean
34 from briefcase.exceptions import InputDisabled
35
36 # Max width for printing to console; matches argparse's default width
37 MAX_TEXT_WIDTH = max(min(shutil.get_terminal_size().columns, 80) - 2, 20)
38
39 # Regex to identify settings likely to contain sensitive information
40 SENSITIVE_SETTING_RE = re.compile(
41 r"API|TOKEN|KEY|SECRET|PASS|SIGNATURE", flags=re.IGNORECASE
42 )
43
44 # 7-bit C1 ANSI escape sequences
45 ANSI_ESC_SEQ_RE_DEF = r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])"
46 ANSI_ESCAPE_RE = re.compile(ANSI_ESC_SEQ_RE_DEF)
47
48
49 def sanitize_text(text: str) -> str:
50 """Remove control codes and ANSI escape sequences from a line of text.
51
52 This is useful for extracting the plain text from the output of third party tools
53 that may be including markup for display in the console.
54 """
55 return ANSI_ESCAPE_RE.sub("", strip_control_codes(text))
56
57
58 class RichConsoleHighlighter(RegexHighlighter):
59 """Custom Rich highlighter for printing to the console.
60
61 This highlighter limits text highlighting to only URLs.
62
63 By default, Rich applies several highlighting rules to anything it prints for
64 concepts like UUIDs, markup, IP addresses, numbers, etc. All these colorful
65 additions to the text can become overbearing and distracting given much of the
66 output does not benefit from coloring.
67
68 This defines a visually simpler style that highlights URLs in a way that is vaguely
69 consistent with a default HTML stylesheet, but otherwise renders content as-is.
70 """
71
72 base_style = "repr."
73 highlights: Collection[str] = [
74 r"(?P<url>(file|https|http|ws|wss)://[-0-9a-zA-Z$_+!`(),.?/;:&=%#~]*)"
75 ]
76
77
78 class RichLoggingStream:
79 """Stream for logging.StreamHandler that prints to console via debug logging."""
80
81 def __init__(self, console: Console):
82 self.console = console
83
84 def write(self, msg: str) -> None:
85 self.console.debug(msg)
86
87
88 class RichLoggingHandler(logging.StreamHandler):
89 """A debug handler for third party tools using stdlib logging."""
90
91 def __init__(self, stream: RichLoggingStream):
92 super().__init__(stream=stream)
93 self.setLevel(logging.DEBUG)
94 self.setFormatter(logging.Formatter("%(levelname)s %(name)s: %(message)s"))
95
96
97 class LogLevel(IntEnum):
98 INFO = 0
99 VERBOSE = 1
100 DEBUG = 2
101 DEEP_DEBUG = 3
102
103
104 class NotDeadYet:
105 # I'm getting better! No, you're not, you'll be stone dead in a minute.
106
107 def __init__(self, console: Console):
108 """A keep-alive spinner for long-running processes without console output.
109
110 Returned by the Wait Bar's context manager but can be used independently. Use in
111 a loop that calls update() each iteration. A keep-alive message will be printed
112 every 10 seconds.
113 """
114 self.console = console
115 self.interval_sec: int = 10
116 self.message: str = "... still waiting"
117 self.ready_time: float = 0.0
118
119 self.reset() # initialize
120
121 def update(self):
122 """Write keep-alive message if the periodic interval has elapsed."""
123 if self.ready_time < time.time():
124 self.console.print(self.message)
125 self.reset()
126
127 def reset(self):
128 """Initialize periodic interval to now; next message prints after interval."""
129 self.ready_time = time.time() + self.interval_sec
130
131
132 class Console:
133 # subdirectory of command.base_path to store log files
134 LOG_DIR = "logs"
135
136 def __init__(
137 self,
138 input_enabled: bool = True,
139 verbosity: LogLevel = LogLevel.INFO,
140 log_width: int = 180,
141 ):
142 """Interface for printing and managing output to the console and/or log.
143
144 :param input_enabled: Is the console current enabled for input?
145 :param verbosity: Controls how much output is displayed to the user.
146 :param log_width: The width at which content should be wrapped in the log file.
147 The default width is wide enough to render the output of ``sdkmanager
148 --list_installed`` in the log file without line wrapping.
149 """
150 self.log_width = log_width
151
152 # A wrapper around the console
153 self._console_impl = RichConsole(
154 highlighter=RichConsoleHighlighter(),
155 emoji=False,
156 soft_wrap=True,
157 )
158
159 # Rich only records what's being logged if it is actually written somewhere;
160 # writing to /dev/null allows Rich to do so without needing to print the
161 # logs in the console or save them to file before it is known a file is wanted.
162 self._dev_null = open( # noqa: SIM115 (can't use context manager here)
163 os.devnull, "w", encoding="utf-8", errors="ignore"
164 )
165 self._log_impl = RichConsole(
166 file=self._dev_null,
167 record=True,
168 width=self.log_width,
169 force_interactive=False,
170 force_terminal=False,
171 no_color=True,
172 color_system=None,
173 markup=False,
174 emoji=False,
175 highlight=False,
176 soft_wrap=True,
177 )
178
179 ##################################################################
180 # Logging properties
181 ##################################################################
182
183 # --verbosity flag: see LogLevel for valid values
184 self.verbosity = verbosity
185 # --log flag to force logfile creation
186 self.save_log = False
187 # flag set by exceptions to skip writing the log; save_log takes precedence.
188 self.skip_log = False
189 # Rich stacktraces of exceptions for logging to a file.
190 # A list of tuples containing a label for the thread context,
191 # and the Trace object
192 self.stacktraces: list[tuple[str, Trace]] = []
193 # functions to run for additional logging if creating a logfile
194 self.log_file_extras: list[Callable[[], object]] = []
195 # The current context for the log
196 self._context = ""
197
198 ##################################################################
199 # Console management properties
200 ##################################################################
201 self.input_enabled = input_enabled
202
203 self._wait_bar: Progress | None = None
204 # Signal that Rich is dynamically controlling the console output. Therefore,
205 # all output must be printed to the screen by Rich to prevent corruption of
206 # dynamic elements like the Wait Bar.
207 self.is_console_controlled = False
208
209 def close(self):
210 self._dev_null.close()
211 self._dev_null = None
212
213 def __del__(self):
214 if self._dev_null:
215 self.close()
216
217 #################################################################
218 # Console primitives
219 #################################################################
220
221 def print(self, *messages, stack_offset=5, show=True, **kwargs):
222 """Entry point for all printing to the console and the log.
223
224 The log records all content that is printed whether it is shown in the console
225 or not (e.g. debug output). When execution completes, the log is conditionally
226 exported and saved to a file.
227
228 :param messages: content to print and/or log
229 :param show: True (default) to print and log messages; False to only log.
230 :param stack_offset: number of levels up the stack where logging was invoked.
231 This tells Rich the number of levels to recurse up the stack to find the
232 filename to put in the right column of the Rich log. Defaults to 5 since
233 most uses are 5 levels deep from the actual logging.
234 """
235 if show:
236 self.to_console(*messages, **kwargs)
237 self.to_log(*messages, stack_offset=stack_offset, **kwargs)
238
239 def to_console(self, *messages, **kwargs):
240 """Write only to the console and skip writing to the log."""
241 self._console_impl.print(*messages, **kwargs)
242
243 def to_log(self, *messages, stack_offset=5, **kwargs):
244 """Write only to the log and skip writing to the console."""
245 self._log_impl.log(
246 *map(sanitize_text, messages), _stack_offset=stack_offset, **kwargs
247 )
248
249 def export_log(self):
250 """Export the text of the entire log; the log is also cleared."""
251 return self._log_impl.export_text()
252
253 #################################################################
254 # Logging controls
255 #################################################################
256 @contextmanager
257 def context(self, context: str):
258 """Wrap a collection of output in a logging context.
259
260 A logging context is a prefix on every logging line. It is used when a set of
261 commands (and output) is being run in a very specific way that needs to be
262 highlighted, such as running a command in a Docker container.
263
264 :param context: The name of the context to enter. This *must* be simple text,
265 with no markup or other special characters.
266 """
267 self.info()
268 self.info(f"Entering {context} context...")
269 old_context = self._context
270 self._context = f"{context}| "
271 self.info("-" * (72 - len(context)))
272 try:
273 yield
274 finally:
275 self.info("-" * (72 - len(context)))
276 self._context = old_context
277 self.info(f"Leaving {context} context.")
278 self.info()
279
280 def _log(
281 self,
282 preface="",
283 prefix="",
284 message="",
285 show=True,
286 markup=False,
287 style=None,
288 ):
289 """Funnel to log all messages.
290
291 :param preface: value to be printed on the far left of the message and symbolic
292 of the type of message being printed.
293 :param prefix: text prepended to the message wrapped in brackets and will be
294 presented as dimmer compared to the styling of the message text.
295 :param message: text to log; can contain Rich tags if markup=True.
296 :param show: True to print message to console; False to not print it. This is to
297 allow logs to be saved to a file without printing them.
298 :param markup: whether to interpret Rich markup in the prefix, preface, and
299 message; if True, all text must already be escaped; defaults False.
300 :param style: Rich style to apply to everything printed for message.
301 """
302 if not message:
303 # When a message is not provided, only output the context;
304 # This type of call is just clearing some vertical space.
305 self.print(self._context, show=show)
306 else:
307 if prefix:
308 # insert vertical space before for all messages with a prefix
309 self.print(self._context, show=show)
310 if not markup:
311 preface, prefix, message = (
312 escape(text) for text in (preface, prefix, message)
313 )
314 prefix = f"[dim]\\[{prefix}][/dim] "
315 markup = True
316 for line in message.splitlines():
317 self.print(
318 f"{self._context}{preface}{prefix}{line}",
319 show=show,
320 markup=markup,
321 style=style,
322 )
323
324 def debug(self, message="", *, preface="", prefix="", markup=False):
325 """Log messages at debug level; included if verbosity >= 2."""
326 self._log(
327 preface=preface,
328 prefix=prefix,
329 message=message,
330 show=self.is_debug,
331 markup=markup,
332 style="dim",
333 )
334
335 def verbose(self, message="", *, prefix="", markup=False):
336 """Log message at verbose level; included if verbosity >= 1."""
337 self._log(prefix=prefix, message=message, show=self.is_verbose, markup=markup)
338
339 def info(self, message="", *, prefix="", markup=False):
340 """Log message at info level; always included in output."""
341 self._log(prefix=prefix, message=message, markup=markup)
342
343 def warning(self, message="", *, prefix="", markup=False):
344 """Log message at warning level; always included in output."""
345 self._log(prefix=prefix, message=message, markup=markup, style="bold yellow")
346
347 def error(self, message="", *, prefix="", markup=False):
348 """Log message at error level; always included in output."""
349 self._log(prefix=prefix, message=message, markup=markup, style="bold red")
350
351 @property
352 def verbosity(self) -> LogLevel:
353 return self._verbosity
354
355 @verbosity.setter
356 def verbosity(self, value: int | LogLevel):
357 """Clamp verbosity between valid log levels."""
358 self._verbosity = LogLevel(max(min(LogLevel), min(value, max(LogLevel))))
359
360 @property
361 def is_verbose(self):
362 """Is verbose logging enabled via the -v flag?
363
364 This includes Briefcase logging that isn't relevant during normal operation.
365 """
366 return self.verbosity >= LogLevel.VERBOSE
367
368 @property
369 def is_debug(self):
370 """Is debug logging enabled via the -vv flag?
371
372 This includes debug logging from third party tools.
373 """
374 return self.verbosity >= LogLevel.DEBUG
375
376 @property
377 def is_deep_debug(self):
378 """Is deep debug logging enabled via the -vvv flag?
379
380 This includes debug logging from third party tools.
381 """
382 return self.verbosity >= LogLevel.DEEP_DEBUG
383
384 def configure_stdlib_logging(self, logger_name: str):
385 """Configure stdlib logging for a third party tool to log through Rich.
386
387 When a third party tool written in Python uses the stdlib logging for their
388 logging, it may provide an abstraction to enable the logging in the console or
389 may require a handler to be added externally. Either way, the default handler
390 to write to the console, i.e. logging.StreamHandler, will bypass Rich logging
391 and therefore not be included in the logfile. To avoid this issue, this will
392 add a handler that specifically writes to the console through Rich.
393
394 :param logger_name: Name of the logger the third party tool uses. Typically,
395 this is the package name or path to a submodule for the package. Since
396 logging uses namespaces for logging, enabling DEBUG logging for `git` will
397 also enable it for others like `git.cmd`, `git.remote`, `git.config`, etc.
398 """
399 if not self.is_deep_debug:
400 return
401
402 logger = logging.getLogger(logger_name)
403
404 # do not add another rich handler if one already exists
405 if not any(isinstance(h, RichLoggingHandler) for h in logger.handlers):
406 logger.addHandler(
407 RichLoggingHandler(stream=RichLoggingStream(console=self))
408 )
409 logger.setLevel(logging.DEBUG)
410
411 def capture_stacktrace(self, label="Main thread"):
412 """Preserve Rich stacktrace from exception while in except block.
413
414 :param label: An identifying label for the thread that has raised the
415 stacktrace. Defaults to the main thread.
416 """
417 exc_info = sys.exc_info()
418 try:
419 self.skip_log = exc_info[1].skip_logfile
420 except AttributeError:
421 pass
422
423 self.stacktraces.append((label, Traceback.extract(*exc_info, show_locals=True)))
424
425 def add_log_file_extra(self, func: Callable[[], object]):
426 """Register a function to be called in the event that a log file is written.
427
428 This can be used to provide additional debugging information which is too
429 expensive to gather preemptively.
430 """
431 self.log_file_extras.append(func)
432
433 def save_log_to_file(self, command):
434 """Save the current application log to file."""
435 # A log file is always written if a Command ran and `--log` was provided.
436 # If `--log` was not provided, then the log is written when an exception
437 # occurred and the exception was not explicitly configured to skip the log.
438 if not (
439 command and (self.save_log or (self.stacktraces and not self.skip_log))
440 ):
441 return
442
443 with command.console.wait_bar("Saving log...", transient=True):
444 self.to_console()
445 log_filename = (
446 f"briefcase.{datetime.now().strftime('%Y_%m_%d-%H_%M_%S')}."
447 f"{command.command}.log"
448 )
449 log_filepath = command.base_path / self.LOG_DIR / log_filename
450 try:
451 log_filepath.parent.mkdir(parents=True, exist_ok=True)
452 with open(
453 log_filepath, "w", encoding="utf-8", errors="backslashreplace"
454 ) as log_file:
455 log_file.write(self._build_log(command))
456 except OSError as e:
457 self.error(f"Failed to save log to {log_filepath}: {e}")
458 else:
459 self.warning(f"Log saved to {log_filepath}")
460 self.to_console()
461
462 def _build_log(self, command) -> str:
463 """Accumulate all information to include in the log file."""
464 # Add the exception stacktraces to end of log if any were captured
465 if self.stacktraces:
466 # using print() instead of to_log() to avoid
467 # timestamp and code location inclusion for the stacktrace box.
468 for thread, stacktrace in self.stacktraces:
469 self._log_impl.print(
470 f"{thread} traceback:",
471 Traceback(
472 trace=stacktrace,
473 width=self.log_width,
474 show_locals=True,
475 ),
476 new_line_start=True,
477 )
478
479 # Retrieve additional logging added by the Command
480 if self.log_file_extras:
481 with self.wait_bar(
482 "Collecting extra information for log...",
483 transient=True,
484 ):
485 self.debug()
486 self.debug("Extra information:")
487 for func in self.log_file_extras:
488 try:
489 func()
490 except Exception:
491 self.error(traceback.format_exc())
492
493 sanitized_env_vars = "\n".join(
494 f"\t{env_var}="
495 + (
496 value
497 if not SENSITIVE_SETTING_RE.search(env_var)
498 else "********************"
499 )
500 for env_var, value in sorted(command.tools.os.environ.items())
501 )
502
503 # Capture pyproject.toml if one exists in the current directory
504 try:
505 with open(Path.cwd() / "pyproject.toml", encoding="utf-8") as f:
506 pyproject_toml = f.read().strip()
507 except OSError as e:
508 pyproject_toml = str(e)
509
510 # Build log with buffered log from Rich
511 uname = platform.uname()
512 return (
513 f"Date/Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S %Z')}\n"
514 f"Command line: {' '.join(sys.argv)}\n"
515 "\n"
516 f"OS Release: {uname.system} {uname.release}\n"
517 f"OS Version: {uname.version}\n"
518 f"Architecture: {uname.machine}\n"
519 f"Platform: {platform.platform(aliased=True)}\n"
520 "\n"
521 f"Python exe: {sys.executable}\n"
522 # replace line breaks with spaces
523 # (use chr(10) since '\n' isn't allowed in f-strings...)
524 f"Python version: {sys.version.replace(chr(10), ' ')}\n"
525 # sys.base_prefix is always the python exe's original site-specific
526 # directory (e.g. /usr/local).
527 # sys.prefix is updated (from base_prefix's value) to the virtual env's
528 # site-specific directory.
529 f"Virtual env: {sys.base_prefix != sys.prefix}\n"
530 # for conda, prefix and base_prefix are likely the same
531 # but contain a conda-meta dir.
532 f"Conda env: {(Path(sys.prefix) / 'conda-meta').exists()}\n"
533 "\n"
534 f"Briefcase: {__version__}\n"
535 f"Target platform: {command.platform}\n"
536 f"Target format: {command.output_format}\n"
537 "\n"
538 "Environment Variables:\n"
539 f"{sanitized_env_vars}\n"
540 "\n"
541 "pyproject.toml:\n"
542 f"{pyproject_toml}\n"
543 "\n"
544 "Briefcase Log:\n"
545 f"{self.export_log()}"
546 )
547
548 #################################################################
549 # Console controls
550 #################################################################
551
552 @property
553 def is_interactive(self):
554 """Returns interactivity mode based on the presence of a tty for stdout.
555
556 In a non-interactive session, Rich's dynamic elements like progress bars should
557 be disabled. By default, Rich will not render dynamic elements if a tty is not
558 available. However, environment variables like FORCE_COLOR can override this
559 behavior in Rich to not only show ANSI color and style but also dynamic
560 elements. In a CI environment with this configuration, a long-lived progress bar
561 can dramatically compromise the quality of logged output. So, dynamic elements
562 should be specifically disabled in non-interactive sessions.
563 """
564 # `sys.__stdout__` is used because Rich captures and redirects `sys.stdout`
565 return os.isatty(sys.__stdout__.fileno())
566
567 @property
568 def is_color_enabled(self):
569 """Is the underlying Rich console using color?
570
571 Rich can be explicitly configured to not use color at Console initialization or
572 the NO_COLOR environment variable; alternatively, the derived color system for
573 the terminal is influenced by attributes of the platform as well as FORCE_COLOR.
574 """
575 # no_color has precedence: color_system can be set even if color is disabled
576 if self._console_impl.no_color:
577 return False
578 else:
579 return self._console_impl.color_system is not None
580
581 def progress_bar(self):
582 """Returns a progress bar as a context manager."""
583 return Progress(
584 TextColumn(" "),
585 SpinnerColumn("line", speed=1.5, style="default"),
586 BarColumn(bar_width=50),
587 TextColumn("{task.percentage:>3.1f}%", style="default"),
588 TextColumn("•", style="default"),
589 TimeRemainingColumn(compact=True, elapsed_when_finished=True),
590 disable=not self.is_interactive,
591 console=self._console_impl,
592 )
593
594 @contextmanager
595 def wait_bar(
596 self,
597 message: str = "",
598 done_message: str = "done",
599 *,
600 transient: bool = False,
601 markup: bool = False,
602 ) -> NotDeadYet:
603 """Activates the Wait Bar as a context manager.
604
605 If the Wait Bar is already active, then its message is updated for the new
606 context. Once the new context is complete, the previous Wait Bar message
607 is restored.
608
609 :param message: text explaining what is being awaited; should end in '...'
610 :param done_message: text appended to the message after exiting
611 :param transient: if True, remove bar and message from screen after exiting;
612 if False (default), the message will remain on the screen without pulsing
613 bar.
614 :param markup: whether to interpret Rich styling markup in the message; if True,
615 the message must already be escaped; defaults False.
616 :returns: Keep-alive spinner to notify user Briefcase is still waiting
617 """
618 is_wait_bar_disabled = not self.is_interactive
619 show_outcome_message = message and (is_wait_bar_disabled or not transient)
620
621 if self._wait_bar is None:
622 self._wait_bar = Progress(
623 TextColumn(" "),
624 BarColumn(bar_width=20, style="black", pulse_style="white"),
625 TextColumn("{task.fields[message]}"),
626 transient=True,
627 disable=is_wait_bar_disabled,
628 console=self._console_impl,
629 )
630 # start=False causes the progress bar to "pulse"
631 # message=None is a sentinel the Wait Bar should be inactive
632 self._wait_bar.add_task("", start=False, message=None)
633
634 self.print(
635 f"{message} started", markup=markup, show=message and is_wait_bar_disabled
636 )
637
638 self.is_console_controlled = True
639 wait_bar_task = self._wait_bar.tasks[0]
640 previous_message = wait_bar_task.fields["message"]
641 self._wait_bar.update(wait_bar_task.id, message=message)
642
643 try:
644 self._wait_bar.start()
645 yield NotDeadYet(console=self)
646 except BaseException as e:
647 # capture BaseException so the message is left on the screen
648 # even if the user sends CTRL+C
649 error_message = "aborted" if isinstance(e, KeyboardInterrupt) else "errored"
650 self.print(
651 f"{message} {error_message}", markup=markup, show=show_outcome_message
652 )
653 raise
654 else:
655 self.print(
656 f"{message} {done_message}", markup=markup, show=show_outcome_message
657 )
658 finally:
659 self._wait_bar.update(wait_bar_task.id, message=previous_message)
660 # Deactivate the Wait Bar if returning to its initial state
661 if previous_message is None:
662 self._wait_bar.stop()
663 self.is_console_controlled = False
664
665 @contextmanager
666 def release_console_control(self):
667 """Context manager to remove console elements such as the Wait Bar.
668
669 This is useful to temporarily release control of the console when, e.g., a
670 process is interrupted or a user needs to be prompted. For instance, when batch
671 scripts are interrupted by CTRL+C in cmd.exe, the user may be prompted to abort
672 the script; so, the console cannot be controlled while such scripts run or the
673 prompt may be hidden from the user.
674 """
675 # Preserve current console state
676 is_output_controlled = self.is_console_controlled
677 is_wait_bar_running = self._wait_bar and self._wait_bar.live.is_started
678
679 # Stop any active dynamic console elements
680 if is_wait_bar_running:
681 self._wait_bar.stop()
682
683 self.is_console_controlled = False
684 try:
685 yield
686 finally:
687 self.is_console_controlled = is_output_controlled
688 # Restore previous console state
689 if is_wait_bar_running:
690 self._wait_bar.start()
691
692 #################################################################
693 # Basic User Input/Output controls
694 #################################################################
695
696 def textwrap(self, text: str, width: int = MAX_TEXT_WIDTH) -> str:
697 """Wrap text to the console width, a default max width, or a specified width."""
698 # textwrap isn't really designed to format text that already contains newlines.
699 # So, instead, break the text by newlines and format each line individually.
700 return "\n".join(
701 "\n".join(textwrap.wrap(line, width)) for line in text.splitlines()
702 )
703
704 def prompt(self, *values, markup=False, **kwargs):
705 """Print to the screen for soliciting user interaction if input enabled.
706
707 :param values: strings to print as the user prompt
708 :param markup: True if prompt contains Rich markup
709 """
710 if self.input_enabled:
711 self.print(*values, markup=markup, stack_offset=4, **kwargs)
712
713 def divider(self, title: str = ""):
714 """Writes a divider with an optional title.
715
716 :param title: Optional; the title to display in the divider.
717 """
718 title = f"-- {title} " if title else ""
719 self.prompt()
720 self.prompt()
721 self.prompt(f"{title}{'-' * (MAX_TEXT_WIDTH - len(title))}", style="bold")
722
723 def input(self, prompt: str, *, markup: bool = False):
724 """A simple input() interface, consistent with the Python builtin input().
725
726 Prompt should be bold if markup is included.
727 """
728 if not self.input_enabled:
729 raise InputDisabled()
730
731 # make the prompt *bold* if it doesn't already contain markup
732 escaped_prompt = f"[bold]{escape(prompt)}[/bold]" if not markup else prompt
733
734 try:
735 # Use underlying Rich input() to read from user
736 input_value = self._console_impl.input(escaped_prompt, markup=True)
737 except EOFError:
738 raise KeyboardInterrupt from None
739
740 self.to_log(prompt)
741 self.to_log(f"User input: {input_value}")
742
743 return input_value
744
745 def input_boolean(self, question: str, default: bool = False) -> bool:
746 """Get a boolean input from user, in the form of y/n.
747
748 The user might press "y" for true or "n" for false. If input is disabled,
749 returns default. If input is disabled and default is *not* defined,
750 InputDisabled is raised.
751
752 :param question: A string message specifying the question to be answered by the
753 user.
754 :param default: (optional) Default response (True/False)
755 :returns: True if the user selected "y", or False if they selected "n".
756 """
757 if default is None:
758 yes_no = "[y/n]"
759 default_text = None
760 elif default:
761 yes_no = "[Y/n]"
762 default_text = "y"
763 else:
764 yes_no = "[y/N]"
765 default_text = "n"
766
767 prompt = f"{question} {yes_no}? "
768
769 result = self.input_selection(
770 prompt=prompt,
771 choices=["y", "n"],
772 default=default_text,
773 error_message="Please enter Y or N",
774 transform=lambda s: s.lower()[:1],
775 )
776 return result == "y"
777
778 def input_selection(
779 self,
780 prompt: str,
781 choices: Iterable[str],
782 default: str | None = None,
783 error_message: str = "Invalid Selection",
784 transform: Callable[[str], str] | None = None,
785 ) -> str:
786 """Prompt the user to select an option from a list of choices.
787
788 :param prompt: The text prompt to display
789 :param choices: The list of available choices
790 :param default: The default choice to select. If None,
791 :param error_message: The error message to display to the user.
792 :param transform: The text transform to apply to any user input before
793 performing any validity checks.
794 """
795 while True:
796 result = self.input_text(prompt, default)
797
798 if transform is not None and result is not None:
799 result = transform(result)
800
801 if result in choices:
802 return result
803
804 self.warning()
805 self.warning(error_message)
806 self.warning()
807
808 def input_text(self, prompt: str, default: str | None = None) -> str:
809 """Prompt the user for text input.
810
811 If no default is specified, the input will be returned as entered.
812
813 The default will also be returned if input is disabled. If input is disabled,
814 and there is no default, InputDisabled will be raised.
815
816 :param prompt: The prompt to display to the user.
817 :param default: (optional) The response to return if the user provides no input.
818 :returns: The content entered by the user.
819 """
820 try:
821 user_input = self.input(prompt)
822 if default is not None and user_input == "":
823 return default
824 except InputDisabled:
825 if default is not None:
826 return default
827 raise
828
829 return user_input
830
831 #################################################################
832 # Advanced User Input/Output controls
833 #################################################################
834
835 def _validate(self, value, validator, usage="Invalid value") -> bool:
836 """Validate a user-provided value.
837
838 A warning message is printed if input is enabled. Otherwise, an exception is
839 raised.
840
841 :param value: The candidate value.
842 :param validator: A validator function (or None, for no validation); accepts a
843 single input (the candidate response), returns True if the value is valid,
844 or raises ValueError() with a debugging message if the candidate value isn't
845 valid.
846 :raises InputDisabled: if console input has been disabled.
847 :returns: True if the value is valid
848 """
849 try:
850 if validator is None or validator(value):
851 return True
852 else:
853 error_msg = repr(value)
854 except ValueError as e:
855 error_msg = str(e)
856
857 if not self.input_enabled:
858 raise InputDisabled(error_msg)
859
860 self.prompt()
861 self.prompt(f"{usage}: {error_msg}", style="bold yellow")
862
863 return False
864
865 def text_question(
866 self,
867 description,
868 intro,
869 default,
870 validator=None,
871 override_value=None,
872 ) -> str:
873 """Ask the user a question whose answer is text.
874
875 :param description: A short description of the question being asked. This text
876 is used in prompts and a header bar prefacing the question.
877 :param intro: An introductory paragraph explaining the question being asked.
878 :param default: The default value if the user hits enter without typing
879 anything.
880 :param validator: (optional) A validator function; accepts a single input (the
881 candidate response), returns True if the answer is valid, or raises
882 ValueError() with a debugging message if the candidate value isn't valid.
883 :param override_value: A preselected answer for the question. This can be used
884 to shortcut asking the question, such as when a command line option provides
885 a value. If provided and valid, the header bar will be displayed, but the
886 intro paragraph and option list will not.
887 :returns: a string, guaranteed to meet the validation criteria of ``validator``
888 """
889 self.divider(title=description)
890
891 if override_value is not None:
892 self.print()
893 self.print(f"Using override value {override_value!r}")
894 if self._validate(
895 override_value,
896 validator,
897 usage=f"Invalid override value for {description}",
898 ):
899 return override_value
900
901 self.prompt()
902 self.prompt(self.textwrap(intro))
903 self.prompt()
904 while True:
905 answer = self.input_text(f"{description} [{default}]: ", default=default)
906
907 if self._validate(answer, validator):
908 return answer
909
910 self.prompt()
911
912 def selection_question(
913 self,
914 description: str,
915 intro: str,
916 options: Iterable[str] | Mapping[Any, str],
917 default: str | None = None,
918 override_value: str | None = None,
919 ) -> Any:
920 """Ask the user a question whose answer requires selecting from a list of
921 options.
922
923 The options are provided as a dictionary, or as a list of items. If a dictionary
924 is provided, the values are the human-readable options, and the keys are the
925 values that will be returned as the selection. The human-readable options will
926 be sorted before display to the user. If a list is provided, the values in the
927 list are both the user-displayed values and the returned value.
928
929 :param description: A short description of the question being asked. This text
930 is used in prompts and a header bar prefacing the question.
931 :param intro: An introductory paragraph explaining the question being asked.
932 :param options: The options to present to the user.
933 :param default: The default option for empty user input. The options for the
934 user start numbering at 1; so, to default to the first item, this should be
935 "1".
936 :param override_value: A preselected answer for the question. This can be used
937 to shortcut asking the question, such as when a command line option provides
938 a value. If provided and valid, the header bar will be displayed, but the
939 intro paragraph and option list will not.
940 :returns: The user's chosen option (the key of that option if options were
941 provided as a dictionary)
942 """
943 self.divider(title=description)
944
945 if override_value is not None:
946 self.print()
947 self.print(f"Using override value {override_value!r}")
948 if self._validate(
949 override_value,
950 validator=lambda c: c in options,
951 usage=f"Invalid override value for {description}",
952 ):
953 return override_value
954
955 self.prompt()
956 self.prompt(self.textwrap(intro))
957 self.prompt()
958
959 if isinstance(options, dict):
960 ordered = list(options.items())
961 else:
962 ordered = list(zip(options, options, strict=True))
963
964 if default is not None:
965 try:
966 default = str([option[0] for option in ordered].index(default) + 1)
967 except ValueError:
968 raise ValueError(f"{default!r} is not a valid default value") from None
969
970 for i, (_, value) in enumerate(ordered, start=1):
971 self.prompt(f" {i}) {value}")
972
973 self.prompt()
974
975 choices = [str(index) for index in range(1, len(ordered) + 1)]
976 index = self.input_selection(
977 prompt=f"{description} [{default}]: " if default else f"{description}: ",
978 choices=choices,
979 error_message="Invalid Selection",
980 default=default,
981 )
982
983 return ordered[int(index) - 1][0]
984
985 def boolean_question(
986 self,
987 description,
988 intro: str,
989 default: bool | None = None,
990 override_value: str | None = None,
991 ) -> bool:
992 """Ask the user a boolean question who's answer requires selecting yes/no.
993
994 :param description: A short description of the question being asked. This text
995 is used in prompts and a header bar prefacing the question.
996 :param intro: An introductory paragraph explaining the question being asked.
997 :param default: The default option for empty user input.
998 :param override_value: A preselected answer for the question. This can be used
999 to shortcut asking the question, such as when a command line option provides
1000 a value. If provided and valid, the header bar will be displayed, but the
1001 intro paragraph and option list will not. Will take the provided string and
1002 attempt to parse into bool
1003 :returns: The user's chosen answer or none if closed without input
1004 """
1005
1006 self.divider(title=description)
1007
1008 if override_value is not None:
1009 self.print()
1010 self.print(f"Using override value {override_value!r}")
1011 try:
1012 return parse_boolean(override_value)
1013 except ValueError as e:
1014 raise ValueError(
1015 f"Invalid override value for {description}: {e}"
1016 ) from None
1017
1018 self.prompt()
1019 self.prompt(self.textwrap(intro))
1020 self.prompt()
1021
1022 return self.input_boolean(description, default=default)