1from threading import local
2
3_local = local()
4
5
6def get_current_context(silent=False):
7    """Returns the current click context.  This can be used as a way to
8    access the current context object from anywhere.  This is a more implicit
9    alternative to the :func:`pass_context` decorator.  This function is
10    primarily useful for helpers such as :func:`echo` which might be
11    interested in changing its behavior based on the current context.
12
13    To push the current context, :meth:`Context.scope` can be used.
14
15    .. versionadded:: 5.0
16
17    :param silent: if set to `True` the return value is `None` if no context
18                   is available.  The default behavior is to raise a
19                   :exc:`RuntimeError`.
20    """
21    try:
22        return _local.stack[-1]
23    except (AttributeError, IndexError):
24        if not silent:
25            raise RuntimeError("There is no active click context.")
26
27
28def push_context(ctx):
29    """Pushes a new context to the current stack."""
30    _local.__dict__.setdefault("stack", []).append(ctx)
31
32
33def pop_context():
34    """Removes the top level from the stack."""
35    _local.stack.pop()
36
37
38def resolve_color_default(color=None):
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