Debian Codegraph @

cloup/styling.py

raw
1 """
2 This module contains components that specifically address the styling and theming
3 of the ``--help`` output.
4 """
5 import dataclasses
6 import dataclasses as dc
7 from dataclasses import dataclass
8 from typing import Any, Callable, Dict, Optional
9
10 import click
11
12 from cloup._util import FrozenSpace, click_version_tuple, delete_keys, identity
13 from cloup.typing import MISSING, Possibly
14
15 IStyle = Callable[[str], str]
16 """A callable that takes a string and returns a styled version of it."""
17
18
19 @dataclass(frozen=True)
20 class HelpTheme:
21 """A collection of styles for several elements of the help page.
22
23 A "style" is just a function or a callable that takes a string and returns
24 a styled version of it. This means you can use your favorite styling/color
25 library (like rich, colorful etc). Nonetheless, given that Click has some
26 basic styling functionality built-in, Cloup provides the :class:`Style`
27 class, which is a wrapper of the ``click.style`` function.
28
29 :param invoked_command:
30 Style of the invoked command name (in Usage).
31 :param command_help:
32 Style of the invoked command description (below Usage).
33 :param heading:
34 Style of help section headings.
35 :param constraint:
36 Style of an option group constraint description.
37 :param section_help:
38 Style of the help text of a section (the optional paragraph below the heading).
39 :param col1:
40 Style of the first column of a definition list (options and command names).
41 :param col2:
42 Style of the second column of a definition list (help text).
43 :param epilog:
44 Style of the epilog.
45 :param alias:
46 Style of subcommand aliases in a definition lists.
47 :param alias_secondary:
48 Style of separator and eventual parenthesis/brackets in subcommand alias lists.
49 If not provided, the ``alias`` style will be used.
50 """
51
52 invoked_command: IStyle = identity
53 """Style of the invoked command name (in Usage)."""
54
55 command_help: IStyle = identity
56 """Style of the invoked command description (below Usage)."""
57
58 heading: IStyle = identity
59 """Style of help section headings."""
60
61 constraint: IStyle = identity
62 """Style of an option group constraint description."""
63
64 section_help: IStyle = identity
65 """Style of the help text of a section (the optional paragraph below the heading)."""
66
67 col1: IStyle = identity
68 """Style of the first column of a definition list (options and command names)."""
69
70 col2: IStyle = identity
71 """Style of the second column of a definition list (help text)."""
72
73 alias: IStyle = identity
74 """Style of subcommand aliases in a definition lists."""
75
76 alias_secondary: Optional[IStyle] = None
77 """Style of separator and eventual parenthesis/brackets in subcommand alias lists.
78 If not provided, the ``alias`` style will be used."""
79
80 epilog: IStyle = identity
81 """Style of the epilog."""
82
83 def with_(
84 self, invoked_command: Optional[IStyle] = None,
85 command_help: Optional[IStyle] = None,
86 heading: Optional[IStyle] = None,
87 constraint: Optional[IStyle] = None,
88 section_help: Optional[IStyle] = None,
89 col1: Optional[IStyle] = None,
90 col2: Optional[IStyle] = None,
91 alias: Optional[IStyle] = None,
92 alias_secondary: Possibly[Optional[IStyle]] = MISSING,
93 epilog: Optional[IStyle] = None,
94 ) -> 'HelpTheme':
95 kwargs = {key: val for key, val in locals().items() if val is not None}
96 if alias_secondary is MISSING:
97 del kwargs["alias_secondary"]
98 kwargs.pop('self')
99 if kwargs:
100 return dataclasses.replace(self, **kwargs)
101 return self
102
103 @staticmethod
104 def dark() -> "HelpTheme":
105 """A theme assuming a dark terminal background color."""
106 return HelpTheme(
107 invoked_command=Style(fg='bright_yellow'),
108 heading=Style(fg='bright_white', bold=True),
109 constraint=Style(fg='magenta'),
110 col1=Style(fg='bright_yellow'),
111 alias=Style(fg='yellow'),
112 alias_secondary=Style(fg='white'),
113 )
114
115 @staticmethod
116 def light() -> "HelpTheme":
117 """A theme assuming a light terminal background color."""
118 return HelpTheme(
119 invoked_command=Style(fg='yellow'),
120 heading=Style(fg='bright_blue'),
121 constraint=Style(fg='red'),
122 col1=Style(fg='yellow'),
123 )
124
125
126 @dc.dataclass(frozen=True)
127 class Style:
128 """Wraps :func:`click.style` for a better integration with :class:`HelpTheme`.
129
130 Available colors are defined as static constants in :class:`Color`.
131
132 Arguments are set to ``None`` by default. Passing ``False`` to boolean args
133 or ``Color.reset`` as color causes a reset code to be inserted.
134
135 With respect to :func:`click.style`, this class:
136
137 - has an argument less, ``reset``, which is always ``True``
138 - add the ``text_transform``.
139
140 .. warning::
141 The arguments ``overline``, ``italic`` and ``strikethrough`` are only
142 supported in Click 8 and will be ignored if you are using Click 7.
143
144 :param fg: foreground color
145 :param bg: background color
146 :param bold:
147 :param dim:
148 :param underline:
149 :param overline:
150 :param italic:
151 :param blink:
152 :param reverse:
153 :param strikethrough:
154 :param text_transform:
155 a generic string transformation; useful to apply functions like ``str.upper``
156
157 .. versionadded:: 0.8.0
158 """
159 fg: Optional[str] = None
160 bg: Optional[str] = None
161 bold: Optional[bool] = None
162 dim: Optional[bool] = None
163 underline: Optional[bool] = None
164 overline: Optional[bool] = None
165 italic: Optional[bool] = None
166 blink: Optional[bool] = None
167 reverse: Optional[bool] = None
168 strikethrough: Optional[bool] = None
169 text_transform: Optional[IStyle] = None
170
171 _style_kwargs: Optional[Dict[str, Any]] = dc.field(init=False, default=None)
172
173 def __call__(self, text: str) -> str:
174 if self._style_kwargs is None:
175 kwargs = dc.asdict(self)
176 delete_keys(kwargs, ['text_transform', '_style_kwargs'])
177 if int(click_version_tuple[0]) < 8:
178 # These arguments are not supported in Click < 8. Ignore them.
179 delete_keys(kwargs, ['overline', 'italic', 'strikethrough'])
180 object.__setattr__(self, '_style_kwargs', kwargs)
181 else:
182 kwargs = self._style_kwargs
183
184 if self.text_transform:
185 text = self.text_transform(text)
186 return click.style(text, **kwargs)
187
188
189 class Color(FrozenSpace):
190 """Colors accepted by :class:`Style` and :func:`click.style`."""
191 black = "black"
192 red = "red"
193 green = "green"
194 yellow = "yellow"
195 blue = "blue"
196 magenta = "magenta"
197 cyan = "cyan"
198 white = "white"
199 reset = "reset"
200 bright_black = "bright_black"
201 bright_red = "bright_red"
202 bright_green = "bright_green"
203 bright_yellow = "bright_yellow"
204 bright_blue = "bright_blue"
205 bright_magenta = "bright_magenta"
206 bright_cyan = "bright_cyan"
207 bright_white = "bright_white"
208
209
210 DEFAULT_THEME = HelpTheme()