Debian Codegraph @

invoke/util.py

raw ◀ ▶
1 Debian patch touch this file
1 from collections import namedtuple
2 from contextlib import contextmanager
3 from types import TracebackType
4 from typing import Any, Generator, List, IO, Optional, Tuple, Type, Union
5 import io
6 import logging
7 import os
8 import threading
9 import sys
10
11 # NOTE: This is the canonical location for commonly-used vendored modules,
12 # which is the only spot that performs this try/except to allow repackaged
13 # Invoke to function (e.g. distro packages which unvendor the vendored bits and
14 # thus must import our 'vendored' stuff from the overall environment.)
15 # All other uses of Lexicon, etc should do 'from .util import lexicon' etc.
16 # Saves us from having to update the same logic in a dozen places.
17 # TODO: would this make more sense to put _into_ invoke.vendor? That way, the
18 # import lines which now read 'from .util import <third party stuff>' would be
19 # more obvious. Requires packagers to leave invoke/vendor/__init__.py alone tho
20 try:
21 from .vendor.lexicon import Lexicon # noqa
22 except ImportError:
23 from lexicon import Lexicon # type: ignore[no-redef] # noqa
•24 try:
25 from .vendor import yaml # noqa
26 except ImportError:
27 import yaml # type: ignore[no-redef] # noqa
28
29
30 LOG_FORMAT = "%(name)s.%(module)s.%(funcName)s: %(message)s"
31
32
33 def enable_logging() -> None:
34 logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
35
36
37 # Allow from-the-start debugging (vs toggled during load of tasks module) via
38 # shell env var.
39 if os.environ.get("INVOKE_DEBUG"):
40 enable_logging()
41
42 # Add top level logger functions to global namespace. Meh.
43 log = logging.getLogger("invoke")
44 debug = log.debug
45
46
47 def task_name_sort_key(name: str) -> Tuple[List[str], str]:
48 """
49 Return key tuple for use sorting dotted task names, via e.g. `sorted`.
50
51 .. versionadded:: 1.0
52 """
53 parts = name.split(".")
54 return (
55 # First group/sort by non-leaf path components. This keeps everything
56 # grouped in its hierarchy, and incidentally puts top-level tasks
57 # (whose non-leaf path set is the empty list) first, where we want them
58 parts[:-1],
59 # Then we sort lexicographically by the actual task name
60 parts[-1],
61 )
62
63
64 # TODO: Make part of public API sometime
65 @contextmanager
66 def cd(where: str) -> Generator[None, None, None]:
67 cwd = os.getcwd()
68 os.chdir(where)
69 try:
70 yield
71 finally:
72 os.chdir(cwd)
73
74
75 def has_fileno(stream: IO) -> bool:
76 """
77 Cleanly determine whether ``stream`` has a useful ``.fileno()``.
78
79 .. note::
80 This function helps determine if a given file-like object can be used
81 with various terminal-oriented modules and functions such as `select`,
82 `termios`, and `tty`. For most of those, a fileno is all that is
83 required; they'll function even if ``stream.isatty()`` is ``False``.
84
85 :param stream: A file-like object.
86
87 :returns:
88 ``True`` if ``stream.fileno()`` returns an integer, ``False`` otherwise
89 (this includes when ``stream`` lacks a ``fileno`` method).
90
91 .. versionadded:: 1.0
92 """
93 try:
94 return isinstance(stream.fileno(), int)
95 except (AttributeError, io.UnsupportedOperation):
96 return False
97
98
99 def isatty(stream: IO) -> Union[bool, Any]:
100 """
101 Cleanly determine whether ``stream`` is a TTY.
102
103 Specifically, first try calling ``stream.isatty()``, and if that fails
104 (e.g. due to lacking the method entirely) fallback to `os.isatty`.
105
106 .. note::
107 Most of the time, we don't actually care about true TTY-ness, but
108 merely whether the stream seems to have a fileno (per `has_fileno`).
109 However, in some cases (notably the use of `pty.fork` to present a
110 local pseudoterminal) we need to tell if a given stream has a valid
111 fileno but *isn't* tied to an actual terminal. Thus, this function.
112
113 :param stream: A file-like object.
114
115 :returns:
116 A boolean depending on the result of calling ``.isatty()`` and/or
117 `os.isatty`.
118
119 .. versionadded:: 1.0
120 """
121 # If there *is* an .isatty, ask it.
122 if hasattr(stream, "isatty") and callable(stream.isatty):
123 return stream.isatty()
124 # If there wasn't, see if it has a fileno, and if so, ask os.isatty
125 elif has_fileno(stream):
126 return os.isatty(stream.fileno())
127 # If we got here, none of the above worked, so it's reasonable to assume
128 # the darn thing isn't a real TTY.
129 return False
130
131
132 def helpline(obj: object) -> Optional[str]:
133 """
134 Yield an object's first docstring line, or None if there was no docstring.
135
136 .. versionadded:: 1.0
137 """
138 docstring = obj.__doc__
139 if (
140 not docstring
141 or not docstring.strip()
142 or docstring == type(obj).__doc__
143 ):
144 return None
145 return docstring.lstrip().splitlines()[0]
146
147
148 class ExceptionHandlingThread(threading.Thread):
149 """
150 Thread handler making it easier for parent to handle thread exceptions.
151
152 Based in part on Fabric 1's ThreadHandler. See also Fabric GH issue #204.
153
154 When used directly, can be used in place of a regular ``threading.Thread``.
155 If subclassed, the subclass must do one of:
156
157 - supply ``target`` to ``__init__``
158 - define ``_run()`` instead of ``run()``
159
160 This is because this thread's entire point is to wrap behavior around the
161 thread's execution; subclasses could not redefine ``run()`` without
162 breaking that functionality.
163
164 .. versionadded:: 1.0
165 """
166
167 def __init__(self, **kwargs: Any) -> None:
168 """
169 Create a new exception-handling thread instance.
170
171 Takes all regular `threading.Thread` keyword arguments, via
172 ``**kwargs`` for easier display of thread identity when raising
173 captured exceptions.
174 """
175 super().__init__(**kwargs)
176 # No record of why, but Fabric used daemon threads ever since the
177 # switch from select.select, so let's keep doing that.
178 self.daemon = True
179 # Track exceptions raised in run()
180 self.kwargs = kwargs
181 # TODO: legacy cruft that needs to be removed
182 self.exc_info: Optional[
183 Union[
184 Tuple[Type[BaseException], BaseException, TracebackType],
185 Tuple[None, None, None],
186 ]
187 ] = None
188
189 def run(self) -> None:
190 try:
191 # Allow subclasses implemented using the "override run()'s body"
192 # approach to work, by using _run() instead of run(). If that
193 # doesn't appear to be the case, then assume we're being used
194 # directly and just use super() ourselves.
195 # XXX https://github.com/python/mypy/issues/1424
196 if hasattr(self, "_run") and callable(self._run): # type: ignore
197 # TODO: this could be:
198 # - io worker with no 'result' (always local)
199 # - tunnel worker, also with no 'result' (also always local)
200 # - threaded concurrent run(), sudo(), put(), etc, with a
201 # result (not necessarily local; might want to be a subproc or
202 # whatever eventually)
203 # TODO: so how best to conditionally add a "capture result
204 # value of some kind"?
205 # - update so all use cases use subclassing, add functionality
206 # alongside self.exception() that is for the result of _run()
207 # - split out class that does not care about result of _run()
208 # and let it continue acting like a normal thread (meh)
209 # - assume the run/sudo/etc case will use a queue inside its
210 # worker body, orthogonal to how exception handling works
211 self._run() # type: ignore
212 else:
213 super().run()
214 except BaseException:
215 # Store for actual reraising later
216 self.exc_info = sys.exc_info()
217 # And log now, in case we never get to later (e.g. if executing
218 # program is hung waiting for us to do something)
219 msg = "Encountered exception {!r} in thread for {!r}"
220 # Name is either target function's dunder-name, or just "_run" if
221 # we were run subclass-wise.
222 name = "_run"
223 if "target" in self.kwargs:
224 name = self.kwargs["target"].__name__
225 debug(msg.format(self.exc_info[1], name)) # noqa
226
227 def exception(self) -> Optional["ExceptionWrapper"]:
228 """
229 If an exception occurred, return an `.ExceptionWrapper` around it.
230
231 :returns:
232 An `.ExceptionWrapper` managing the result of `sys.exc_info`, if an
233 exception was raised during thread execution. If no exception
234 occurred, returns ``None`` instead.
235
236 .. versionadded:: 1.0
237 """
238 if self.exc_info is None:
239 return None
240 return ExceptionWrapper(self.kwargs, *self.exc_info)
241
242 @property
243 def is_dead(self) -> bool:
244 """
245 Returns ``True`` if not alive and has a stored exception.
246
247 Used to detect threads that have excepted & shut down.
248
249 .. versionadded:: 1.0
250 """
251 # NOTE: it seems highly unlikely that a thread could still be
252 # is_alive() but also have encountered an exception. But hey. Why not
253 # be thorough?
254 return (not self.is_alive()) and self.exc_info is not None
255
256 def __repr__(self) -> str:
257 # TODO: beef this up more
258 return str(self.kwargs["target"].__name__)
259
260
261 # NOTE: ExceptionWrapper defined here, not in exceptions.py, to avoid circular
262 # dependency issues (e.g. Failure subclasses need to use some bits from this
263 # module...)
264 #: A namedtuple wrapping a thread-borne exception & that thread's arguments.
265 #: Mostly used as an intermediate between `.ExceptionHandlingThread` (which
266 #: preserves initial exceptions) and `.ThreadException` (which holds 1..N such
267 #: exceptions, as typically multiple threads are involved.)
268 ExceptionWrapper = namedtuple(
269 "ExceptionWrapper", "kwargs type value traceback"
270 )