| 1 |
import dataclasses as dc |
| 2 |
import inspect |
| 3 |
import shutil |
| 4 |
import textwrap |
| 5 |
from itertools import chain |
| 6 |
from typing import ( |
| 7 |
Any, Callable, Dict, Iterable, Iterator, Optional, Sequence, TYPE_CHECKING, |
| 8 |
Tuple, Union, |
| 9 |
) |
| 10 |
|
| 11 |
from cloup._util import click_version_ge_8_1 |
| 12 |
from cloup.formatting._util import unstyled_len |
| 13 |
|
| 14 |
if TYPE_CHECKING: |
| 15 |
from .sep import RowSepPolicy, SepGenerator |
| 16 |
|
| 17 |
import click |
| 18 |
from click.formatting import wrap_text |
| 19 |
|
| 20 |
from cloup._util import ( |
| 21 |
check_positive_int, identity, indent_lines, make_repr, |
| 22 |
pick_non_missing, |
| 23 |
) |
| 24 |
from ..typing import MISSING, Possibly |
| 25 |
from cloup.styling import HelpTheme, IStyle |
| 26 |
|
| 27 |
Definition = Tuple[str, Union[str, Callable[[int], str]]] |
| 28 |
|
| 29 |
|
| 30 |
@dc.dataclass() |
| 31 |
class HelpSection: |
| 32 |
"""A container for a help section data.""" |
| 33 |
heading: str |
| 34 |
"""Help section title.""" |
| 35 |
|
| 36 |
definitions: Sequence[Definition] |
| 37 |
"""Rows with 2 columns each. The 2nd element of each row can also be a function |
| 38 |
taking an integer (the available width for the 2nd column) and returning a string.""" |
| 39 |
|
| 40 |
help: Optional[str] = None |
| 41 |
"""(Optional) long description of the section.""" |
| 42 |
|
| 43 |
constraint: Optional[str] = None |
| 44 |
"""(Optional) option group constraint description.""" |
| 45 |
|
| 46 |
|
| 47 |
# noinspection PyMethodMayBeStatic |
| 48 |
class HelpFormatter(click.HelpFormatter): |
| 49 |
""" |
| 50 |
A custom help formatter. Features include: |
| 51 |
|
| 52 |
- more attributes for controlling the output of the formatter |
| 53 |
- a ``col1_width`` parameter in :meth:`write_dl` that allows Cloup to align |
| 54 |
multiple definition lists without resorting to hacks |
| 55 |
- a "linear layout" for definition lists that kicks in when the available |
| 56 |
terminal width is not enough for the standard 2-column layout |
| 57 |
(see argument ``col2_min_width``) |
| 58 |
- the first column width, when not explicitly given in ``write_dl`` is |
| 59 |
computed excluding the rows that exceed ``col1_max_width`` |
| 60 |
(called ``col_max`` in ``write_dl`` for compatibility with Click). |
| 61 |
|
| 62 |
.. versionchanged:: 0.9.0 |
| 63 |
the ``row_sep`` parameter now: |
| 64 |
|
| 65 |
- is set to ``None`` by default and ``row_sep=""`` corresponds to an |
| 66 |
empty line between rows |
| 67 |
- must not ends with ``\\n``; the formatter writes a newline just after |
| 68 |
it (when it's not ``None``), so a newline at the end is always enforced |
| 69 |
- accepts instances of :class:`~cloup.formatting.sep.SepGenerator` and |
| 70 |
:class:`~cloup.formatting.sep.RowSepPolicy`. |
| 71 |
|
| 72 |
.. versionadded:: 0.8.0 |
| 73 |
|
| 74 |
:param indent_increment: |
| 75 |
width of each indentation increment. |
| 76 |
:param width: |
| 77 |
content line width, excluding the newline character; by default it's |
| 78 |
initialized to ``min(terminal_width - 1, max_width)`` where |
| 79 |
``max_width`` is another argument. |
| 80 |
:param max_width: |
| 81 |
maximum content line width (equivalent to ``Context.max_content_width``). |
| 82 |
Used to compute ``width`` when it is not provided, ignored otherwise. |
| 83 |
:param col1_max_width: |
| 84 |
the maximum width of the first column of a definition list; as in Click, |
| 85 |
if the text of a row exceeds this threshold, the 2nd column is printed |
| 86 |
on a new line. |
| 87 |
:param col2_min_width: |
| 88 |
the minimum width for the second column of a definition list; if the |
| 89 |
available space is less than this value, the formatter switches from the |
| 90 |
standard 2-column layout to the "linear layout" (that this decision |
| 91 |
is taken for each definition list). If you want to always use the linear |
| 92 |
layout, you can set this argument to a very high number (or ``math.inf``). |
| 93 |
If you never want it (not recommended), you can set this argument to zero. |
| 94 |
:param col_spacing: |
| 95 |
the number of spaces between the column boundaries of a definition list. |
| 96 |
:param row_sep: |
| 97 |
an "extra" separator to insert between the rows of a definition list (in |
| 98 |
addition to the normal newline between definitions). If you want an empty |
| 99 |
line between rows, pass ``row_sep=""``. |
| 100 |
Read :ref:`Row separators <row-separators>` for more. |
| 101 |
:param theme: |
| 102 |
an :class:`~cloup.HelpTheme` instance specifying how to style the various |
| 103 |
elements of the help page. |
| 104 |
""" |
| 105 |
|
| 106 |
def __init__( |
| 107 |
self, indent_increment: int = 2, |
| 108 |
width: Optional[int] = None, |
| 109 |
max_width: Optional[int] = None, |
| 110 |
col1_max_width: int = 30, |
| 111 |
col2_min_width: int = 35, |
| 112 |
col_spacing: int = 2, |
| 113 |
row_sep: Union[None, str, 'SepGenerator', 'RowSepPolicy'] = None, |
| 114 |
theme: HelpTheme = HelpTheme(), |
| 115 |
): |
| 116 |
check_positive_int(col1_max_width, 'col1_max_width') |
| 117 |
check_positive_int(col_spacing, 'col_spacing') |
| 118 |
if isinstance(row_sep, str) and row_sep.endswith('\n'): |
| 119 |
raise ValueError( |
| 120 |
"since v0.9, row_sep must not end with '\\n'. The formatter writes " |
| 121 |
"a '\\n' after it; no other newline is allowed.\n" |
| 122 |
"If you want an empty line between rows, set row_sep=''.") |
| 123 |
|
| 124 |
max_width = max_width or 80 |
| 125 |
# We subtract 1 to the terminal width to leave space for the new line character. |
| 126 |
# Otherwise, when we write a line that is long exactly terminal_size (without \n) |
| 127 |
# the \n is printed on a new terminal line, leading to a useless empty line. |
| 128 |
width = ( |
| 129 |
width |
| 130 |
or click.formatting.FORCED_WIDTH |
| 131 |
or min(max_width, shutil.get_terminal_size((80, 100)).columns - 1) |
| 132 |
) |
| 133 |
super().__init__( |
| 134 |
width=width, max_width=max_width, indent_increment=indent_increment |
| 135 |
) |
| 136 |
self.width: int = width |
| 137 |
self.col1_max_width = col1_max_width |
| 138 |
self.col2_min_width = col2_min_width |
| 139 |
self.col_spacing = col_spacing |
| 140 |
self.theme = theme |
| 141 |
self.row_sep = row_sep |
| 142 |
|
| 143 |
@staticmethod |
| 144 |
def settings( |
| 145 |
*, width: Possibly[Optional[int]] = MISSING, |
| 146 |
max_width: Possibly[Optional[int]] = MISSING, |
| 147 |
indent_increment: Possibly[int] = MISSING, |
| 148 |
col1_max_width: Possibly[int] = MISSING, |
| 149 |
col2_min_width: Possibly[int] = MISSING, |
| 150 |
col_spacing: Possibly[int] = MISSING, |
| 151 |
row_sep: Possibly[Union[None, str, 'SepGenerator', 'RowSepPolicy']] = MISSING, |
| 152 |
theme: Possibly[HelpTheme] = MISSING, |
| 153 |
) -> Dict[str, Any]: |
| 154 |
"""A utility method for creating a ``formatter_settings`` dictionary to |
| 155 |
pass as context settings or command attribute. This method exists for |
| 156 |
one only reason: it enables auto-complete for formatter options, thus |
| 157 |
improving the developer experience. |
| 158 |
|
| 159 |
Parameters are described in :class:`HelpFormatter`. |
| 160 |
""" |
| 161 |
return pick_non_missing(locals()) |
| 162 |
|
| 163 |
@property |
| 164 |
def available_width(self) -> int: |
| 165 |
return self.width - self.current_indent |
| 166 |
|
| 167 |
def write(self, *strings: str) -> None: |
| 168 |
self.buffer += strings |
| 169 |
|
| 170 |
def write_usage( |
| 171 |
self, prog: str, args: str = "", prefix: Optional[str] = None |
| 172 |
) -> None: |
| 173 |
prefix = "Usage:" if prefix is None else prefix |
| 174 |
prefix = self.theme.heading(prefix) + " " |
| 175 |
prog = self.theme.invoked_command(prog) |
| 176 |
super().write_usage(prog, args, prefix) |
| 177 |
|
| 178 |
def write_aliases(self, aliases: Sequence[str]) -> None: |
| 179 |
self.write_heading("Aliases", newline=False) |
| 180 |
alias_list = ", ".join(self.theme.col1(alias) for alias in aliases) |
| 181 |
self.write(f" {alias_list}\n") |
| 182 |
|
| 183 |
def write_command_help_text(self, cmd: click.Command) -> None: |
| 184 |
help_text = cmd.help or "" |
| 185 |
if help_text and click_version_ge_8_1: |
| 186 |
help_text = inspect.cleandoc(help_text).partition("\f")[0] |
| 187 |
if cmd.deprecated: |
| 188 |
# Use the same label as Click: |
| 189 |
# https://github.com/pallets/click/blob/b0538df/src/click/core.py#L1331 |
| 190 |
help_text = "(Deprecated) " + help_text |
| 191 |
if help_text: |
| 192 |
self.write_paragraph() |
| 193 |
with self.indentation(): |
| 194 |
self.write_text(help_text, style=self.theme.command_help) |
| 195 |
|
| 196 |
def write_heading(self, heading: str, newline: bool = True) -> None: |
| 197 |
if self.current_indent: |
| 198 |
self.write(" " * self.current_indent) |
| 199 |
self.write(self.theme.heading(heading + ":")) |
| 200 |
if newline: |
| 201 |
self.write('\n') |
| 202 |
|
| 203 |
def write_many_sections( |
| 204 |
self, sections: Sequence[HelpSection], |
| 205 |
aligned: bool = True, |
| 206 |
) -> None: |
| 207 |
if aligned: |
| 208 |
return self.write_aligned_sections(sections) |
| 209 |
for s in sections: |
| 210 |
self.write_section(s) |
| 211 |
|
| 212 |
def write_aligned_sections(self, sections: Sequence[HelpSection]) -> None: |
| 213 |
"""Write multiple aligned definition lists.""" |
| 214 |
all_rows = chain.from_iterable(dl.definitions for dl in sections) |
| 215 |
col1_width = self.compute_col1_width(all_rows, self.col1_max_width) |
| 216 |
for s in sections: |
| 217 |
self.write_section(s, col1_width=col1_width) |
| 218 |
|
| 219 |
def write_section(self, s: HelpSection, col1_width: Optional[int] = None) -> None: |
| 220 |
theme = self.theme |
| 221 |
self.write("\n") |
| 222 |
self.write_heading(s.heading, newline=not s.constraint) |
| 223 |
if s.constraint: |
| 224 |
constraint_text = f'[{s.constraint}]' |
| 225 |
available_width = self.available_width - len(s.heading) - len(': ') |
| 226 |
if len(constraint_text) <= available_width: |
| 227 |
self.write(" ", theme.constraint(constraint_text), "\n") |
| 228 |
else: |
| 229 |
self.write("\n") |
| 230 |
with self.indentation(): |
| 231 |
self.write_text(constraint_text, theme.constraint) |
| 232 |
|
| 233 |
with self.indentation(): |
| 234 |
if s.help: |
| 235 |
self.write_text(s.help, theme.section_help) |
| 236 |
self.write_dl(s.definitions, col1_width=col1_width) |
| 237 |
|
| 238 |
def write_text(self, text: str, style: IStyle = identity) -> None: |
| 239 |
wrapped = wrap_text( |
| 240 |
text, self.width - self.current_indent, preserve_paragraphs=True) |
| 241 |
if style is identity: |
| 242 |
wrapped_text = textwrap.indent(wrapped, prefix=' ' * self.current_indent) |
| 243 |
else: |
| 244 |
styled_lines = map(style, wrapped.splitlines()) |
| 245 |
lines = indent_lines(styled_lines, width=self.current_indent) |
| 246 |
wrapped_text = "\n".join(lines) |
| 247 |
self.write(wrapped_text, "\n") |
| 248 |
|
| 249 |
def compute_col1_width(self, rows: Iterable[Definition], max_width: int) -> int: |
| 250 |
col1_lengths = (unstyled_len(r[0]) for r in rows) |
| 251 |
lengths_under_limit = (length for length in col1_lengths if length <= max_width) |
| 252 |
return max(lengths_under_limit, default=0) |
| 253 |
|
| 254 |
def write_dl( |
| 255 |
self, rows: Sequence[Definition], |
| 256 |
col_max: Optional[int] = None, # default changed to None wrt parent class |
| 257 |
col_spacing: Optional[int] = None, # default changed to None wrt parent class |
| 258 |
col1_width: Optional[int] = None, |
| 259 |
) -> None: |
| 260 |
"""Write a definition list into the buffer. This is how options |
| 261 |
and commands are usually formatted. |
| 262 |
|
| 263 |
If there's enough space, definition lists are rendered as a 2-column |
| 264 |
pseudo-table: if the first column text of a row doesn't fit in the |
| 265 |
provided/computed ``col1_width``, the 2nd column is printed on the |
| 266 |
following line. |
| 267 |
|
| 268 |
If the available space for the 2nd column is below ``self.col2_min_width``, |
| 269 |
the 2nd "column" is always printed below the 1st, indented with a minimum |
| 270 |
of 3 spaces (or one ``indent_increment`` if that's greater than 3). |
| 271 |
|
| 272 |
:param rows: |
| 273 |
a list of two item tuples for the terms and values. |
| 274 |
:param col_max: |
| 275 |
the maximum width for the 1st column of a definition list; this |
| 276 |
argument is here to not break compatibility with Click; if provided, |
| 277 |
it overrides the attribute ``self.col1_max_width``. |
| 278 |
:param col_spacing: |
| 279 |
number of spaces between the first and second column; |
| 280 |
this argument is here to not break compatibility with Click; |
| 281 |
if provided, it overrides ``self.col_spacing``. |
| 282 |
:param col1_width: |
| 283 |
the width to use for the first column; if not provided, it's |
| 284 |
computed as the length of the longest string under ``self.col1_max_width``; |
| 285 |
useful when you need to align multiple definition lists. |
| 286 |
""" |
| 287 |
# |<----------------------- width ------------------------>| |
| 288 |
# | |<---------- available_width ---------->| |
| 289 |
# | current_indent | col1_width | col_spacing | col2_width | |
| 290 |
|
| 291 |
col1_max_width = min( |
| 292 |
col_max or self.col1_max_width, |
| 293 |
self.available_width, |
| 294 |
) |
| 295 |
col1_width = min( |
| 296 |
col1_width or self.compute_col1_width(rows, col1_max_width), |
| 297 |
col1_max_width, |
| 298 |
) |
| 299 |
col_spacing = col_spacing or self.col_spacing |
| 300 |
col2_width = self.available_width - col1_width - col_spacing |
| 301 |
|
| 302 |
if col2_width < self.col2_min_width: |
| 303 |
self.write_linear_dl(rows) |
| 304 |
else: |
| 305 |
self.write_tabular_dl(rows, col1_width, col_spacing, col2_width) |
| 306 |
|
| 307 |
def _get_row_sep_for( |
| 308 |
self, text_rows: Sequence[Sequence[str]], |
| 309 |
col_widths: Sequence[int], |
| 310 |
col_spacing: int, |
| 311 |
) -> Optional[str]: |
| 312 |
if self.row_sep is None or isinstance(self.row_sep, str): |
| 313 |
return self.row_sep |
| 314 |
|
| 315 |
from .sep import RowSepPolicy |
| 316 |
if isinstance(self.row_sep, RowSepPolicy): |
| 317 |
return self.row_sep(text_rows, col_widths, col_spacing) |
| 318 |
elif callable(self.row_sep): # RowSepPolicy is callable; keep this for last |
| 319 |
return self.row_sep(self.available_width) |
| 320 |
else: |
| 321 |
raise TypeError('row_sep') |
| 322 |
|
| 323 |
def write_tabular_dl( |
| 324 |
self, rows: Sequence[Definition], |
| 325 |
col1_width: int, col_spacing: int, col2_width: int, |
| 326 |
) -> None: |
| 327 |
"""Format a definition list as a 2-column "pseudo-table". If the first |
| 328 |
column of a row exceeds ``col1_width``, the 2nd column is written on |
| 329 |
the subsequent line. This is the standard way of formatting definition |
| 330 |
lists and it's the default if there's enough space.""" |
| 331 |
|
| 332 |
col1_plus_spacing = col1_width + col_spacing |
| 333 |
col2_indentation = " " * ( |
| 334 |
self.current_indent + max(self.indent_increment, col1_plus_spacing) |
| 335 |
) |
| 336 |
indentation = " " * self.current_indent |
| 337 |
|
| 338 |
# Note: iter_defs() resolves eventual callables in row[1] |
| 339 |
text_rows = list(iter_defs(rows, col2_width)) |
| 340 |
row_sep = self._get_row_sep_for(text_rows, (col1_width, col2_width), col_spacing) |
| 341 |
col1_styler, col2_styler = self.theme.col1, self.theme.col2 |
| 342 |
|
| 343 |
def write_row(row: Tuple[str, str]) -> None: |
| 344 |
first, second = row |
| 345 |
self.write(indentation, col1_styler(first)) |
| 346 |
if not second: |
| 347 |
self.write("\n") |
| 348 |
else: |
| 349 |
first_display_length = unstyled_len(first) |
| 350 |
if first_display_length <= col1_width: |
| 351 |
spaces_to_col2 = col1_plus_spacing - first_display_length |
| 352 |
self.write(" " * spaces_to_col2) |
| 353 |
else: |
| 354 |
self.write("\n", col2_indentation) |
| 355 |
|
| 356 |
if len(second) <= col2_width: |
| 357 |
self.write(col2_styler(second), "\n") |
| 358 |
else: |
| 359 |
wrapped_text = wrap_text(second, col2_width, preserve_paragraphs=True) |
| 360 |
lines = [col2_styler(line) for line in wrapped_text.splitlines()] |
| 361 |
self.write(lines[0], "\n") |
| 362 |
for line in lines[1:]: |
| 363 |
self.write(col2_indentation, line, "\n") |
| 364 |
|
| 365 |
write_row(text_rows[0]) |
| 366 |
for row in text_rows[1:]: |
| 367 |
if row_sep is not None: |
| 368 |
self.write(indentation, row_sep, "\n") |
| 369 |
write_row(row) |
| 370 |
|
| 371 |
def write_linear_dl(self, dl: Sequence[Definition]) -> None: |
| 372 |
"""Format a definition list as a "linear list". This is the default when |
| 373 |
the available width for the definitions (2nd column) is below |
| 374 |
``self.col2_min_width``.""" |
| 375 |
help_extra_indent = max(3, self.indent_increment) |
| 376 |
help_total_indent = self.current_indent + help_extra_indent |
| 377 |
help_max_width = self.width - help_total_indent |
| 378 |
current_indentation = " " * self.current_indent |
| 379 |
|
| 380 |
col1_styler = self.theme.col1 |
| 381 |
col2_styler = self.theme.col2 |
| 382 |
|
| 383 |
for names, help in iter_defs(dl, help_max_width): |
| 384 |
self.write(current_indentation + col1_styler(names) + '\n') |
| 385 |
if help: |
| 386 |
self.current_indent += help_extra_indent |
| 387 |
self.write_text(help, col2_styler) |
| 388 |
self.current_indent -= help_extra_indent |
| 389 |
self.write("\n") |
| 390 |
self.buffer.pop() # pop last newline |
| 391 |
|
| 392 |
def write_epilog(self, epilog: str) -> None: |
| 393 |
self.write_text(epilog, self.theme.epilog) |
| 394 |
|
| 395 |
def __repr__(self) -> str: |
| 396 |
return make_repr( |
| 397 |
self, width=self.width, indent_increment=self.indent_increment, |
| 398 |
col1_max_width=self.col1_max_width, col_spacing=self.col_spacing |
| 399 |
) |
| 400 |
|
| 401 |
|
| 402 |
def iter_defs(rows: Iterable[Definition], col2_width: int) -> Iterator[Tuple[str, str]]: |
| 403 |
for row in rows: |
| 404 |
if len(row) == 1: |
| 405 |
yield row[0], '' |
| 406 |
elif len(row) == 2: |
| 407 |
second = row[1](col2_width) if callable(row[1]) else row[1] |
| 408 |
yield row[0], second |
| 409 |
else: |
| 410 |
raise ValueError(f'invalid row length: {len(row)}') |