Merge pull request #379 from mitsuhiko/feature/global-ctx
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Implement support for thread local context.
authored by Armin Ronacher · committed by Armin Ronacher · parents 9c57c9e, 695ca34 · 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
Provenance
- Commit
022fc73- Tree
3a181aa- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent 1
9c57c9e- Parent 2
695ca34
8 files changed+83 added−9 removed
modified:click/__init__.py+6 added
16 unmodified lines17 # Core classes18 from .core import Context, BaseCommand, Command, MultiCommand, Group, \19 CommandCollection, Parameter, Option, Argument20 21+# Globals22+from .globals import get_current_context23+24 # Decorators25 from .decorators import pass_context, pass_obj, make_pass_decorator, \26 command, group, argument, option, confirmation_option, \27 password_option, version_option, help_option26 unmodified lines54 # Core classes55 'Context', 'BaseCommand', 'Command', 'MultiCommand', 'Group',56 'CommandCollection', 'Parameter', 'Option', 'Argument',57 58+ # Globals59+ 'get_current_context',60+61 # Decorators62 'pass_context', 'pass_obj', 'make_pass_decorator', 'command', 'group',63 'argument', 'option', 'confirmation_option', 'password_option',64 'version_option', 'help_option',27 unmodified linesmodified:click/core.py+4 added-2 removed
10 unmodified lines11 MissingParameter12 from .termui import prompt, confirm13 from .formatting import HelpFormatter, join_options14 from .parser import OptionParser, split_opt15+from .globals import push_context, pop_context16 17 from ._compat import PY2, isidentifier, iteritems18 19+20 _missing = object()21 22 23 SUBCOMMAND_METAVAR = 'COMMAND [ARGS]...'268 unmodified lines292 self._depth = 0293 294 def __enter__(self):295 self._depth += 1296+ push_context(self)297 return self298 299 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 lines434 if param.name not in kwargs and param.expose_value:435 kwargs[param.name] = param.get_default(ctx)436 437 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 linesmodified:click/decorators.py+6 added-6 removed
3 unmodified lines4 from functools import update_wrapper5 6 from ._compat import iteritems7 from .utils import echo8+from .globals import get_current_context9 10 11 def 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)18 19 20 def pass_obj(f):21 """Similar to :func:`pass_context`, but only pass the object on the1 unmodified line23 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)29 30 31 def make_pass_decorator(object_type, ensure=False):18 unmodified lines50 :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 linesadded:click/globals.py+46 added
1+from threading import local2+3+4+_local = local()5+6+7+def 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.13+14+ .. versionadded:: 5.015+16+ :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.')25+26+27+def push_context(ctx):28+ """Pushes a new context to the current stack."""29+ _local.__dict__.setdefault('stack', []).append(ctx)30+31+32+def pop_context():33+ """Removes the top level from the stack."""34+ _local.stack.pop()35+36+37+def 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.colormodified:click/termui.py+3 added
5 unmodified lines6 isatty, strip_ansi, get_winterm_size, DEFAULT_COLUMNS, WIN7 from .utils import echo8 from .exceptions import Abort, UsageError9 from .types import convert_type10+from .globals import resolve_color_default11 12 13 # The prompt functions to use. The doc tools currently override these14 # functions to customize how they work.182 unmodified lines197 :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 lines288 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 linesmodified:click/utils.py+3 added
1 import os2 import sys3 from collections import deque4 5+from .globals import resolve_color_default6+7 from ._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, WIN284 unmodified lines295 # 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 linesmodified:tests/test_context.py+13 added
108 unmodified lines109 110 result = runner.invoke(cli, [])111 assert result.exception is None112 assert called == [True]113+114+115+def 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'122+123+ assert click.get_current_context(silent=True) is None124+ runner.invoke(cli, [], catch_exceptions=False)125+ assert click.get_current_context(silent=True) is Nonemodified:tests/test_imports.py+2 added-1 removed
27 unmodified lines28 '''29 30 ALLOWED_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 ])35 36 37 def test_light_imports():13 unmodified lines