console.py 15 KB

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