console.py 15 KB

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