Skip to content
Myr

Implement support for thread local context.

Before adoption: this commit came in with the history the project adopted, so no landing records it.

This allows click users to access the context object from anywhere within the current thread. The access to this object is properly scoped as before.

authored by Armin Ronacher · committed by Armin Ronacher · parent 9c57c9e · Browse files · 8 files+83 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+83 added−9 removed

  • tests:+15 added−1 removed
  • other:+68 added−8 removed

8 files+83 added−9 removed

modified:click/__init__.py+6 added
16 unmodified lines
17# Core classes18from .core import Context, BaseCommand, Command, MultiCommand, Group, \19 CommandCollection, Parameter, Option, Argument2021# Globals22from .globals import get_current_context2324# Decorators25from .decorators import pass_context, pass_obj, make_pass_decorator, \26 command, group, argument, option, confirmation_option, \27 password_option, version_option, help_option
26 unmodified lines
54 # Core classes55 'Context', 'BaseCommand', 'Command', 'MultiCommand', 'Group',56 'CommandCollection', 'Parameter', 'Option', 'Argument',5758 # Globals59 'get_current_context',6061 # Decorators62 'pass_context', 'pass_obj', 'make_pass_decorator', 'command', 'group',63 'argument', 'option', 'confirmation_option', 'password_option',64 'version_option', 'help_option',
27 unmodified lines
modified:click/core.py+4 added-2 removed
10 unmodified lines
11 MissingParameter12from .termui import prompt, confirm13from .formatting import HelpFormatter, join_options14from .parser import OptionParser, split_opt15from .globals import push_context, pop_context1617from ._compat import PY2, isidentifier, iteritems181920_missing = object()212223SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'
268 unmodified lines
292 self._depth = 0293294 def __enter__(self):295 self._depth += 1296 push_context(self)297 return self298299 def __exit__(self, exc_type, exc_value, tb):300 pop_context()301 self._depth -= 1302 if self._depth == 0:303 self.close()304
129 unmodified lines
434 if param.name not in kwargs and param.expose_value:435 kwargs[param.name] = param.get_default(ctx)436437 args = args[2:]434 if getattr(callback, '__click_pass_context__', False):435 args = (ctx,) + args438 with augment_usage_errors(self):439 with ctx:440 return callback(*args, **kwargs)441
1184 unmodified lines
modified:click/decorators.py+6 added-6 removed
3 unmodified lines
4from functools import update_wrapper56from ._compat import iteritems7from .utils import echo8from .globals import get_current_context91011def pass_context(f):12 """Marks a callback as wanting to receive the current context13 object as first argument.14 """14 f.__click_pass_context__ = True15 return f15 def new_func(*args, **kwargs):16 return f(get_current_context(), *args, **kwargs)17 return update_wrapper(new_func, f)181920def pass_obj(f):21 """Similar to :func:`pass_context`, but only pass the object on the
1 unmodified line
23 represents the state of a nested system.24 """25 @pass_context26 def new_func(*args, **kwargs):25 ctx = args[0]26 return ctx.invoke(f, ctx.obj, *args[1:], **kwargs)27 return f(get_current_context().obj, *args, **kwargs)28 return update_wrapper(new_func, f)293031def make_pass_decorator(object_type, ensure=False):
18 unmodified lines
50 :param ensure: if set to `True`, a new object will be created and51 remembered on the context if it's not there yet.52 """53 def decorator(f):53 @pass_context54 def new_func(*args, **kwargs):55 ctx = args[0]55 ctx = get_current_context()56 if ensure:57 obj = ctx.ensure_object(object_type)58 else:59 obj = ctx.find_object(object_type)
242 unmodified lines
added:click/globals.py+46 added
1from threading import local234_local = local()567def get_current_context(silent=False):8 """Returns the current click context. This can be used as a way to9 access the current context object from anywhere. This is a more implicit10 alternative to the :func:`pass_context` decorator. This function is11 primarily useful for helpers such as :func:`echo` which might be12 interested in changing it's behavior based on the current context.1314 .. versionadded:: 5.01516 :param silent: is set to `True` the return value is `None` if no context17 is available. The default behavior is to raise a18 :exc:`RuntimeError`.19 """20 try:21 return getattr(_local, 'stack')[-1]22 except (AttributeError, IndexError):23 if not silent:24 raise RuntimeError('There is no active click context.')252627def push_context(ctx):28 """Pushes a new context to the current stack."""29 _local.__dict__.setdefault('stack', []).append(ctx)303132def pop_context():33 """Removes the top level from the stack."""34 _local.stack.pop()353637def resolve_color_default(color=None):38 """"Internal helper to get the default value of the color flag. If a39 value is passed it's returned unchanged, otherwise it's looked up from40 the current context.41 """42 if color is not None:43 return color44 ctx = get_current_context(silent=True)45 if ctx is not None:46 return ctx.color
modified:click/termui.py+3 added
5 unmodified lines
6 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN7from .utils import echo8from .exceptions import Abort, UsageError9from .types import convert_type10from .globals import resolve_color_default111213# The prompt functions to use. The doc tools currently override these14# functions to customize how they work.
182 unmodified lines
197 :param text: the text to page.198 :param color: controls if the pager supports ANSI colors or not. The199 default is autodetection.200 """201 color = resolve_color_default(color)202 if not isinstance(text, string_types):203 text = text_type(text)204 from ._termui_impl import pager205 return pager(text + '\n', color)
82 unmodified lines
288 codes are included anywhere in the progress bar output289 which is not the case by default.290 """291 from ._termui_impl import ProgressBar292 color = resolve_color_default(color)293 return ProgressBar(iterable=iterable, length=length, show_eta=show_eta,294 show_percent=show_percent, show_pos=show_pos,295 item_show_func=item_show_func, fill_char=fill_char,296 empty_char=empty_char, bar_template=bar_template,
235 unmodified lines
modified:click/utils.py+3 added
1import os2import sys3from collections import deque45from .globals import resolve_color_default67from ._compat import text_type, open_stream, get_filesystem_encoding, \8 get_streerror, string_types, PY2, binary_streams, text_streams, \9 filename_to_ui, auto_wrap_for_ansi, strip_ansi, should_strip_ansi, \10 _default_text_stdout, _default_text_stderr, is_bytes, WIN
284 unmodified lines
295 # to strip colors. If we are on windows we either wrap the stream296 # to strip the color or we use the colorama support to translate the297 # ansi codes to API calls.298 if message and not is_bytes(message):299 color = resolve_color_default(color)300 if should_strip_ansi(file, color):301 message = strip_ansi(message)302 elif WIN:303 if auto_wrap_for_ansi is not None:
143 unmodified lines
modified:tests/test_context.py+13 added
108 unmodified lines
109110 result = runner.invoke(cli, [])111 assert result.exception is None112 assert called == [True]113114115def test_global_context_object(runner):116 @click.command()117 @click.pass_context118 def cli(ctx):119 assert click.get_current_context() is ctx120 ctx.obj = 'FOOBAR'121 assert click.get_current_context().obj == 'FOOBAR'122123 assert click.get_current_context(silent=True) is None124 runner.invoke(cli, [], catch_exceptions=False)125 assert click.get_current_context(silent=True) is None
modified:tests/test_imports.py+2 added-1 removed
27 unmodified lines
28'''2930ALLOWED_IMPORTS = set([31 'weakref', 'os', 'struct', 'collections', 'sys', 'contextlib',32 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io'32 'functools', 'stat', 're', 'codecs', 'inspect', 'itertools', 'io',33 'threading'34])353637def test_light_imports():
13 unmodified lines