console.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. # Warnings which have been printed.
  16. _EMIITED_WARNINGS = set()
  17. # Errors which have been printed.
  18. _EMITTED_ERRORS = set()
  19. # Success messages which have been printed.
  20. _EMITTED_SUCCESS = set()
  21. # Debug messages which have been printed.
  22. _EMITTED_DEBUG = set()
  23. # Logs which have been printed.
  24. _EMITTED_LOGS = set()
  25. # Prints which have been printed.
  26. _EMITTED_PRINTS = set()
  27. def set_log_level(log_level: LogLevel):
  28. """Set the log level.
  29. Args:
  30. log_level: The log level to set.
  31. Raises:
  32. ValueError: If the log level is invalid.
  33. """
  34. if not isinstance(log_level, LogLevel):
  35. raise ValueError("Invalid log level")
  36. global _LOG_LEVEL
  37. _LOG_LEVEL = log_level
  38. def is_debug() -> bool:
  39. """Check if the log level is debug.
  40. Returns:
  41. True if the log level is debug.
  42. """
  43. return _LOG_LEVEL <= LogLevel.DEBUG
  44. def print(msg: str, dedupe: bool = False, **kwargs):
  45. """Print a message.
  46. Args:
  47. msg: The message to print.
  48. dedupe: If True, suppress multiple console logs of print message.
  49. kwargs: Keyword arguments to pass to the print function.
  50. """
  51. if dedupe:
  52. if msg in _EMITTED_PRINTS:
  53. return
  54. else:
  55. _EMITTED_PRINTS.add(msg)
  56. _console.print(msg, **kwargs)
  57. def debug(msg: str, dedupe: bool = False, **kwargs):
  58. """Print a debug message.
  59. Args:
  60. msg: The debug message.
  61. dedupe: If True, suppress multiple console logs of debug message.
  62. kwargs: Keyword arguments to pass to the print function.
  63. """
  64. if is_debug():
  65. msg_ = f"[purple]Debug: {msg}[/purple]"
  66. if dedupe:
  67. if msg_ in _EMITTED_DEBUG:
  68. return
  69. else:
  70. _EMITTED_DEBUG.add(msg_)
  71. if progress := kwargs.pop("progress", None):
  72. progress.console.print(msg_, **kwargs)
  73. else:
  74. print(msg_, **kwargs)
  75. def info(msg: str, dedupe: bool = False, **kwargs):
  76. """Print an info message.
  77. Args:
  78. msg: The info message.
  79. dedupe: If True, suppress multiple console logs of info message.
  80. kwargs: Keyword arguments to pass to the print function.
  81. """
  82. if _LOG_LEVEL <= LogLevel.INFO:
  83. if dedupe:
  84. if msg in _EMITTED_INFO:
  85. return
  86. else:
  87. _EMITTED_INFO.add(msg)
  88. print(f"[cyan]Info: {msg}[/cyan]", **kwargs)
  89. def success(msg: str, dedupe: bool = False, **kwargs):
  90. """Print a success message.
  91. Args:
  92. msg: The success message.
  93. dedupe: If True, suppress multiple console logs of success message.
  94. kwargs: Keyword arguments to pass to the print function.
  95. """
  96. if _LOG_LEVEL <= LogLevel.INFO:
  97. if dedupe:
  98. if msg in _EMITTED_SUCCESS:
  99. return
  100. else:
  101. _EMITTED_SUCCESS.add(msg)
  102. print(f"[green]Success: {msg}[/green]", **kwargs)
  103. def log(msg: str, dedupe: bool = False, **kwargs):
  104. """Takes a string and logs it to the console.
  105. Args:
  106. msg: The message to log.
  107. dedupe: If True, suppress multiple console logs of log message.
  108. kwargs: Keyword arguments to pass to the print function.
  109. """
  110. if _LOG_LEVEL <= LogLevel.INFO:
  111. if dedupe:
  112. if msg in _EMITTED_LOGS:
  113. return
  114. else:
  115. _EMITTED_LOGS.add(msg)
  116. _console.log(msg, **kwargs)
  117. def rule(title: str, **kwargs):
  118. """Prints a horizontal rule with a title.
  119. Args:
  120. title: The title of the rule.
  121. kwargs: Keyword arguments to pass to the print function.
  122. """
  123. _console.rule(title, **kwargs)
  124. def warn(msg: str, dedupe: bool = False, **kwargs):
  125. """Print a warning message.
  126. Args:
  127. msg: The warning message.
  128. dedupe: If True, suppress multiple console logs of warning message.
  129. kwargs: Keyword arguments to pass to the print function.
  130. """
  131. if _LOG_LEVEL <= LogLevel.WARNING:
  132. if dedupe:
  133. if msg in _EMIITED_WARNINGS:
  134. return
  135. else:
  136. _EMIITED_WARNINGS.add(msg)
  137. print(f"[orange1]Warning: {msg}[/orange1]", **kwargs)
  138. def deprecate(
  139. feature_name: str,
  140. reason: str,
  141. deprecation_version: str,
  142. removal_version: str,
  143. dedupe: bool = True,
  144. **kwargs,
  145. ):
  146. """Print a deprecation warning.
  147. Args:
  148. feature_name: The feature to deprecate.
  149. reason: The reason for deprecation.
  150. deprecation_version: The version the feature was deprecated
  151. removal_version: The version the deprecated feature will be removed
  152. dedupe: If True, suppress multiple console logs of deprecation message.
  153. kwargs: Keyword arguments to pass to the print function.
  154. """
  155. if feature_name not in _EMITTED_DEPRECATION_WARNINGS:
  156. msg = (
  157. f"{feature_name} has been deprecated in version {deprecation_version} {reason.rstrip('.')}. It will be completely "
  158. f"removed in {removal_version}"
  159. )
  160. if _LOG_LEVEL <= LogLevel.WARNING:
  161. print(f"[yellow]DeprecationWarning: {msg}[/yellow]", **kwargs)
  162. if dedupe:
  163. _EMITTED_DEPRECATION_WARNINGS.add(feature_name)
  164. def error(msg: str, dedupe: bool = False, **kwargs):
  165. """Print an error message.
  166. Args:
  167. msg: The error message.
  168. dedupe: If True, suppress multiple console logs of error message.
  169. kwargs: Keyword arguments to pass to the print function.
  170. """
  171. if _LOG_LEVEL <= LogLevel.ERROR:
  172. if dedupe:
  173. if msg in _EMITTED_ERRORS:
  174. return
  175. else:
  176. _EMITTED_ERRORS.add(msg)
  177. print(f"[red]{msg}[/red]", **kwargs)
  178. def ask(
  179. question: str,
  180. choices: list[str] | None = None,
  181. default: str | None = None,
  182. show_choices: bool = True,
  183. ) -> str:
  184. """Takes a prompt question and optionally a list of choices
  185. and returns the user input.
  186. Args:
  187. question: The question to ask the user.
  188. choices: A list of choices to select from.
  189. default: The default option selected.
  190. show_choices: Whether to show the choices.
  191. Returns:
  192. A string with the user input.
  193. """
  194. return Prompt.ask(
  195. question, choices=choices, default=default, show_choices=show_choices
  196. ) # type: ignore
  197. def progress():
  198. """Create a new progress bar.
  199. Returns:
  200. A new progress bar.
  201. """
  202. return Progress(
  203. *Progress.get_default_columns()[:-1],
  204. MofNCompleteColumn(),
  205. TimeElapsedColumn(),
  206. )
  207. def status(*args, **kwargs):
  208. """Create a status with a spinner.
  209. Args:
  210. *args: Args to pass to the status.
  211. **kwargs: Kwargs to pass to the status.
  212. Returns:
  213. A new status.
  214. """
  215. return _console.status(*args, **kwargs)