bazarr/libs/click/globals.py

69 lines
1.9 KiB
Python
Raw Normal View History

import typing as t
2018-10-31 16:08:29 +00:00
from threading import local
if t.TYPE_CHECKING:
import typing_extensions as te
from .core import Context
2018-10-31 16:08:29 +00:00
_local = local()
2022-11-07 18:06:49 +00:00
@t.overload
def get_current_context(silent: "te.Literal[False]" = False) -> "Context":
...
2022-11-07 18:06:49 +00:00
@t.overload
def get_current_context(silent: bool = ...) -> t.Optional["Context"]:
...
def get_current_context(silent: bool = False) -> t.Optional["Context"]:
2018-10-31 16:08:29 +00: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
2019-12-10 20:09:51 +00:00
interested in changing its behavior based on the current context.
2018-10-31 16:08:29 +00:00
To push the current context, :meth:`Context.scope` can be used.
.. versionadded:: 5.0
:param silent: if set to `True` the return value is `None` if no context
2018-10-31 16:08:29 +00:00
is available. The default behavior is to raise a
:exc:`RuntimeError`.
"""
try:
return t.cast("Context", _local.stack[-1])
except (AttributeError, IndexError) as e:
2018-10-31 16:08:29 +00:00
if not silent:
raise RuntimeError("There is no active click context.") from e
2018-10-31 16:08:29 +00:00
return None
2018-10-31 16:08:29 +00:00
def push_context(ctx: "Context") -> None:
2018-10-31 16:08:29 +00:00
"""Pushes a new context to the current stack."""
_local.__dict__.setdefault("stack", []).append(ctx)
2018-10-31 16:08:29 +00:00
def pop_context() -> None:
2018-10-31 16:08:29 +00:00
"""Removes the top level from the stack."""
_local.stack.pop()
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
2018-10-31 16:08:29 +00:00
value is passed it's returned unchanged, otherwise it's looked up from
the current context.
"""
if color is not None:
return color
2018-10-31 16:08:29 +00:00
ctx = get_current_context(silent=True)
2018-10-31 16:08:29 +00:00
if ctx is not None:
return ctx.color
return None