globals.py 1.9 KB

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