globals.py 1.9 KB

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