console.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. """Functions to communicate to the user via console."""
  2. from __future__ import annotations
  3. import contextlib
  4. import inspect
  5. import shutil
  6. import time
  7. from pathlib import Path
  8. from types import FrameType
  9. from rich.console import Console
  10. from rich.progress import MofNCompleteColumn, Progress, TimeElapsedColumn
  11. from rich.prompt import Prompt
  12. from reflex.constants import LogLevel
  13. # Console for pretty printing.
  14. _console = Console()
  15. # The current log level.
  16. _LOG_LEVEL = LogLevel.INFO
  17. # Deprecated features who's warning has been printed.
  18. _EMITTED_DEPRECATION_WARNINGS = set()
  19. # Info messages which have been printed.
  20. _EMITTED_INFO = set()
  21. # Warnings which have been printed.
  22. _EMIITED_WARNINGS = set()
  23. # Errors which have been printed.
  24. _EMITTED_ERRORS = set()
  25. # Success messages which have been printed.
  26. _EMITTED_SUCCESS = set()
  27. # Debug messages which have been printed.
  28. _EMITTED_DEBUG = set()
  29. # Logs which have been printed.
  30. _EMITTED_LOGS = set()
  31. # Prints which have been printed.
  32. _EMITTED_PRINTS = set()
  33. def set_log_level(log_level: LogLevel):
  34. """Set the log level.
  35. Args:
  36. log_level: The log level to set.
  37. Raises:
  38. TypeError: If the log level is a string.
  39. """
  40. if not isinstance(log_level, LogLevel):
  41. raise TypeError(
  42. f"log_level must be a LogLevel enum value, got {log_level} of type {type(log_level)} instead."
  43. )
  44. global _LOG_LEVEL
  45. _LOG_LEVEL = log_level
  46. def is_debug() -> bool:
  47. """Check if the log level is debug.
  48. Returns:
  49. True if the log level is debug.
  50. """
  51. return _LOG_LEVEL <= LogLevel.DEBUG
  52. def print(msg: str, dedupe: bool = False, **kwargs):
  53. """Print a message.
  54. Args:
  55. msg: The message to print.
  56. dedupe: If True, suppress multiple console logs of print message.
  57. kwargs: Keyword arguments to pass to the print function.
  58. """
  59. if dedupe:
  60. if msg in _EMITTED_PRINTS:
  61. return
  62. else:
  63. _EMITTED_PRINTS.add(msg)
  64. _console.print(msg, **kwargs)
  65. def debug(msg: str, dedupe: bool = False, **kwargs):
  66. """Print a debug message.
  67. Args:
  68. msg: The debug message.
  69. dedupe: If True, suppress multiple console logs of debug message.
  70. kwargs: Keyword arguments to pass to the print function.
  71. """
  72. if is_debug():
  73. msg_ = f"[purple]Debug: {msg}[/purple]"
  74. if dedupe:
  75. if msg_ in _EMITTED_DEBUG:
  76. return
  77. else:
  78. _EMITTED_DEBUG.add(msg_)
  79. if progress := kwargs.pop("progress", None):
  80. progress.console.print(msg_, **kwargs)
  81. else:
  82. print(msg_, **kwargs)
  83. def info(msg: str, dedupe: bool = False, **kwargs):
  84. """Print an info message.
  85. Args:
  86. msg: The info message.
  87. dedupe: If True, suppress multiple console logs of info message.
  88. kwargs: Keyword arguments to pass to the print function.
  89. """
  90. if _LOG_LEVEL <= LogLevel.INFO:
  91. if dedupe:
  92. if msg in _EMITTED_INFO:
  93. return
  94. else:
  95. _EMITTED_INFO.add(msg)
  96. print(f"[cyan]Info: {msg}[/cyan]", **kwargs)
  97. def success(msg: str, dedupe: bool = False, **kwargs):
  98. """Print a success message.
  99. Args:
  100. msg: The success message.
  101. dedupe: If True, suppress multiple console logs of success message.
  102. kwargs: Keyword arguments to pass to the print function.
  103. """
  104. if _LOG_LEVEL <= LogLevel.INFO:
  105. if dedupe:
  106. if msg in _EMITTED_SUCCESS:
  107. return
  108. else:
  109. _EMITTED_SUCCESS.add(msg)
  110. print(f"[green]Success: {msg}[/green]", **kwargs)
  111. def log(msg: str, dedupe: bool = False, **kwargs):
  112. """Takes a string and logs it to the console.
  113. Args:
  114. msg: The message to log.
  115. dedupe: If True, suppress multiple console logs of log message.
  116. kwargs: Keyword arguments to pass to the print function.
  117. """
  118. if _LOG_LEVEL <= LogLevel.INFO:
  119. if dedupe:
  120. if msg in _EMITTED_LOGS:
  121. return
  122. else:
  123. _EMITTED_LOGS.add(msg)
  124. _console.log(msg, **kwargs)
  125. def rule(title: str, **kwargs):
  126. """Prints a horizontal rule with a title.
  127. Args:
  128. title: The title of the rule.
  129. kwargs: Keyword arguments to pass to the print function.
  130. """
  131. _console.rule(title, **kwargs)
  132. def warn(msg: str, dedupe: bool = False, **kwargs):
  133. """Print a warning message.
  134. Args:
  135. msg: The warning message.
  136. dedupe: If True, suppress multiple console logs of warning message.
  137. kwargs: Keyword arguments to pass to the print function.
  138. """
  139. if _LOG_LEVEL <= LogLevel.WARNING:
  140. if dedupe:
  141. if msg in _EMIITED_WARNINGS:
  142. return
  143. else:
  144. _EMIITED_WARNINGS.add(msg)
  145. print(f"[orange1]Warning: {msg}[/orange1]", **kwargs)
  146. def _get_first_non_framework_frame() -> FrameType | None:
  147. import click
  148. import typer
  149. import typing_extensions
  150. import reflex as rx
  151. # Exclude utility modules that should never be the source of deprecated reflex usage.
  152. exclude_modules = [click, rx, typer, typing_extensions]
  153. exclude_roots = [
  154. p.parent.resolve()
  155. if (p := Path(m.__file__)).name == "__init__.py" # pyright: ignore [reportArgumentType]
  156. else p.resolve()
  157. for m in exclude_modules
  158. ]
  159. # Specifically exclude the reflex cli module.
  160. if reflex_bin := shutil.which(b"reflex"):
  161. exclude_roots.append(Path(reflex_bin.decode()))
  162. frame = inspect.currentframe()
  163. while frame := frame and frame.f_back:
  164. frame_path = Path(inspect.getfile(frame)).resolve()
  165. if not any(frame_path.is_relative_to(root) for root in exclude_roots):
  166. break
  167. return frame
  168. def deprecate(
  169. feature_name: str,
  170. reason: str,
  171. deprecation_version: str,
  172. removal_version: str,
  173. dedupe: bool = True,
  174. **kwargs,
  175. ):
  176. """Print a deprecation warning.
  177. Args:
  178. feature_name: The feature to deprecate.
  179. reason: The reason for deprecation.
  180. deprecation_version: The version the feature was deprecated
  181. removal_version: The version the deprecated feature will be removed
  182. dedupe: If True, suppress multiple console logs of deprecation message.
  183. kwargs: Keyword arguments to pass to the print function.
  184. """
  185. dedupe_key = feature_name
  186. loc = ""
  187. # See if we can find where the deprecation exists in "user code"
  188. origin_frame = _get_first_non_framework_frame()
  189. if origin_frame is not None:
  190. filename = Path(origin_frame.f_code.co_filename)
  191. if filename.is_relative_to(Path.cwd()):
  192. filename = filename.relative_to(Path.cwd())
  193. loc = f"{filename}:{origin_frame.f_lineno}"
  194. dedupe_key = f"{dedupe_key} {loc}"
  195. if dedupe_key not in _EMITTED_DEPRECATION_WARNINGS:
  196. msg = (
  197. f"{feature_name} has been deprecated in version {deprecation_version} {reason.rstrip('.')}. It will be completely "
  198. f"removed in {removal_version}. ({loc})"
  199. )
  200. if _LOG_LEVEL <= LogLevel.WARNING:
  201. print(f"[yellow]DeprecationWarning: {msg}[/yellow]", **kwargs)
  202. if dedupe:
  203. _EMITTED_DEPRECATION_WARNINGS.add(dedupe_key)
  204. def error(msg: str, dedupe: bool = False, **kwargs):
  205. """Print an error message.
  206. Args:
  207. msg: The error message.
  208. dedupe: If True, suppress multiple console logs of error message.
  209. kwargs: Keyword arguments to pass to the print function.
  210. """
  211. if _LOG_LEVEL <= LogLevel.ERROR:
  212. if dedupe:
  213. if msg in _EMITTED_ERRORS:
  214. return
  215. else:
  216. _EMITTED_ERRORS.add(msg)
  217. print(f"[red]{msg}[/red]", **kwargs)
  218. def ask(
  219. question: str,
  220. choices: list[str] | None = None,
  221. default: str | None = None,
  222. show_choices: bool = True,
  223. ) -> str | None:
  224. """Takes a prompt question and optionally a list of choices
  225. and returns the user input.
  226. Args:
  227. question: The question to ask the user.
  228. choices: A list of choices to select from.
  229. default: The default option selected.
  230. show_choices: Whether to show the choices.
  231. Returns:
  232. A string with the user input.
  233. """
  234. return Prompt.ask(
  235. question, choices=choices, default=default, show_choices=show_choices
  236. )
  237. def progress():
  238. """Create a new progress bar.
  239. Returns:
  240. A new progress bar.
  241. """
  242. return Progress(
  243. *Progress.get_default_columns()[:-1],
  244. MofNCompleteColumn(),
  245. TimeElapsedColumn(),
  246. )
  247. def status(*args, **kwargs):
  248. """Create a status with a spinner.
  249. Args:
  250. *args: Args to pass to the status.
  251. **kwargs: Kwargs to pass to the status.
  252. Returns:
  253. A new status.
  254. """
  255. return _console.status(*args, **kwargs)
  256. @contextlib.contextmanager
  257. def timing(msg: str):
  258. """Create a context manager to time a block of code.
  259. Args:
  260. msg: The message to display.
  261. Yields:
  262. None.
  263. """
  264. start = time.time()
  265. try:
  266. yield
  267. finally:
  268. debug(f"[white]\\[timing] {msg}: {time.time() - start:.2f}s[/white]")