Debian Codegraph @

cloup/formatting/sep.py

raw
1 """
2 This module contains anything related to separators. Currently, it contains an
3 implementation of "row sep policies", e.g. components that decide if and how to
4 add an extra separator/spacing between the rows of a definition list (only for
5 tabular layout). In the future, it may be expanded with something analogous for
6 help sections.
7 """
8 import abc
9 from itertools import zip_longest
10 from typing import Optional, Protocol, Sequence, Union
11
12 SepType = Union[str, 'SepGenerator']
13
14
15 class SepGenerator(Protocol):
16 """Generate a separator given a width. When used as ``row_sep``, this ``width``
17 corresponds to ``HelpFormatter.available_width``, i.e. the line width excluding
18 the current indentation width.
19
20 Note: the length of the returned separator may differ from ``width``.
21 """
22
23 def __call__(self, width: int) -> str:
24 ...
25
26
27 class RowSepPolicy(metaclass=abc.ABCMeta):
28 """A callable that can be passed as ``row_sep`` to :class:`HelpFormatter` in
29 order to decide *if* a definition list should get a row separator (in
30 addition to ``\\n``) and *which* separator.
31
32 In practice, the row separator should be the same for all definition lists
33 that satisfy a given condition. That's why :class:`RowSepIf`
34 exists, you probably want to use that.
35
36 Nonetheless, this protocol exists mainly for one reason: it leaves open the
37 door to policies that can decide a row separator for each individual row
38 (feature I'm personally against to for now), without breaking changes.
39 This would make possible to implement the old Click 7.2 behavior, which
40 inserted an empty line only after options with a long help. Adding this
41 feature would be possible without breaking changes, by extending the return
42 type to ``Union[None, str, Sequence[str]]``.
43 """
44
45 @abc.abstractmethod
46 def __call__( # noqa E704
47 self, rows: Sequence[Sequence[str]],
48 col_widths: Sequence[int],
49 col_spacing: int,
50 ) -> Optional[str]:
51 """Decide which row separator to use (eventually none) in the given
52 definition list."""
53
54
55 class RowSepCondition(Protocol):
56 """Determines when a definition list should use a row separator."""
57
58 # Ignore error due to flake8 issue: "multiple statements on one line (def)"
59 def __call__( # noqa E704
60 self, rows: Sequence[Sequence[str]],
61 col_widths: Sequence[int],
62 col_spacing: int,
63 ) -> bool:
64 """Return ``True`` if the input definition list should use a row
65 separator (in addition to the usual ``\\n``)."""
66
67
68 class RowSepIf(RowSepPolicy):
69 """
70 Inserts a row separator between the rows of a definition list only if a
71 condition is satisfied. This class implements the ``RowSepPolicy``
72 protocol and does two things:
73
74 - enforces the use of a single row separator for all rows of a
75 definition lists and for all definition lists; note that
76 ``RowSepPolicy`` doesn't for implementation reasons but it's probably
77 what you want;
78 - allows you to implement different conditions (see type
79 :data:`RowSepCondition`) without worrying about the generation part,
80 which is always the same.
81
82 :param condition:
83 a :class:`RowSepCondition` that determines when to add the (extra)
84 row separator.
85 :param sep:
86 either a string or a ``SepGenerator``,
87 i.e. a function ``(width: int) -> str`` (e.g. :class:`Hline`).
88 The empty string corresponds to an empty line separator.
89 """
90
91 def __init__(self, condition: RowSepCondition,
92 sep: Union[str, SepGenerator] = ''):
93 if isinstance(sep, str) and sep.endswith('\n'):
94 raise ValueError(
95 "sep must not end with '\\n'. The formatter writes a '\\n' after it; "
96 "no other newline is allowed.")
97 self.condition = condition
98 self.sep = sep
99
100 def __call__(
101 self, rows: Sequence[Sequence[str]], col_widths: Sequence[int], col_spacing: int
102 ) -> Optional[str]:
103 if self.condition(rows, col_widths, col_spacing):
104 if callable(self.sep):
105 total_width = get_total_width(col_widths, col_spacing)
106 return self.sep(total_width)
107 return self.sep
108 return None
109
110
111 # ==========================================
112 # Conditions & related utils
113
114 def get_total_width(col_widths: Sequence[int], col_spacing: int) -> int:
115 """Return the total width of a definition list (or, more generally, a table).
116 Useful when implementing a RowSepStrategy."""
117 return sum(col_widths) + col_spacing * (len(col_widths) - 1)
118
119
120 def count_multiline_rows(rows: Sequence[Sequence[str]], col_widths: Sequence[int]) -> int:
121 # Note: I'm using zip_longest on purpose so that a TypeError will be raised
122 # if len(row) != len(col_widths). An explicit check is not worth it since
123 # this should never happen.
124 return sum(
125 any(len(col_text) > col_width
126 for col_text, col_width in zip_longest(row, col_widths))
127 for row in rows
128 )
129
130
131 def multiline_rows_are_at_least(
132 count_or_percentage: Union[int, float]
133 ) -> RowSepCondition:
134 """
135 Return a ``RowSepStrategy`` that returns a row separator between all rows
136 of a definition list, only if the number of rows taking multiple lines is
137 greater than or equal to a certain threshold.
138
139 :param count_or_percentage:
140 a threshold for multiline rows above which the returned strategy will
141 insert a row separator. It can be either an absolute count (`int`) or a
142 percentage relative to the total number of rows expressed as a `float`
143 between 0 and 1 (0 and 1 excluded).
144 """
145 if count_or_percentage <= 0:
146 raise ValueError('count_or_percentage should be > 0')
147
148 if isinstance(count_or_percentage, int):
149 count_threshold = count_or_percentage
150
151 def condition(
152 rows: Sequence[Sequence[str]],
153 col_widths: Sequence[int],
154 col_spacing: int,
155 ) -> bool:
156 num_multiline = count_multiline_rows(rows, col_widths)
157 return num_multiline >= count_threshold
158
159 elif isinstance(count_or_percentage, float):
160 percent_threshold = count_or_percentage
161 if percent_threshold > 1.0:
162 raise ValueError(
163 "count_or_percentage must be either an integer or a float in the "
164 f"interval ]0, 1[. You passed a float >= 1.0 ({percent_threshold}).")
165
166 def condition(
167 rows: Sequence[Sequence[str]],
168 col_widths: Sequence[int],
169 col_spacing: int,
170 ) -> bool:
171 num_multiline = count_multiline_rows(rows, col_widths)
172 percent_multiline = num_multiline / len(rows)
173 return percent_multiline >= percent_threshold
174 else:
175 raise TypeError('count_or_percentage must be an int or a float')
176
177 return condition
178
179
180 class Hline(SepGenerator):
181 """Returns a function that generates an horizontal line of a given length.
182
183 This class has different static members for different line styles
184 like ``Hline.solid``, ``Hline.dashed``, ``Hline.densely_dashed``
185 and ``Hline.dotted``.
186
187 :param pattern:
188 a string (usually a single character) that is repeated to generate
189 the line.
190 """
191
192 # Workaround: PyCharm auto-completion doesn't work without these declarations
193 solid: 'Hline'
194 dashed: 'Hline'
195 densely_dashed: 'Hline'
196 dotted: 'Hline'
197
198 def __init__(self, pattern: str):
199 self.pattern = pattern
200
201 def __call__(self, width: int) -> str:
202 pattern = self.pattern
203 if len(pattern) == 1:
204 return pattern * width
205 reps, rest = width // len(pattern), width % len(pattern)
206 return pattern * reps + pattern[:rest]
207
208
209 Hline.solid = Hline("─")
210 """Return a line like ``────────``."""
211
212 Hline.dashed = Hline('-')
213 """Return a line like ``--------``."""
214
215 Hline.densely_dashed = Hline('╌')
216 """Return a line like ``╌╌╌╌╌╌╌╌``."""
217
218 Hline.dotted = Hline("┄")
219 """Return a line like ``┄┄┄┄┄┄┄┄``."""