console.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. """Functions to communicate to the user via console."""
  2. from __future__ import annotations
  3. import contextlib
  4. import dataclasses
  5. import inspect
  6. import os
  7. import re
  8. import shutil
  9. import sys
  10. import time
  11. import types
  12. from dataclasses import dataclass
  13. from pathlib import Path
  14. from types import FrameType
  15. from termcolor import colored
  16. from reflex.constants import LogLevel
  17. def _get_terminal_width() -> int:
  18. try:
  19. # First try using shutil, which is more reliable across platforms
  20. return shutil.get_terminal_size().columns
  21. except (AttributeError, ValueError, OSError):
  22. try:
  23. # Fallback to environment variables
  24. return int(os.environ.get("COLUMNS", os.environ.get("TERM_WIDTH", 80)))
  25. except (TypeError, ValueError):
  26. # Default fallback
  27. return 80
  28. @dataclasses.dataclass
  29. class Reprinter:
  30. """A class that reprints text on the terminal."""
  31. _text: str = dataclasses.field(default="", init=False)
  32. @staticmethod
  33. def _moveup(lines: int):
  34. for _ in range(lines):
  35. sys.stdout.write("\x1b[A")
  36. def reprint(self, text: str):
  37. """Reprint the text.
  38. Args:
  39. text: The text to print
  40. """
  41. if not text.endswith("\n"):
  42. text += "\n"
  43. # Clear previous text by overwritig non-spaces with spaces
  44. self._moveup(self._text.count("\n"))
  45. sys.stdout.write(re.sub(r"[^\s]", " ", self._text))
  46. # Print new text
  47. lines = min(self._text.count("\n"), text.count("\n"))
  48. self._moveup(lines)
  49. sys.stdout.write(text)
  50. sys.stdout.flush()
  51. self._text = text
  52. def finish(self):
  53. """Finish printing the text."""
  54. self._moveup(1)
  55. @dataclass
  56. class Status:
  57. """A status class for displaying a spinner."""
  58. message: str = "Loading"
  59. _reprinter: Reprinter | None = None
  60. def __enter__(self):
  61. """Enter the context manager.
  62. Returns:
  63. The status object.
  64. """
  65. self._reprinter = Reprinter()
  66. return self
  67. def __exit__(
  68. self,
  69. exc_type: type[BaseException] | None,
  70. exc_value: BaseException | None,
  71. traceback: types.TracebackType | None,
  72. ):
  73. """Exit the context manager.
  74. Args:
  75. exc_type: The exception type.
  76. exc_value: The exception value.
  77. traceback: The traceback.
  78. """
  79. if self._reprinter:
  80. self._reprinter.reprint("")
  81. self._reprinter.finish()
  82. self._reprinter = None
  83. def update(self, msg: str, **kwargs):
  84. """Update the status spinner.
  85. Args:
  86. msg: The message to display.
  87. kwargs: Keyword arguments to pass to the print function.
  88. """
  89. if self._reprinter:
  90. self._reprinter.reprint(f"O {msg}")
  91. @dataclass
  92. class Console:
  93. """A console class for pretty printing."""
  94. def print(self, msg: str, **kwargs):
  95. """Print a message.
  96. Args:
  97. msg: The message to print.
  98. kwargs: Keyword arguments to pass to the print function.
  99. """
  100. from builtins import print
  101. color = kwargs.pop("color", None)
  102. bold = kwargs.pop("bold", False)
  103. if color or bold:
  104. msg = colored(msg, color, attrs=["bold"] if bold else [])
  105. print(msg, **kwargs) # noqa: T201
  106. def rule(self, title: str, **kwargs):
  107. """Prints a horizontal rule with a title.
  108. Args:
  109. title: The title of the rule.
  110. kwargs: Keyword arguments to pass to the print function.
  111. """
  112. terminal_width = _get_terminal_width()
  113. remaining_width = (
  114. terminal_width - len(title) - 4
  115. ) # 4 for the spaces and characters around the title
  116. left_padding = remaining_width // 2
  117. right_padding = remaining_width - left_padding
  118. rule_line = "─" * left_padding + f" {title} " + "─" * right_padding
  119. self.print(rule_line, **kwargs)
  120. def status(self, *args, **kwargs):
  121. """Create a status.
  122. Args:
  123. *args: Args to pass to the status.
  124. **kwargs: Kwargs to pass to the status.
  125. Returns:
  126. A new status.
  127. """
  128. return Status(*args, **kwargs)
  129. class Prompt:
  130. """A class for prompting the user for input."""
  131. @staticmethod
  132. def ask(
  133. question: str,
  134. choices: list[str] | None = None,
  135. default: str | None = None,
  136. show_choices: bool = True,
  137. ) -> str | None:
  138. """Ask the user a question.
  139. Args:
  140. question: The question to ask the user.
  141. choices: A list of choices to select from.
  142. default: The default option selected.
  143. show_choices: Whether to show the choices.
  144. Returns:
  145. The user's response or the default value.
  146. """
  147. prompt = question
  148. if choices and show_choices:
  149. choice_str = "/".join(choices)
  150. prompt = f"{question} [{choice_str}]"
  151. if default is not None:
  152. prompt = f"{prompt} ({default})"
  153. prompt = f"{prompt}: "
  154. response = input(prompt)
  155. if not response and default is not None:
  156. return default
  157. if choices and response not in choices:
  158. print(f"Please choose from: {', '.join(choices)}")
  159. return Prompt.ask(question, choices, default, show_choices)
  160. return response
  161. # Console for pretty printing.
  162. _console = Console()
  163. # The current log level.
  164. _LOG_LEVEL = LogLevel.INFO
  165. # Deprecated features who's warning has been printed.
  166. _EMITTED_DEPRECATION_WARNINGS = set()
  167. # Info messages which have been printed.
  168. _EMITTED_INFO = set()
  169. # Warnings which have been printed.
  170. _EMIITED_WARNINGS = set()
  171. # Errors which have been printed.
  172. _EMITTED_ERRORS = set()
  173. # Success messages which have been printed.
  174. _EMITTED_SUCCESS = set()
  175. # Debug messages which have been printed.
  176. _EMITTED_DEBUG = set()
  177. # Logs which have been printed.
  178. _EMITTED_LOGS = set()
  179. # Prints which have been printed.
  180. _EMITTED_PRINTS = set()
  181. def set_log_level(log_level: LogLevel):
  182. """Set the log level.
  183. Args:
  184. log_level: The log level to set.
  185. Raises:
  186. TypeError: If the log level is a string.
  187. """
  188. if not isinstance(log_level, LogLevel):
  189. raise TypeError(
  190. f"log_level must be a LogLevel enum value, got {log_level} of type {type(log_level)} instead."
  191. )
  192. global _LOG_LEVEL
  193. if log_level != _LOG_LEVEL:
  194. # Set the loglevel persistenly for subprocesses.
  195. os.environ["LOGLEVEL"] = log_level.value
  196. _LOG_LEVEL = log_level
  197. def is_debug() -> bool:
  198. """Check if the log level is debug.
  199. Returns:
  200. True if the log level is debug.
  201. """
  202. return _LOG_LEVEL <= LogLevel.DEBUG
  203. def print(msg: str, dedupe: bool = False, **kwargs):
  204. """Print a message.
  205. Args:
  206. msg: The message to print.
  207. dedupe: If True, suppress multiple console logs of print message.
  208. kwargs: Keyword arguments to pass to the print function.
  209. """
  210. if dedupe:
  211. if msg in _EMITTED_PRINTS:
  212. return
  213. else:
  214. _EMITTED_PRINTS.add(msg)
  215. _console.print(msg, **kwargs)
  216. def debug(msg: str, dedupe: bool = False, **kwargs):
  217. """Print a debug message.
  218. Args:
  219. msg: The debug message.
  220. dedupe: If True, suppress multiple console logs of debug message.
  221. kwargs: Keyword arguments to pass to the print function.
  222. """
  223. if is_debug():
  224. if dedupe:
  225. if msg in _EMITTED_DEBUG:
  226. return
  227. else:
  228. _EMITTED_DEBUG.add(msg)
  229. kwargs.setdefault("color", "purple")
  230. print(msg, **kwargs)
  231. def info(msg: str, dedupe: bool = False, **kwargs):
  232. """Print an info message.
  233. Args:
  234. msg: The info message.
  235. dedupe: If True, suppress multiple console logs of info message.
  236. kwargs: Keyword arguments to pass to the print function.
  237. """
  238. if _LOG_LEVEL <= LogLevel.INFO:
  239. if dedupe:
  240. if msg in _EMITTED_INFO:
  241. return
  242. else:
  243. _EMITTED_INFO.add(msg)
  244. kwargs.setdefault("color", "cyan")
  245. print(f"Info: {msg}", **kwargs)
  246. def success(msg: str, dedupe: bool = False, **kwargs):
  247. """Print a success message.
  248. Args:
  249. msg: The success message.
  250. dedupe: If True, suppress multiple console logs of success message.
  251. kwargs: Keyword arguments to pass to the print function.
  252. """
  253. if _LOG_LEVEL <= LogLevel.INFO:
  254. if dedupe:
  255. if msg in _EMITTED_SUCCESS:
  256. return
  257. else:
  258. _EMITTED_SUCCESS.add(msg)
  259. kwargs.setdefault("color", "green")
  260. print(f"Success: {msg}", **kwargs)
  261. def log(msg: str, dedupe: bool = False, **kwargs):
  262. """Takes a string and logs it to the console.
  263. Args:
  264. msg: The message to log.
  265. dedupe: If True, suppress multiple console logs of log message.
  266. kwargs: Keyword arguments to pass to the print function.
  267. """
  268. if _LOG_LEVEL <= LogLevel.INFO:
  269. if dedupe:
  270. if msg in _EMITTED_LOGS:
  271. return
  272. else:
  273. _EMITTED_LOGS.add(msg)
  274. _console.print(msg, **kwargs)
  275. def rule(title: str, **kwargs):
  276. """Prints a horizontal rule with a title.
  277. Args:
  278. title: The title of the rule.
  279. kwargs: Keyword arguments to pass to the print function.
  280. """
  281. _console.rule(title, **kwargs)
  282. def warn(msg: str, dedupe: bool = False, **kwargs):
  283. """Print a warning message.
  284. Args:
  285. msg: The warning message.
  286. dedupe: If True, suppress multiple console logs of warning message.
  287. kwargs: Keyword arguments to pass to the print function.
  288. """
  289. if _LOG_LEVEL <= LogLevel.WARNING:
  290. if dedupe:
  291. if msg in _EMIITED_WARNINGS:
  292. return
  293. else:
  294. _EMIITED_WARNINGS.add(msg)
  295. kwargs.setdefault("color", "light_yellow")
  296. print(f"Warning: {msg}", **kwargs)
  297. def _get_first_non_framework_frame() -> FrameType | None:
  298. import click
  299. import typer
  300. import typing_extensions
  301. import reflex as rx
  302. # Exclude utility modules that should never be the source of deprecated reflex usage.
  303. exclude_modules = [click, rx, typer, typing_extensions]
  304. exclude_roots = [
  305. p.parent.resolve()
  306. if (p := Path(m.__file__)).name == "__init__.py" # pyright: ignore [reportArgumentType]
  307. else p.resolve()
  308. for m in exclude_modules
  309. ]
  310. # Specifically exclude the reflex cli module.
  311. if reflex_bin := shutil.which(b"reflex"):
  312. exclude_roots.append(Path(reflex_bin.decode()))
  313. frame = inspect.currentframe()
  314. while frame := frame and frame.f_back:
  315. frame_path = Path(inspect.getfile(frame)).resolve()
  316. if not any(frame_path.is_relative_to(root) for root in exclude_roots):
  317. break
  318. return frame
  319. def deprecate(
  320. feature_name: str,
  321. reason: str,
  322. deprecation_version: str,
  323. removal_version: str,
  324. dedupe: bool = True,
  325. **kwargs,
  326. ):
  327. """Print a deprecation warning.
  328. Args:
  329. feature_name: The feature to deprecate.
  330. reason: The reason for deprecation.
  331. deprecation_version: The version the feature was deprecated
  332. removal_version: The version the deprecated feature will be removed
  333. dedupe: If True, suppress multiple console logs of deprecation message.
  334. kwargs: Keyword arguments to pass to the print function.
  335. """
  336. dedupe_key = feature_name
  337. loc = ""
  338. # See if we can find where the deprecation exists in "user code"
  339. origin_frame = _get_first_non_framework_frame()
  340. if origin_frame is not None:
  341. filename = Path(origin_frame.f_code.co_filename)
  342. if filename.is_relative_to(Path.cwd()):
  343. filename = filename.relative_to(Path.cwd())
  344. loc = f"{filename}:{origin_frame.f_lineno}"
  345. dedupe_key = f"{dedupe_key} {loc}"
  346. if dedupe_key not in _EMITTED_DEPRECATION_WARNINGS:
  347. msg = (
  348. f"{feature_name} has been deprecated in version {deprecation_version}. {reason.rstrip('.').lstrip('. ')}. It will be completely "
  349. f"removed in {removal_version}. ({loc})"
  350. )
  351. if _LOG_LEVEL <= LogLevel.WARNING:
  352. kwargs.setdefault("color", "yellow")
  353. print(f"DeprecationWarning: {msg}", **kwargs)
  354. if dedupe:
  355. _EMITTED_DEPRECATION_WARNINGS.add(dedupe_key)
  356. def error(msg: str, dedupe: bool = False, **kwargs):
  357. """Print an error message.
  358. Args:
  359. msg: The error message.
  360. dedupe: If True, suppress multiple console logs of error message.
  361. kwargs: Keyword arguments to pass to the print function.
  362. """
  363. if _LOG_LEVEL <= LogLevel.ERROR:
  364. if dedupe:
  365. if msg in _EMITTED_ERRORS:
  366. return
  367. else:
  368. _EMITTED_ERRORS.add(msg)
  369. kwargs.setdefault("color", "red")
  370. print(f"{msg}", **kwargs)
  371. def ask(
  372. question: str,
  373. choices: list[str] | None = None,
  374. default: str | None = None,
  375. show_choices: bool = True,
  376. ) -> str | None:
  377. """Takes a prompt question and optionally a list of choices
  378. and returns the user input.
  379. Args:
  380. question: The question to ask the user.
  381. choices: A list of choices to select from.
  382. default: The default option selected.
  383. show_choices: Whether to show the choices.
  384. Returns:
  385. A string with the user input.
  386. """
  387. return Prompt.ask(
  388. question, choices=choices, default=default, show_choices=show_choices
  389. )
  390. def status(*args, **kwargs):
  391. """Create a status with a spinner.
  392. Args:
  393. *args: Args to pass to the status.
  394. **kwargs: Kwargs to pass to the status.
  395. Returns:
  396. A new status.
  397. """
  398. return _console.status(*args, **kwargs)
  399. @contextlib.contextmanager
  400. def timing(msg: str):
  401. """Create a context manager to time a block of code.
  402. Args:
  403. msg: The message to display.
  404. Yields:
  405. None.
  406. """
  407. start = time.time()
  408. try:
  409. yield
  410. finally:
  411. debug(f"[timing] {msg}: {time.time() - start:.2f}s", color="white")