Debian Codegraph @

cloup/_context.py

raw
1 from __future__ import annotations
2
3 import warnings
4 from functools import update_wrapper
5 from typing import (
6 Any, Callable, cast, Dict, List, Optional, Type, TypeVar, TYPE_CHECKING, overload,
7 )
8
9 import click
10
11 import cloup
12 from cloup._util import coalesce, pick_non_missing
13 from cloup.formatting import HelpFormatter
14 from cloup.typing import MISSING, Possibly
15
16 if TYPE_CHECKING:
17 from typing_extensions import Concatenate, ParamSpec
18
19 P = ParamSpec("P")
20
21 R = TypeVar("R")
22
23
24 @overload
25 def get_current_context() -> "Context":
26 ...
27
28
29 @overload
30 def get_current_context(silent: bool = False) -> "Optional[Context]":
31 ...
32
33
34 def get_current_context(silent: bool = False) -> "Optional[Context]":
35 """Equivalent to :func:`click.get_current_context` but casts the returned
36 :class:`click.Context` object to :class:`cloup.Context` (which is safe when using
37 cloup commands classes and decorators)."""
38 return cast(Optional[Context], click.get_current_context(silent=silent))
39
40
41 def pass_context(f: "Callable[Concatenate[Context, P], R]") -> "Callable[P, R]":
42 """Marks a callback as wanting to receive the current context object as first
43 argument. Equivalent to :func:`click.pass_context` but assumes the current context
44 is of type :class:`cloup.Context`."""
45
46 def new_func(*args: "P.args", **kwargs: "P.kwargs") -> R:
47 return f(get_current_context(), *args, **kwargs)
48
49 return update_wrapper(new_func, f)
50
51
52 def _warn_if_formatter_settings_conflict(
53 ctx_key: str,
54 formatter_key: str,
55 ctx_kwargs: Dict[str, Any],
56 formatter_settings: Dict[str, Any],
57 ) -> None:
58 if ctx_kwargs.get(ctx_key) and formatter_settings.get(formatter_key):
59 from textwrap import dedent
60 formatter_arg = f'formatter_settings.{formatter_key}'
61 warnings.warn(dedent(f"""
62 You provided both {ctx_key} and {formatter_arg} as arguments of a Context.
63 Unless you have a particular reason, you should set only one of them..
64 If you use both, {formatter_arg} will be used by the formatter.
65 You can suppress this warning by setting:
66
67 cloup.warnings.formatter_settings_conflict = False
68 """))
69
70
71 class Context(click.Context):
72 """A custom context for Cloup.
73
74 Look up :class:`click.Context` for the list of all arguments.
75
76 .. versionadded:: 0.9.0
77 added the ``check_constraints_consistency`` parameter.
78
79 .. versionadded:: 0.8.0
80
81 :param ctx_args:
82 arguments forwarded to :class:`click.Context`.
83 :param align_option_groups:
84 if True, align the definition lists of all option groups of a command.
85 You can override this by setting the corresponding argument of ``Command``
86 (but you probably shouldn't: be consistent).
87 :param align_sections:
88 if True, align the definition lists of all subcommands of a group.
89 You can override this by setting the corresponding argument of ``Group``
90 (but you probably shouldn't: be consistent).
91 :param show_subcommand_aliases:
92 whether to show the aliases of subcommands in the help of a ``cloup.Group``.
93 :param show_constraints:
94 whether to include a "Constraint" section in the command help (if at
95 least one constraint is defined).
96 :param check_constraints_consistency:
97 enable additional checks for constraints which detects mistakes of the
98 developer (see :meth:`cloup.Constraint.check_consistency`).
99 :param formatter_settings:
100 keyword arguments forwarded to :class:`HelpFormatter` in ``make_formatter``.
101 This args are merged with those of the (eventual) parent context and then
102 merged again (being overridden) by those of the command.
103 **Tip**: use the static method :meth:`HelpFormatter.settings` to create this
104 dictionary, so that you can be guided by your IDE.
105 :param ctx_kwargs:
106 keyword arguments forwarded to :class:`click.Context`.
107 """
108 formatter_class: Type[HelpFormatter] = HelpFormatter
109
110 def __init__(
111 self, *ctx_args: Any,
112 align_option_groups: Optional[bool] = None,
113 align_sections: Optional[bool] = None,
114 show_subcommand_aliases: Optional[bool] = None,
115 show_constraints: Optional[bool] = None,
116 check_constraints_consistency: Optional[bool] = None,
117 formatter_settings: Dict[str, Any] = {},
118 **ctx_kwargs: Any,
119 ):
120 super().__init__(*ctx_args, **ctx_kwargs)
121
122 self.align_option_groups = coalesce(
123 align_option_groups,
124 getattr(self.parent, 'align_option_groups', None),
125 )
126 self.align_sections = coalesce(
127 align_sections,
128 getattr(self.parent, 'align_sections', None),
129 )
130 self.show_subcommand_aliases = coalesce(
131 show_subcommand_aliases,
132 getattr(self.parent, 'show_subcommand_aliases', None),
133 )
134 self.show_constraints = coalesce(
135 show_constraints,
136 getattr(self.parent, 'show_constraints', None),
137 )
138 self.check_constraints_consistency = coalesce(
139 check_constraints_consistency,
140 getattr(self.parent, 'check_constraints_consistency', None)
141 )
142
143 if cloup.warnings.formatter_settings_conflict:
144 _warn_if_formatter_settings_conflict(
145 'terminal_width', 'width', ctx_kwargs, formatter_settings)
146 _warn_if_formatter_settings_conflict(
147 'max_content_width', 'max_width', ctx_kwargs, formatter_settings)
148
149 #: Keyword arguments for the HelpFormatter. Obtained by merging the options
150 #: of the parent context with the one passed to this context. Before creating
151 #: the help formatter, these options are merged with the (eventual) options
152 #: provided to the command (having higher priority).
153 self.formatter_settings = {
154 **getattr(self.parent, 'formatter_settings', {}),
155 **formatter_settings,
156 }
157
158 def get_formatter_settings(self) -> Dict[str, Any]:
159 return {
160 'width': self.terminal_width,
161 'max_width': self.max_content_width,
162 **self.formatter_settings,
163 **getattr(self.command, 'formatter_settings', {})
164 }
165
166 def make_formatter(self) -> HelpFormatter:
167 opts = self.get_formatter_settings()
168 return self.formatter_class(**opts)
169
170 @staticmethod
171 def settings(
172 *, auto_envvar_prefix: Possibly[str] = MISSING,
173 default_map: Possibly[Dict[str, Any]] = MISSING,
174 terminal_width: Possibly[int] = MISSING,
175 max_content_width: Possibly[int] = MISSING,
176 resilient_parsing: Possibly[bool] = MISSING,
177 allow_extra_args: Possibly[bool] = MISSING,
178 allow_interspersed_args: Possibly[bool] = MISSING,
179 ignore_unknown_options: Possibly[bool] = MISSING,
180 help_option_names: Possibly[List[str]] = MISSING,
181 token_normalize_func: Possibly[Callable[[str], str]] = MISSING,
182 color: Possibly[bool] = MISSING,
183 show_default: Possibly[bool] = MISSING,
184 align_option_groups: Possibly[bool] = MISSING,
185 align_sections: Possibly[bool] = MISSING,
186 show_subcommand_aliases: Possibly[bool] = MISSING,
187 show_constraints: Possibly[bool] = MISSING,
188 check_constraints_consistency: Possibly[bool] = MISSING,
189 formatter_settings: Possibly[Dict[str, Any]] = MISSING,
190 ) -> Dict[str, Any]:
191 """Utility method for creating a ``context_settings`` dictionary.
192
193 :param auto_envvar_prefix:
194 the prefix to use for automatic environment variables. If this is
195 `None` then reading from environment variables is disabled. This
196 does not affect manually set environment variables which are always
197 read.
198 :param default_map:
199 a dictionary (like object) with default values for parameters.
200 :param terminal_width:
201 the width of the terminal. The default is inherited from parent
202 context. If no context defines the terminal width then auto-detection
203 will be applied.
204 :param max_content_width:
205 the maximum width for content rendered by Click (this currently
206 only affects help pages). This defaults to 80 characters if not
207 overridden. In other words: even if the terminal is larger than
208 that, Click will not format things wider than 80 characters by
209 default. In addition to that, formatters might add some safety
210 mapping on the right.
211 :param resilient_parsing:
212 if this flag is enabled then Click will parse without any
213 interactivity or callback invocation. Default values will also be
214 ignored. This is useful for implementing things such as completion
215 support.
216 :param allow_extra_args:
217 if this is set to `True` then extra arguments at the end will not
218 raise an error and will be kept on the context. The default is to
219 inherit from the command.
220 :param allow_interspersed_args:
221 if this is set to `False` then options and arguments cannot be
222 mixed. The default is to inherit from the command.
223 :param ignore_unknown_options:
224 instructs click to ignore options it does not know and keeps them
225 for later processing.
226 :param help_option_names:
227 optionally a list of strings that define how the default help
228 parameter is named. The default is ``['--help']``.
229 :param token_normalize_func:
230 an optional function that is used to normalize tokens (options,
231 choices, etc.). This for instance can be used to implement
232 case-insensitive behavior.
233 :param color:
234 controls if the terminal supports ANSI colors or not. The default
235 is auto-detection. This is only needed if ANSI codes are used in
236 texts that Click prints which is by default not the case. This for
237 instance would affect help output.
238 :param show_default: Show defaults for all options. If not set,
239 defaults to the value from a parent context. Overrides an
240 option's ``show_default`` argument.
241 :param align_option_groups:
242 if True, align the definition lists of all option groups of a command.
243 You can override this by setting the corresponding argument of ``Command``
244 (but you probably shouldn't: be consistent).
245 :param align_sections:
246 if True, align the definition lists of all subcommands of a group.
247 You can override this by setting the corresponding argument of ``Group``
248 (but you probably shouldn't: be consistent).
249 :param show_subcommand_aliases:
250 whether to show the aliases of subcommands in the help of a ``cloup.Group``.
251 :param show_constraints:
252 whether to include a "Constraint" section in the command help (if at
253 least one constraint is defined).
254 :param check_constraints_consistency:
255 enable additional checks for constraints which detects mistakes of the
256 developer (see :meth:`cloup.Constraint.check_consistency`).
257 :param formatter_settings:
258 keyword arguments forwarded to :class:`HelpFormatter` in ``make_formatter``.
259 This args are merged with those of the (eventual) parent context and then
260 merged again (being overridden) by those of the command.
261 **Tip**: use the static method :meth:`HelpFormatter.settings` to create this
262 dictionary, so that you can be guided by your IDE.
263 """
264 return pick_non_missing(locals())