Debian Codegraph @

autopage/argparse.py

raw symbols SCIP
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 """
14 This module provides a drop-in replacement for the standard library argparse
15 module, with the output of the 'help' action automatically sent to a pager
16 when appropriate.
17
18 To use, replace the code:
19
20 >>> import argparse
21
22 with:
23
24 >>> from autopage import argparse
25
26 Or, alternatively, call the ``autopage.argparse.monkey_patch()`` function to
27 monkey-patch the argparse module. This is useful when you do not control the
28 code that creates the ArgumentParser. The result of calling this function can
29 also be used as a context manager to ensure that the original functionality is
30 restored.
31 """
32
33 import argparse
34 import contextlib
35 import functools
36 import os
37 import sys
38 import types
39 from typing import Any, Sequence, Text, TextIO, Tuple, Type, Optional, Union
40 from typing import Callable, ContextManager, Generator
41
42 import autopage
43
44 from argparse import * # noqa
45
46
47 _HelpFormatter = argparse.HelpFormatter
48
49 _color_attr = '_autopage_color'
50 _original_stream_attr = '_autopage_original_stream'
51
52
53 def help_pager(out_stream: Optional[TextIO] = None) -> autopage.AutoPager:
54 """Return an AutoPager suitable for help output."""
55 return autopage.AutoPager(out_stream,
56 allow_color=True,
57 line_buffering=False,
58 reset_on_exit=False)
59
60
61 def use_color_for_parser(parser: argparse.ArgumentParser,
62 color: bool) -> None:
63 """Configure a parser whether to output in color from HelpFormatters."""
64 if os.getenv('FORCE_COLOR') is None:
65 if (os.getenv('NO_COLOR') is not None or
66 os.getenv('TERM') == 'dumb' or
67 (not sys.flags.ignore_environment and
68 os.getenv('PYTHON_COLORS') == '0')):
69 color = False
70 elif sys.platform == 'win32':
71 try:
72 import nt
73 if not nt._supports_virtual_terminal():
74 color = False
75 except (ImportError, AttributeError):
76 color = False
77 parser.color = color
78
79
80 class ColorHelpFormatter(_HelpFormatter):
81 class _Section(_HelpFormatter._Section): # type: ignore
82 @property
83 def heading(self) -> Optional[Text]:
84 if (not self._heading
85 or self._heading == argparse.SUPPRESS
86 or not getattr(self.formatter, _color_attr, False)):
87 return self._heading
88 return f'\033[4m{self._heading}\033[0m'
89
90 @heading.setter
91 def heading(self, heading: Optional[Text]) -> None:
92 self._heading = heading
93
94 def _metavar_formatter(self,
95 action: argparse.Action,
96 default_metavar: Text) -> Callable[[int],
97 Tuple[str, ...]]:
98 get_metavars = super()._metavar_formatter(action, default_metavar)
99 if not getattr(self, _color_attr, False):
100 return get_metavars
101
102 def color_metavar(size: int) -> Tuple[str, ...]:
103 return tuple(f'\033[3m{mv}\033[0m' for mv in get_metavars(size))
104 return color_metavar
105
106
107 class ColorRawDescriptionHelpFormatter(ColorHelpFormatter,
108 argparse.RawDescriptionHelpFormatter):
109 """Help message formatter which retains any formatting in descriptions."""
110
111
112 class ColorRawTextHelpFormatter(ColorHelpFormatter,
113 argparse.RawTextHelpFormatter):
114 """Help message formatter which retains formatting of all help text."""
115
116
117 class ColorArgDefaultsHelpFormatter(ColorHelpFormatter,
118 argparse.ArgumentDefaultsHelpFormatter):
119 """Help message formatter which adds default values to argument help."""
120
121
122 class ColorMetavarTypeHelpFormatter(ColorHelpFormatter,
123 argparse.MetavarTypeHelpFormatter):
124 """Help message formatter which uses the argument 'type' as the default
125 metavar value (instead of the argument 'dest')"""
126
127
128 class _HelpAction(argparse._HelpAction):
129 def __init__(self,
130 option_strings: Sequence[Text],
131 dest: Text = argparse.SUPPRESS,
132 default: Text = argparse.SUPPRESS,
133 help: Optional[Text] = None) -> None:
134 argparse.Action.__init__(
135 self,
136 option_strings=option_strings,
137 dest=dest,
138 default=default,
139 nargs=0,
140 help=help)
141
142 def __call__(self, parser: argparse.ArgumentParser,
143 namespace: argparse.Namespace,
144 values: Union[Text, Sequence[Any], None],
145 option_string: Optional[Text] = None) -> None:
146 pager = help_pager()
147 with pager as out:
148 if out is not pager._out:
149 setattr(out, _original_stream_attr, pager._out)
150 use_color_for_parser(parser, (pager.to_terminal() and
151 getattr(parser, 'color', True)))
152 parser.print_help(out)
153 parser.exit(pager.exit_code())
154
155
156 class _ActionsContainer(argparse._ActionsContainer):
157 def __init__(self, *args, **kwargs) -> None: # type: ignore
158 super().__init__(*args, **kwargs)
159 self.register('action', 'help', _HelpAction)
160
161
162 def _substitute_formatter(
163 get_fmtr: Callable[[Any], _HelpFormatter]
164 ) -> Callable[[argparse.ArgumentParser], _HelpFormatter]:
165 @functools.wraps(get_fmtr)
166 def _get_formatter(parser: argparse.ArgumentParser,
167 file: Optional[TextIO] = None) -> _HelpFormatter:
168 if parser.formatter_class is _HelpFormatter:
169 parser.formatter_class = HelpFormatter
170 kwargs = {}
171 if file is not None:
172 kwargs['file'] = getattr(file, _original_stream_attr, file)
173 formatter = get_fmtr(parser, **kwargs)
174 if isinstance(formatter, ColorHelpFormatter):
175 setattr(formatter, _color_attr,
176 getattr(parser, 'color', False))
177 return formatter
178 return _get_formatter
179
180
181 class AutoPageArgumentParser(argparse.ArgumentParser, _ActionsContainer):
182 @_substitute_formatter
183 def _get_formatter(self, file: Optional[TextIO] = None) -> _HelpFormatter:
184 kwargs = {}
185 if file is not None:
186 kwargs['file'] = file
187 return super()._get_formatter(**kwargs)
188
189
190 ArgumentParser = AutoPageArgumentParser # type: ignore
191 if sys.version_info < (3, 14):
192 HelpFormatter = ColorHelpFormatter # type: ignore
193 RawDescriptionHelpFormatter = \
194 ColorRawDescriptionHelpFormatter # type: ignore
195 RawTextHelpFormatter = \
196 ColorRawTextHelpFormatter # type: ignore
197 ArgumentDefaultsHelpFormatter = \
198 ColorArgDefaultsHelpFormatter # type: ignore
199 MetavarTypeHelpFormatter = \
200 ColorMetavarTypeHelpFormatter # type: ignore
201
202
203 def monkey_patch() -> ContextManager:
204 """
205 Monkey-patch the system argparse module to automatically page help output.
206
207 The result of calling this function can optionally be used as a context
208 manager to restore the status quo when it exits.
209 """
210 import sys
211
212 def get_existing_classes(module: types.ModuleType) -> Tuple[Type, ...]:
213 return (
214 module._HelpAction, # type: ignore
215 module.HelpFormatter, # type: ignore
216 module.RawDescriptionHelpFormatter, # type: ignore
217 module.RawTextHelpFormatter, # type: ignore
218 module.ArgumentDefaultsHelpFormatter, # type: ignore
219 module.MetavarTypeHelpFormatter, # type: ignore
220 ) # type: ignore
221
222 def patch_classes(module: types.ModuleType,
223 impl: Tuple[Type, ...]) -> None:
224 (
225 module._HelpAction, # type: ignore
226 module.HelpFormatter, # type: ignore
227 module.RawDescriptionHelpFormatter, # type: ignore
228 module.RawTextHelpFormatter, # type: ignore
229 module.ArgumentDefaultsHelpFormatter, # type: ignore
230 module.MetavarTypeHelpFormatter, # type: ignore
231 ) = impl
232
233 orig = get_existing_classes(argparse)
234 orig_fmtr = argparse.ArgumentParser._get_formatter
235 patched = get_existing_classes(sys.modules[__name__])
236 patch_classes(argparse, patched)
237 new_fmtr = _substitute_formatter(orig_fmtr)
238 argparse.ArgumentParser._get_formatter = new_fmtr # type: ignore
239
240 @contextlib.contextmanager
241 def unpatcher() -> Generator:
242 try:
243 yield
244 finally:
245 patch_classes(argparse, orig)
246 argparse.ArgumentParser._get_formatter = orig_fmtr # type: ignore
247
248 return unpatcher()
249
250
251 __all__ = argparse.__all__ + [ # type: ignore
252 'use_color_for_parser', 'monkey_patch'
253 ]