console.py 9.2 KB

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