console.py 8.7 KB

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