console.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. """Functions to communicate to the user via console."""
  2. from __future__ import annotations
  3. from rich.console import Console
  4. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  5. from rich.prompt import Prompt
  6. from reflex.constants import LogLevel
  7. # Console for pretty printing.
  8. _console = Console()
  9. # The current log level.
  10. _LOG_LEVEL = LogLevel.INFO
  11. # Deprecated features who's warning has been printed.
  12. _EMITTED_DEPRECATION_WARNINGS = set()
  13. # Info messages which have been printed.
  14. _EMITTED_INFO = set()
  15. def set_log_level(log_level: LogLevel):
  16. """Set the log level.
  17. Args:
  18. log_level: The log level to set.
  19. """
  20. global _LOG_LEVEL
  21. _LOG_LEVEL = log_level
  22. def is_debug() -> bool:
  23. """Check if the log level is debug.
  24. Returns:
  25. True if the log level is debug.
  26. """
  27. return _LOG_LEVEL <= LogLevel.DEBUG
  28. def print(msg: str, **kwargs):
  29. """Print a message.
  30. Args:
  31. msg: The message to print.
  32. kwargs: Keyword arguments to pass to the print function.
  33. """
  34. _console.print(msg, **kwargs)
  35. def debug(msg: str, **kwargs):
  36. """Print a debug message.
  37. Args:
  38. msg: The debug message.
  39. kwargs: Keyword arguments to pass to the print function.
  40. """
  41. if is_debug():
  42. msg_ = f"[blue]Debug: {msg}[/blue]"
  43. if progress := kwargs.pop("progress", None):
  44. progress.console.print(msg_, **kwargs)
  45. else:
  46. print(msg_, **kwargs)
  47. def info(msg: str, dedupe: bool = False, **kwargs):
  48. """Print an info message.
  49. Args:
  50. msg: The info message.
  51. dedupe: If True, suppress multiple console logs of info message.
  52. kwargs: Keyword arguments to pass to the print function.
  53. """
  54. if _LOG_LEVEL <= LogLevel.INFO:
  55. if dedupe:
  56. if msg in _EMITTED_INFO:
  57. return
  58. else:
  59. _EMITTED_INFO.add(msg)
  60. print(f"[cyan]Info: {msg}[/cyan]", **kwargs)
  61. def success(msg: str, **kwargs):
  62. """Print a success message.
  63. Args:
  64. msg: The success message.
  65. kwargs: Keyword arguments to pass to the print function.
  66. """
  67. if _LOG_LEVEL <= LogLevel.INFO:
  68. print(f"[green]Success: {msg}[/green]", **kwargs)
  69. def log(msg: str, **kwargs):
  70. """Takes a string and logs it to the console.
  71. Args:
  72. msg: The message to log.
  73. kwargs: Keyword arguments to pass to the print function.
  74. """
  75. if _LOG_LEVEL <= LogLevel.INFO:
  76. _console.log(msg, **kwargs)
  77. def rule(title: str, **kwargs):
  78. """Prints a horizontal rule with a title.
  79. Args:
  80. title: The title of the rule.
  81. kwargs: Keyword arguments to pass to the print function.
  82. """
  83. _console.rule(title, **kwargs)
  84. def warn(msg: str, **kwargs):
  85. """Print a warning message.
  86. Args:
  87. msg: The warning message.
  88. kwargs: Keyword arguments to pass to the print function.
  89. """
  90. if _LOG_LEVEL <= LogLevel.WARNING:
  91. print(f"[orange1]Warning: {msg}[/orange1]", **kwargs)
  92. def deprecate(
  93. feature_name: str,
  94. reason: str,
  95. deprecation_version: str,
  96. removal_version: str,
  97. dedupe: bool = True,
  98. **kwargs,
  99. ):
  100. """Print a deprecation warning.
  101. Args:
  102. feature_name: The feature to deprecate.
  103. reason: The reason for deprecation.
  104. deprecation_version: The version the feature was deprecated
  105. removal_version: The version the deprecated feature will be removed
  106. dedupe: If True, suppress multiple console logs of deprecation message.
  107. kwargs: Keyword arguments to pass to the print function.
  108. """
  109. if feature_name not in _EMITTED_DEPRECATION_WARNINGS:
  110. msg = (
  111. f"{feature_name} has been deprecated in version {deprecation_version} {reason.rstrip('.')}. It will be completely "
  112. f"removed in {removal_version}"
  113. )
  114. if _LOG_LEVEL <= LogLevel.WARNING:
  115. print(f"[yellow]DeprecationWarning: {msg}[/yellow]", **kwargs)
  116. if dedupe:
  117. _EMITTED_DEPRECATION_WARNINGS.add(feature_name)
  118. def error(msg: str, **kwargs):
  119. """Print an error message.
  120. Args:
  121. msg: The error message.
  122. kwargs: Keyword arguments to pass to the print function.
  123. """
  124. if _LOG_LEVEL <= LogLevel.ERROR:
  125. print(f"[red]{msg}[/red]", **kwargs)
  126. def ask(
  127. question: str,
  128. choices: list[str] | None = None,
  129. default: str | None = None,
  130. show_choices: bool = True,
  131. ) -> str:
  132. """Takes a prompt question and optionally a list of choices
  133. and returns the user input.
  134. Args:
  135. question: The question to ask the user.
  136. choices: A list of choices to select from.
  137. default: The default option selected.
  138. show_choices: Whether to show the choices.
  139. Returns:
  140. A string with the user input.
  141. """
  142. return Prompt.ask(
  143. question, choices=choices, default=default, show_choices=show_choices
  144. ) # type: ignore
  145. def progress():
  146. """Create a new progress bar.
  147. Returns:
  148. A new progress bar.
  149. """
  150. return Progress(
  151. *Progress.get_default_columns()[:-1],
  152. MofNCompleteColumn(),
  153. TimeElapsedColumn(),
  154. )
  155. def status(*args, **kwargs):
  156. """Create a status with a spinner.
  157. Args:
  158. *args: Args to pass to the status.
  159. **kwargs: Kwargs to pass to the status.
  160. Returns:
  161. A new status.
  162. """
  163. return _console.status(*args, **kwargs)