python-click/src/click/globals.py

70 lines
1.9 KiB
Python
Raw Normal View History

2021-10-10 03:31:57 +02:00
import typing
import typing as t
2015-08-23 03:10:31 +02:00
from threading import local
2021-10-10 03:31:57 +02:00
if t.TYPE_CHECKING:
import typing_extensions as te
from .core import Context
2015-08-23 03:10:31 +02:00
_local = local()
2021-10-10 03:31:57 +02:00
@typing.overload
def get_current_context(silent: "te.Literal[False]" = False) -> "Context":
...
@typing.overload
def get_current_context(silent: bool = ...) -> t.Optional["Context"]:
...
def get_current_context(silent: bool = False) -> t.Optional["Context"]:
2015-08-23 03:10:31 +02:00
"""Returns the current click context. This can be used as a way to
access the current context object from anywhere. This is a more implicit
alternative to the :func:`pass_context` decorator. This function is
primarily useful for helpers such as :func:`echo` which might be
2018-09-06 20:55:10 +02:00
interested in changing its behavior based on the current context.
2015-08-23 03:10:31 +02:00
To push the current context, :meth:`Context.scope` can be used.
.. versionadded:: 5.0
2020-07-21 08:23:42 +02:00
:param silent: if set to `True` the return value is `None` if no context
2015-08-23 03:10:31 +02:00
is available. The default behavior is to raise a
:exc:`RuntimeError`.
"""
try:
2021-10-10 03:31:57 +02:00
return t.cast("Context", _local.stack[-1])
except (AttributeError, IndexError) as e:
2015-08-23 03:10:31 +02:00
if not silent:
2021-10-10 03:31:57 +02:00
raise RuntimeError("There is no active click context.") from e
2015-08-23 03:10:31 +02:00
2021-10-10 03:31:57 +02:00
return None
2015-08-23 03:10:31 +02:00
2021-10-10 03:31:57 +02:00
def push_context(ctx: "Context") -> None:
2015-08-23 03:10:31 +02:00
"""Pushes a new context to the current stack."""
2020-07-21 08:23:42 +02:00
_local.__dict__.setdefault("stack", []).append(ctx)
2015-08-23 03:10:31 +02:00
2021-10-10 03:31:57 +02:00
def pop_context() -> None:
2015-08-23 03:10:31 +02:00
"""Removes the top level from the stack."""
_local.stack.pop()
2021-10-10 03:31:57 +02:00
def resolve_color_default(color: t.Optional[bool] = None) -> t.Optional[bool]:
"""Internal helper to get the default value of the color flag. If a
2015-08-23 03:10:31 +02:00
value is passed it's returned unchanged, otherwise it's looked up from
the current context.
"""
if color is not None:
return color
2021-10-10 03:31:57 +02:00
2015-08-23 03:10:31 +02:00
ctx = get_current_context(silent=True)
2021-10-10 03:31:57 +02:00
2015-08-23 03:10:31 +02:00
if ctx is not None:
return ctx.color
2021-10-10 03:31:57 +02:00
return None