Debian Codegraph @

cloup/_sections.py

raw
1 from collections import OrderedDict
2 from typing import (
3 Any, Dict, Iterable, List, Optional, Sequence, Tuple, Type, TypeVar, Union,
4 )
5
6 import click
7
8 from cloup._util import first_bool, pick_not_none
9 from cloup.formatting import HelpSection, ensure_is_cloup_formatter
10
11 CommandType = TypeVar('CommandType', bound=Type[click.Command])
12 Subcommands = Union[Iterable[click.Command], Dict[str, click.Command]]
13
14
15 class Section:
16 """
17 A group of (sub)commands to show in the same help section of a
18 ``MultiCommand``. You can use sections with any `Command` that inherits
19 from :class:`SectionMixin`.
20
21 .. versionchanged:: 0.6.0
22 removed the deprecated old name ``GroupSection``.
23
24 .. versionchanged:: 0.5.0
25 introduced the new name ``Section`` and deprecated the old ``GroupSection``.
26 """
27
28 def __init__(self, title: str,
29 commands: Subcommands = (),
30 is_sorted: bool = False): # noqa
31 """
32 :param title:
33 :param commands: sequence of commands or dict of commands keyed by name
34 :param is_sorted:
35 if True, ``list_commands()`` returns the commands in lexicographic order
36 """
37 if not isinstance(title, str):
38 raise TypeError(
39 'the first argument must be a string, the title; you probably forgot it')
40 self.title = title
41 self.is_sorted = is_sorted
42 self.commands: OrderedDict[str, click.Command] = OrderedDict()
43 if isinstance(commands, Sequence):
44 self.commands = OrderedDict()
45 for cmd in commands:
46 self.add_command(cmd)
47 elif isinstance(commands, dict):
48 self.commands = OrderedDict(commands)
49 else:
50 raise TypeError('argument `commands` must be a sequence of commands '
51 'or a dict of commands keyed by name')
52
53 @classmethod
54 def sorted(cls, title: str, commands: Subcommands = ()) -> 'Section':
55 return cls(title, commands, is_sorted=True)
56
57 def add_command(self, cmd: click.Command, name: Optional[str] = None) -> None:
58 name = name or cmd.name
59 if not name:
60 raise TypeError('missing command name')
61 if name in self.commands:
62 raise Exception(f'command "{name}" already exists')
63 self.commands[name] = cmd
64
65 def list_commands(self) -> List[Tuple[str, click.Command]]:
66 command_list = [(name, cmd) for name, cmd in self.commands.items()
67 if not cmd.hidden]
68 if self.is_sorted:
69 command_list.sort()
70 return command_list
71
72 def __len__(self) -> int:
73 return len(self.commands)
74
75 def __repr__(self) -> str:
76 return 'Section({}, is_sorted={})'.format(self.title, self.is_sorted)
77
78
79 class SectionMixin:
80 """
81 Adds to a :class:`click.MultiCommand` the possibility of organizing its subcommands
82 into multiple help sections.
83
84 Sections can be specified in the following ways:
85
86 #. passing a list of :class:`Section` objects to the constructor setting
87 the argument ``sections``
88 #. using :meth:`add_section` to add a single section
89 #. using :meth:`add_command` with the argument `section` set
90
91 Commands not assigned to any user-defined section are added to the
92 "default section", whose title is "Commands" or "Other commands" depending
93 on whether it is the only section or not. The default section is the last
94 shown section in the help and its commands are listed in lexicographic order.
95
96 .. versionchanged:: 0.8.0
97 this mixin now relies on ``cloup.HelpFormatter`` to align help sections.
98 If a ``click.HelpFormatter`` is used with a ``TypeError`` is raised.
99
100 .. versionchanged:: 0.8.0
101 removed ``format_section``. Added ``make_commands_help_section``.
102
103 .. versionadded:: 0.5.0
104 """
105
106 def __init__(
107 self, *args: Any,
108 commands: Optional[Dict[str, click.Command]] = None,
109 sections: Iterable[Section] = (),
110 align_sections: Optional[bool] = None,
111 **kwargs: Any,
112 ):
113 """
114 :param align_sections:
115 whether to align the columns of all subcommands' help sections.
116 This is also available as a context setting having a lower priority
117 than this attribute. Given that this setting should be consistent
118 across all you commands, you should probably use the context
119 setting only.
120 :param args:
121 positional arguments forwarded to the next class in the MRO
122 :param kwargs:
123 keyword arguments forwarded to the next class in the MRO
124 """
125 super().__init__(*args, commands=commands, **kwargs) # type: ignore
126 self.align_sections = align_sections
127 self._default_section = Section('__DEFAULT', commands=commands or [])
128 self._user_sections: List[Section] = []
129 self._section_set = {self._default_section}
130 for section in sections:
131 self.add_section(section)
132
133 def _add_command_to_section(
134 self, cmd: click.Command,
135 name: Optional[str] = None,
136 section: Optional[Section] = None
137 ) -> None:
138 """Add a command to the section (if specified) or to the default section."""
139 name = name or cmd.name
140 if section is None:
141 section = self._default_section
142 section.add_command(cmd, name)
143 if section not in self._section_set:
144 self._user_sections.append(section)
145 self._section_set.add(section)
146
147 def add_section(self, section: Section) -> None:
148 """Add a :class:`Section` to this group. You can add the same
149 section object only a single time.
150
151 See Also:
152 :meth:`section`
153 """
154 if section in self._section_set:
155 raise ValueError(f'section "{section}" was already added')
156 self._user_sections.append(section)
157 self._section_set.add(section)
158 for name, cmd in section.commands.items():
159 # It's important to call self.add_command() and not super().add_command() here
160 # otherwise subclasses' add_command() is not called.
161 self.add_command(cmd, name, fallback_to_default_section=False)
162
163 def section(self, title: str, *commands: click.Command, **attrs: Any) -> Section:
164 """Create a new :class:`Section`, adds it to this group and returns it."""
165 section = Section(title, commands, **attrs)
166 self.add_section(section)
167 return section
168
169 def add_command(
170 self, cmd: click.Command,
171 name: Optional[str] = None,
172 section: Optional[Section] = None,
173 fallback_to_default_section: bool = True,
174 ) -> None:
175 """
176 Add a subcommand to this ``Group``.
177
178 **Implementation note:** ``fallback_to_default_section`` looks not very
179 clean but, even if it's not immediate to see (it wasn't for me), I chose
180 it over apparently cleaner options.
181
182 :param cmd:
183 :param name:
184 :param section:
185 a ``Section`` instance. The command must not be in the section already.
186 :param fallback_to_default_section:
187 if ``section`` is None and this option is enabled, the command is added
188 to the "default section". If disabled, the command is not added to
189 any section unless ``section`` is provided. This is useful for
190 internal code and subclasses. Don't disable it unless you know what
191 you are doing.
192 """
193 super().add_command(cmd, name) # type: ignore
194 if section or fallback_to_default_section:
195 self._add_command_to_section(cmd, name, section)
196
197 def list_sections(
198 self, ctx: click.Context, include_default_section: bool = True
199 ) -> List[Section]:
200 """
201 Return the list of all sections in the "correct order".
202
203 If ``include_default_section=True`` and the default section is non-empty,
204 it will be included at the end of the list.
205 """
206 section_list = list(self._user_sections)
207 if include_default_section and len(self._default_section) > 0:
208 default_section = Section.sorted(
209 title='Other commands' if len(self._user_sections) > 0 else 'Commands',
210 commands=self._default_section.commands)
211 section_list.append(default_section)
212 return section_list
213
214 def format_subcommand_name(
215 self, ctx: click.Context, name: str, cmd: click.Command
216 ) -> str:
217 """Used to format the name of the subcommands. This method is useful
218 when you combine this extension with other click extensions that override
219 :meth:`format_commands`. Most of these, like click-default-group, just
220 add something to the name of the subcommands, which is exactly what this
221 method allows you to do without overriding bigger methods.
222 """
223 return name
224
225 def make_commands_help_section(
226 self, ctx: click.Context, section: Section
227 ) -> Optional[HelpSection]:
228 visible_subcommands = section.list_commands()
229 if not visible_subcommands:
230 return None
231 return HelpSection(
232 heading=section.title,
233 definitions=[
234 (self.format_subcommand_name(ctx, name, cmd), cmd.get_short_help_str)
235 for name, cmd in visible_subcommands
236 ]
237 )
238
239 def must_align_sections(
240 self, ctx: Optional[click.Context], default: bool = True
241 ) -> bool:
242 return first_bool(
243 self.align_sections,
244 getattr(ctx, 'align_sections', None),
245 default,
246 )
247
248 def format_commands(self, ctx: click.Context, formatter: click.HelpFormatter) -> None:
249 formatter = ensure_is_cloup_formatter(formatter)
250
251 subcommand_sections = self.list_sections(ctx)
252 help_sections = pick_not_none(
253 self.make_commands_help_section(ctx, section)
254 for section in subcommand_sections
255 )
256 if not help_sections:
257 return
258
259 formatter.write_many_sections(
260 help_sections, aligned=self.must_align_sections(ctx)
261 )