globals.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import typing
  2. import typing as t
  3. from threading import local
  4. if t.TYPE_CHECKING:
  5. import typing_extensions as te
  6. from .core import Context
  7. _local = local()
  8. @typing.overload
  9. def get_current_context(silent: "te.Literal[False]" = False) -> "Context":
  10. ...
  11. @typing.overload
  12. def get_current_context(silent: bool = ...) -> t.Optional["Context"]:
  13. ...
  14. def get_current_context(silent: bool = False) -> t.Optional["Context"]:
  15. """Returns the current click context. This can be used as a way to
  16. access the current context object from anywhere. This is a more implicit
  17. alternative to the :func:`pass_context` decorator. This function is
  18. primarily useful for helpers such as :func:`echo` which might be
  19. interested in changing its behavior based on the current context.
  20. To push the current context, :meth:`Context.scope` can be used.
  21. .. versionadded:: 5.0
  22. :param silent: if set to `True` the return value is `None` if no context
  23. is available. The default behavior is to raise a
  24. :exc:`RuntimeError`.
  25. """
  26. try:
  27. return t.cast("Context", _local.stack[-1])
  28. except (AttributeError, IndexError) as e:
  29. if not silent:
  30. raise RuntimeError("There is no active click context.") from e
  31. return None
  32. def push_context(ctx: "Context") -> None:
  33. """Pushes a new context to the current stack."""
  34. _local.__dict__.setdefault("stack", []).append(ctx)
  35. def pop_context() -> None:
  36. """Removes the top level from the stack."""
  37. _local.stack.pop()
  38. def resolve_color_default(color: t.Optional[bool] = None) -> t.Optional[bool]:
  39. """Internal helper to get the default value of the color flag. If a
  40. value is passed it's returned unchanged, otherwise it's looked up from
  41. the current context.
  42. """
  43. if color is not None:
  44. return color
  45. ctx = get_current_context(silent=True)
  46. if ctx is not None:
  47. return ctx.color
  48. return None