1
0

globals.py 1.5 KB

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