Debian Codegraph @

autopage/__init__.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 A library to provide automatic paging for console output.
15
16 By Zane Bitter.
17 """
18
19 import codecs
20 import contextlib
21 import enum
22 import io
23 import os
24 import signal
25 import subprocess
26 import sys
27
28 import types
29 import typing
30 from typing import Any, Optional, Type, Dict, TextIO
31
32 from autopage import command
33
34
35 __all__ = ['AutoPager', 'line_buffer_from_input']
36
37
38 class ErrorStrategy(enum.Enum):
39 """
40 The strategy for dealing with unicode errors when convering text to bytes.
41 """
42 STRICT = 'strict'
43 IGNORE = 'ignore'
44 REPLACE = 'replace'
45 BACKSLASH_REPLACE = 'backslashreplace'
46 XML_CHARREF_REPLACE = 'xmlcharrefreplace'
47 NAME_REPLACE = 'namereplace'
48
49
50 class AutoPager:
51 """
52 A context manager that launches a pager for the output if appropriate.
53
54 If the output stream is not to the console (i.e. it is piped or
55 redirected), no pager will be launched.
56 """
57
58 def __init__(self,
59 output_stream: Optional[TextIO] = None, *,
60 pager_command: command.CommandType = command.DefaultPager(),
61 allow_color: bool = True,
62 line_buffering: Optional[bool] = None,
63 reset_on_exit: bool = False,
64 errors: Optional[ErrorStrategy] = None):
65 self._use_stdout = output_stream is None or output_stream is sys.stdout
66 self._out = sys.stdout if output_stream is None else output_stream
67 self._tty = (not self._out.closed) and self._out.isatty()
68 self._command = command.get_pager_command(pager_command)
69 self._config = command.PagerConfig(
70 color=allow_color,
71 line_buffering_requested=bool(line_buffering),
72 reset_terminal=reset_on_exit,
73 )
74 self._set_line_buffering = line_buffering
75 self._set_errors = (ErrorStrategy(errors) if errors is not None
76 else None)
77 self._pager: Optional[subprocess.Popen] = None
78 self._exit_code: typing.Union[int, BaseException] = 0
79
80 def to_terminal(self) -> bool:
81 """Return whether the output stream is a terminal."""
82 return self._tty
83
84 def __enter__(self) -> TextIO:
85 # Only invoke the pager if the output is going to a tty; if it is
86 # being sent to a file or pipe then we don't want the pager involved
87 if self.to_terminal() and self._command.command() != ['cat']:
88 try:
89 return self._paged_stream()
90 except OSError:
91 pass
92 self._reconfigure_output_stream()
93 return self._out
94
95 def _line_buffering(self) -> bool:
96 if self._set_line_buffering is None:
97 return getattr(self._out, 'line_buffering', self._tty)
98 return self._set_line_buffering
99
100 def _encoding(self) -> str:
101 dflt = 'utf-8' if getattr(sys.flags, 'utf8_mode', False) else 'ascii'
102 encoding = getattr(self._out, 'encoding', dflt)
103 try:
104 return codecs.lookup(encoding).name
105 except LookupError:
106 return dflt
107
108 def _errors(self) -> str:
109 if self._set_errors is None:
110 return getattr(self._out, 'errors', ErrorStrategy.STRICT.value)
111 return self._set_errors.value
112
113 def _reconfigure_output_stream(self) -> None:
114 if self._set_line_buffering is None and self._set_errors is None:
115 return
116
117 if not isinstance(self._out, io.TextIOWrapper):
118 return
119
120 # Python 3.7 & later
121 if hasattr(self._out, 'reconfigure'):
122 self._out.reconfigure(line_buffering=self._set_line_buffering,
123 errors=(self._set_errors.value
124 if self._set_errors is not None
125 else None))
126 # Python 3.6
127 elif (self._out.line_buffering != self._line_buffering()
128 or self._out.errors != self._errors()):
129 # Pure-python I/O
130 if (hasattr(self._out, '_line_buffering')
131 and hasattr(self._out, '_errors')):
132 py_out = typing.cast(Any, self._out)
133 py_out._line_buffering = self._line_buffering()
134 py_out._errors = self._errors()
135 py_out.flush()
136 # Native C I/O
137 else:
138 encoding = self._encoding()
139 errors = self._errors()
140 line_buffering = self._line_buffering()
141 try:
142 if self._use_stdout:
143 sys.stdout = typing.cast(TextIO, None)
144 newstream = io.TextIOWrapper(
145 self._out.detach(),
146 line_buffering=line_buffering,
147 encoding=encoding,
148 errors=errors)
149 self._out = newstream
150 finally:
151 if self._use_stdout:
152 sys.stdout = self._out
153
154 def _pager_env(self) -> Optional[Dict[str, str]]:
155 new_vars = self._command.environment_variables(self._config)
156 if not new_vars:
157 return None
158
159 env = dict(os.environ)
160 env.update(new_vars)
161 return env
162
163 def _pager_out_stream(self) -> Optional[TextIO]:
164 if not self._use_stdout:
165 try:
166 # Ensure the output stream has a file descriptor
167 self._out.fileno()
168 except OSError:
169 pass
170 else:
171 return self._out
172 return None
173
174 def _paged_stream(self) -> TextIO:
175 buffer_size = 1 if self._line_buffering() else -1
176 self._pager = subprocess.Popen(self._command.command(),
177 env=self._pager_env(),
178 bufsize=buffer_size,
179 universal_newlines=True,
180 encoding=self._encoding(),
181 errors=self._errors(),
182 stdin=subprocess.PIPE,
183 stdout=self._pager_out_stream())
184 assert self._pager.stdin is not None
185 return typing.cast(TextIO, self._pager.stdin)
186
187 def __exit__(self,
188 exc_type: Optional[Type[BaseException]],
189 exc: Optional[BaseException],
190 traceback: Optional[types.TracebackType]) -> bool:
191 if self._pager is not None:
192 # Pager ignores Ctrl-C, so we should too
193 with _sigint_ignore():
194 pager_in = self._pager.stdin
195 assert pager_in is not None
196 try:
197 pager_in.close()
198 except BrokenPipeError:
199 # Other end of pipe already closed
200 self._exit_code = _signal_exit_code(signal.SIGPIPE)
201 # Wait for user to exit pager
202 self._pager.wait()
203 else:
204 self._flush_output()
205 return self._process_exception(exc)
206
207 def _flush_output(self) -> None:
208 try:
209 if not self._out.closed:
210 self._out.flush()
211 except BrokenPipeError:
212 self._exit_code = _signal_exit_code(signal.SIGPIPE)
213 try:
214 # Other end of pipe already closed, so close the stream now
215 # and handle the error. If we leave the stream open with
216 # unflushed data, then it will print an unhandleable
217 # exception during Python's interpreter shutdown.
218 self._out.close()
219 except BrokenPipeError:
220 # This will always happen
221 pass
222
223 def _process_exception(self, exc: Optional[BaseException]) -> bool:
224 if exc is not None:
225 if isinstance(exc, BrokenPipeError):
226 self._exit_code = _signal_exit_code(signal.SIGPIPE)
227 # Suppress exceptions caused by a broken pipe (indicating that
228 # the user has exited the pager, or the following process in
229 # the pipeline has exited)
230 return True
231 elif isinstance(exc, KeyboardInterrupt):
232 self._exit_code = _signal_exit_code(signal.SIGINT)
233 elif isinstance(exc, SystemExit) and isinstance(exc.code, int):
234 self._exit_code = exc.code
235 else:
236 self._exit_code = exc
237 return False
238
239 def exit_code(self, *, on_error_default: int = 1) -> int:
240 """
241 Return an appropriate exit code for the process based on any errors.
242
243 If the user exits the program prematurely by closing the pager, we may
244 want to return a different exit code for the process. This method
245 returns an appropriate exit code on the basis of the existence and type
246 of any uncaught exceptions.
247 """
248 if not isinstance(self._exit_code, int):
249 return on_error_default
250 return self._exit_code
251
252
253 def line_buffer_from_input(input_stream: Optional[typing.IO] = None) -> bool:
254 """
255 Return whether line buffering should be enabled for a given input stream.
256
257 When data is being read from an input stream, processed somehow, and then
258 written to an autopaged output stream, it may be desirable to enable line
259 buffering on the output. This means that each line of data written to the
260 output will be visible immediately, as opposed to waiting for the output
261 buffer to fill up. This is, however, slower.
262
263 If the input stream is a file, line buffering is unnecessary. This function
264 determines whether an input stream might require line buffering on output.
265
266 If no input stream is specified, sys.stdin is assumed.
267
268 >>> with AutoPager(line_buffering=line_buffer_from_input()) as out:
269 >>> for l in sys.stdin:
270 >>> out.write(l)
271 """
272 if input_stream is None:
273 input_stream = sys.stdin
274 # On Illumos, TTYs claim to be seekable so don't believe them
275 return not (input_stream.seekable() and not input_stream.isatty())
276
277
278 def _signal_exit_code(signum: signal.Signals) -> int:
279 """
280 Return the exit code corresponding to a received signal.
281
282 Conventionally, when a program exits due to a signal its exit code is 128
283 plus the signal number.
284 """
285 return 128 + int(signum)
286
287
288 @contextlib.contextmanager
289 def _sigint_ignore() -> typing.Generator[None, None, None]:
290 """
291 Context manager to temporarily ignore SIGINT.
292 """
293 old_int_handler: Any = None
294 try:
295 old_int_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
296 yield
297 finally:
298 # If this is called from a finalizer during interpreter shutdown,
299 # CPython will have removed the definition of SIG_IGN, so we can't
300 # set the signal handler back to anything. We can detect this by
301 # checking for None returned from getsignal()
302 if signal.getsignal(signal.SIGINT) is not None:
303 signal.signal(signal.SIGINT, old_int_handler)