coverage 7.13.1__cp313-cp313-musllinux_1_2_riscv64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- a1_coverage.pth +1 -0
- coverage/__init__.py +38 -0
- coverage/__main__.py +12 -0
- coverage/annotate.py +113 -0
- coverage/bytecode.py +197 -0
- coverage/cmdline.py +1220 -0
- coverage/collector.py +487 -0
- coverage/config.py +732 -0
- coverage/context.py +74 -0
- coverage/control.py +1514 -0
- coverage/core.py +139 -0
- coverage/data.py +251 -0
- coverage/debug.py +669 -0
- coverage/disposition.py +59 -0
- coverage/env.py +135 -0
- coverage/exceptions.py +85 -0
- coverage/execfile.py +329 -0
- coverage/files.py +553 -0
- coverage/html.py +860 -0
- coverage/htmlfiles/coverage_html.js +735 -0
- coverage/htmlfiles/favicon_32.png +0 -0
- coverage/htmlfiles/index.html +199 -0
- coverage/htmlfiles/keybd_closed.png +0 -0
- coverage/htmlfiles/pyfile.html +149 -0
- coverage/htmlfiles/style.css +389 -0
- coverage/htmlfiles/style.scss +844 -0
- coverage/inorout.py +590 -0
- coverage/jsonreport.py +200 -0
- coverage/lcovreport.py +218 -0
- coverage/misc.py +381 -0
- coverage/multiproc.py +120 -0
- coverage/numbits.py +146 -0
- coverage/parser.py +1215 -0
- coverage/patch.py +118 -0
- coverage/phystokens.py +197 -0
- coverage/plugin.py +617 -0
- coverage/plugin_support.py +299 -0
- coverage/pth_file.py +16 -0
- coverage/py.typed +1 -0
- coverage/python.py +272 -0
- coverage/pytracer.py +370 -0
- coverage/regions.py +127 -0
- coverage/report.py +298 -0
- coverage/report_core.py +117 -0
- coverage/results.py +502 -0
- coverage/sqldata.py +1212 -0
- coverage/sqlitedb.py +226 -0
- coverage/sysmon.py +509 -0
- coverage/templite.py +319 -0
- coverage/tomlconfig.py +212 -0
- coverage/tracer.cpython-313-riscv64-linux-musl.so +0 -0
- coverage/tracer.pyi +43 -0
- coverage/types.py +214 -0
- coverage/version.py +35 -0
- coverage/xmlreport.py +263 -0
- coverage-7.13.1.dist-info/METADATA +200 -0
- coverage-7.13.1.dist-info/RECORD +61 -0
- coverage-7.13.1.dist-info/WHEEL +5 -0
- coverage-7.13.1.dist-info/entry_points.txt +4 -0
- coverage-7.13.1.dist-info/licenses/LICENSE.txt +177 -0
- coverage-7.13.1.dist-info/top_level.txt +1 -0
coverage/pytracer.py
ADDED
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
|
|
2
|
+
# For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
|
|
3
|
+
|
|
4
|
+
"""Raw data collector for coverage.py."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import atexit
|
|
9
|
+
import dis
|
|
10
|
+
import itertools
|
|
11
|
+
import sys
|
|
12
|
+
import threading
|
|
13
|
+
from collections.abc import Callable
|
|
14
|
+
from types import FrameType, ModuleType
|
|
15
|
+
from typing import Any, cast
|
|
16
|
+
|
|
17
|
+
from coverage import env
|
|
18
|
+
from coverage.types import (
|
|
19
|
+
TArc,
|
|
20
|
+
TFileDisposition,
|
|
21
|
+
TLineNo,
|
|
22
|
+
Tracer,
|
|
23
|
+
TShouldStartContextFn,
|
|
24
|
+
TShouldTraceFn,
|
|
25
|
+
TTraceData,
|
|
26
|
+
TTraceFileData,
|
|
27
|
+
TTraceFn,
|
|
28
|
+
TWarnFn,
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
# I don't understand why, but if we use `cast(set[TLineNo], ...)` inside
|
|
32
|
+
# the _trace() function, we get some strange behavior on PyPy 3.10.
|
|
33
|
+
# Assigning these names here and using them below fixes the problem.
|
|
34
|
+
# See https://github.com/coveragepy/coveragepy/issues/1902
|
|
35
|
+
set_TLineNo = set[TLineNo]
|
|
36
|
+
set_TArc = set[TArc]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# We need the YIELD_VALUE opcode below, in a comparison-friendly form.
|
|
40
|
+
# PYVERSIONS: RESUME is new in Python3.11
|
|
41
|
+
RESUME = dis.opmap.get("RESUME")
|
|
42
|
+
RETURN_VALUE = dis.opmap["RETURN_VALUE"]
|
|
43
|
+
if RESUME is None:
|
|
44
|
+
YIELD_VALUE = dis.opmap["YIELD_VALUE"]
|
|
45
|
+
YIELD_FROM = dis.opmap["YIELD_FROM"]
|
|
46
|
+
YIELD_FROM_OFFSET = 0 if env.PYPY else 2
|
|
47
|
+
else:
|
|
48
|
+
YIELD_VALUE = YIELD_FROM = YIELD_FROM_OFFSET = -1
|
|
49
|
+
|
|
50
|
+
# When running meta-coverage, this file can try to trace itself, which confuses
|
|
51
|
+
# everything. Don't trace ourselves.
|
|
52
|
+
|
|
53
|
+
THIS_FILE = __file__.rstrip("co")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class PyTracer(Tracer):
|
|
57
|
+
"""Python implementation of the raw data tracer."""
|
|
58
|
+
|
|
59
|
+
# Because of poor implementations of trace-function-manipulating tools,
|
|
60
|
+
# the Python trace function must be kept very simple. In particular, there
|
|
61
|
+
# must be only one function ever set as the trace function, both through
|
|
62
|
+
# sys.settrace, and as the return value from the trace function. Put
|
|
63
|
+
# another way, the trace function must always return itself. It cannot
|
|
64
|
+
# swap in other functions, or return None to avoid tracing a particular
|
|
65
|
+
# frame.
|
|
66
|
+
#
|
|
67
|
+
# The trace manipulator that introduced this restriction is DecoratorTools,
|
|
68
|
+
# which sets a trace function, and then later restores the pre-existing one
|
|
69
|
+
# by calling sys.settrace with a function it found in the current frame.
|
|
70
|
+
#
|
|
71
|
+
# Systems that use DecoratorTools (or similar trace manipulations) must use
|
|
72
|
+
# PyTracer to get accurate results. The command-line --timid argument is
|
|
73
|
+
# used to force the use of this tracer.
|
|
74
|
+
|
|
75
|
+
tracer_ids = itertools.count()
|
|
76
|
+
|
|
77
|
+
def __init__(self) -> None:
|
|
78
|
+
# Which tracer are we?
|
|
79
|
+
self.id = next(self.tracer_ids)
|
|
80
|
+
|
|
81
|
+
# Attributes set from the collector:
|
|
82
|
+
self.data: TTraceData
|
|
83
|
+
self.trace_arcs = False
|
|
84
|
+
self.should_trace: TShouldTraceFn
|
|
85
|
+
self.should_trace_cache: dict[str, TFileDisposition | None]
|
|
86
|
+
self.should_start_context: TShouldStartContextFn | None = None
|
|
87
|
+
self.switch_context: Callable[[str | None], None] | None = None
|
|
88
|
+
self.lock_data: Callable[[], None]
|
|
89
|
+
self.unlock_data: Callable[[], None]
|
|
90
|
+
self.warn: TWarnFn
|
|
91
|
+
|
|
92
|
+
# The threading module to use, if any.
|
|
93
|
+
self.threading: ModuleType | None = None
|
|
94
|
+
|
|
95
|
+
self.cur_file_data: TTraceFileData | None = None
|
|
96
|
+
self.last_line: TLineNo = 0
|
|
97
|
+
self.cur_file_name: str | None = None
|
|
98
|
+
self.context: str | None = None
|
|
99
|
+
self.started_context = False
|
|
100
|
+
|
|
101
|
+
# The data_stack parallels the Python call stack. Each entry is
|
|
102
|
+
# information about an active frame, a four-element tuple:
|
|
103
|
+
# [0] The TTraceData for this frame's file. Could be None if we
|
|
104
|
+
# aren't tracing this frame.
|
|
105
|
+
# [1] The current file name for the frame. None if we aren't tracing
|
|
106
|
+
# this frame.
|
|
107
|
+
# [2] The last line number executed in this frame.
|
|
108
|
+
# [3] Boolean: did this frame start a new context?
|
|
109
|
+
self.data_stack: list[tuple[TTraceFileData | None, str | None, TLineNo, bool]] = []
|
|
110
|
+
self.thread: threading.Thread | None = None
|
|
111
|
+
self.stopped = False
|
|
112
|
+
self._activity = False
|
|
113
|
+
|
|
114
|
+
self.in_atexit = False
|
|
115
|
+
# On exit, self.in_atexit = True
|
|
116
|
+
atexit.register(setattr, self, "in_atexit", True)
|
|
117
|
+
|
|
118
|
+
# Cache a bound method on the instance, so that we don't have to
|
|
119
|
+
# re-create a bound method object all the time.
|
|
120
|
+
self._cached_bound_method_trace: TTraceFn = self._trace
|
|
121
|
+
|
|
122
|
+
def __repr__(self) -> str:
|
|
123
|
+
points = sum(len(v) for v in self.data.values())
|
|
124
|
+
files = len(self.data)
|
|
125
|
+
return f"<PyTracer at {id(self):#x}: {points} data points in {files} files>"
|
|
126
|
+
|
|
127
|
+
def log(self, marker: str, *args: Any) -> None:
|
|
128
|
+
"""For hard-core logging of what this tracer is doing."""
|
|
129
|
+
with open("/tmp/debug_trace.txt", "a", encoding="utf-8") as f:
|
|
130
|
+
f.write(f"{marker} {self.id}[{len(self.data_stack)}]")
|
|
131
|
+
if 0: # if you want thread ids..
|
|
132
|
+
f.write( # type: ignore[unreachable]
|
|
133
|
+
".{:x}.{:x}".format(
|
|
134
|
+
self.thread.ident,
|
|
135
|
+
self.threading.current_thread().ident,
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
f.write(" {}".format(" ".join(map(str, args))))
|
|
139
|
+
if 0: # if you want callers..
|
|
140
|
+
f.write(" | ") # type: ignore[unreachable]
|
|
141
|
+
stack = " / ".join(
|
|
142
|
+
(fname or "???").rpartition("/")[-1] for _, fname, _, _ in self.data_stack
|
|
143
|
+
)
|
|
144
|
+
f.write(stack)
|
|
145
|
+
f.write("\n")
|
|
146
|
+
|
|
147
|
+
def _trace(
|
|
148
|
+
self,
|
|
149
|
+
frame: FrameType,
|
|
150
|
+
event: str,
|
|
151
|
+
arg: Any, # pylint: disable=unused-argument
|
|
152
|
+
lineno: TLineNo | None = None, # pylint: disable=unused-argument
|
|
153
|
+
) -> TTraceFn | None:
|
|
154
|
+
"""The trace function passed to sys.settrace."""
|
|
155
|
+
|
|
156
|
+
if THIS_FILE in frame.f_code.co_filename:
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
# f = frame; code = f.f_code
|
|
160
|
+
# self.log(":", f"{code.co_filename} {f.f_lineno} {code.co_name}()", event)
|
|
161
|
+
|
|
162
|
+
if self.stopped and sys.gettrace() == self._cached_bound_method_trace: # pylint: disable=comparison-with-callable
|
|
163
|
+
# The PyTrace.stop() method has been called, possibly by another
|
|
164
|
+
# thread, let's deactivate ourselves now.
|
|
165
|
+
if 0:
|
|
166
|
+
f = frame # type: ignore[unreachable]
|
|
167
|
+
self.log("---\nX", f.f_code.co_filename, f.f_lineno)
|
|
168
|
+
while f:
|
|
169
|
+
self.log(">", f.f_code.co_filename, f.f_lineno, f.f_code.co_name, f.f_trace)
|
|
170
|
+
f = f.f_back
|
|
171
|
+
sys.settrace(None)
|
|
172
|
+
try:
|
|
173
|
+
self.cur_file_data, self.cur_file_name, self.last_line, self.started_context = (
|
|
174
|
+
self.data_stack.pop()
|
|
175
|
+
)
|
|
176
|
+
except IndexError:
|
|
177
|
+
self.log(
|
|
178
|
+
"Empty stack!",
|
|
179
|
+
frame.f_code.co_filename,
|
|
180
|
+
frame.f_lineno,
|
|
181
|
+
frame.f_code.co_name,
|
|
182
|
+
)
|
|
183
|
+
return None
|
|
184
|
+
|
|
185
|
+
# if event != "call" and frame.f_code.co_filename != self.cur_file_name:
|
|
186
|
+
# self.log("---\n*", frame.f_code.co_filename, self.cur_file_name, frame.f_lineno)
|
|
187
|
+
|
|
188
|
+
if event == "call":
|
|
189
|
+
# Should we start a new context?
|
|
190
|
+
if self.should_start_context and self.context is None:
|
|
191
|
+
context_maybe = self.should_start_context(frame) # pylint: disable=not-callable
|
|
192
|
+
if context_maybe is not None:
|
|
193
|
+
self.context = context_maybe
|
|
194
|
+
started_context = True
|
|
195
|
+
assert self.switch_context is not None
|
|
196
|
+
self.switch_context(self.context) # pylint: disable=not-callable
|
|
197
|
+
else:
|
|
198
|
+
started_context = False
|
|
199
|
+
else:
|
|
200
|
+
started_context = False
|
|
201
|
+
self.started_context = started_context
|
|
202
|
+
|
|
203
|
+
# Entering a new frame. Decide if we should trace in this file.
|
|
204
|
+
self._activity = True
|
|
205
|
+
self.data_stack.append(
|
|
206
|
+
(
|
|
207
|
+
self.cur_file_data,
|
|
208
|
+
self.cur_file_name,
|
|
209
|
+
self.last_line,
|
|
210
|
+
started_context,
|
|
211
|
+
),
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
# Improve tracing performance: when calling a function, both caller
|
|
215
|
+
# and callee are often within the same file. if that's the case, we
|
|
216
|
+
# don't have to re-check whether to trace the corresponding
|
|
217
|
+
# function (which is a little bit expensive since it involves
|
|
218
|
+
# dictionary lookups). This optimization is only correct if we
|
|
219
|
+
# didn't start a context.
|
|
220
|
+
filename = frame.f_code.co_filename
|
|
221
|
+
if filename != self.cur_file_name or started_context:
|
|
222
|
+
self.cur_file_name = filename
|
|
223
|
+
disp = self.should_trace_cache.get(filename)
|
|
224
|
+
if disp is None:
|
|
225
|
+
disp = self.should_trace(filename, frame)
|
|
226
|
+
self.should_trace_cache[filename] = disp
|
|
227
|
+
|
|
228
|
+
self.cur_file_data = None
|
|
229
|
+
if disp.trace:
|
|
230
|
+
tracename = disp.source_filename
|
|
231
|
+
assert tracename is not None
|
|
232
|
+
self.lock_data()
|
|
233
|
+
try:
|
|
234
|
+
if tracename not in self.data:
|
|
235
|
+
self.data[tracename] = set()
|
|
236
|
+
finally:
|
|
237
|
+
self.unlock_data()
|
|
238
|
+
self.cur_file_data = self.data[tracename]
|
|
239
|
+
else:
|
|
240
|
+
frame.f_trace_lines = False
|
|
241
|
+
elif not self.cur_file_data:
|
|
242
|
+
frame.f_trace_lines = False
|
|
243
|
+
|
|
244
|
+
# The call event is really a "start frame" event, and happens for
|
|
245
|
+
# function calls and re-entering generators. The f_lasti field is
|
|
246
|
+
# -1 for calls, and a real offset for generators. Use <0 as the
|
|
247
|
+
# line number for calls, and the real line number for generators.
|
|
248
|
+
if RESUME is not None:
|
|
249
|
+
# The current opcode is guaranteed to be RESUME. The argument
|
|
250
|
+
# determines what kind of resume it is.
|
|
251
|
+
oparg = frame.f_code.co_code[frame.f_lasti + 1]
|
|
252
|
+
real_call = (oparg == 0) # fmt: skip
|
|
253
|
+
else:
|
|
254
|
+
real_call = (getattr(frame, "f_lasti", -1) < 0) # fmt: skip
|
|
255
|
+
if real_call:
|
|
256
|
+
self.last_line = -frame.f_code.co_firstlineno
|
|
257
|
+
else:
|
|
258
|
+
self.last_line = frame.f_lineno
|
|
259
|
+
|
|
260
|
+
elif event == "line":
|
|
261
|
+
# Record an executed line.
|
|
262
|
+
if self.cur_file_data is not None:
|
|
263
|
+
flineno: TLineNo = frame.f_lineno
|
|
264
|
+
|
|
265
|
+
if self.trace_arcs:
|
|
266
|
+
cast(set_TArc, self.cur_file_data).add((self.last_line, flineno))
|
|
267
|
+
else:
|
|
268
|
+
cast(set_TLineNo, self.cur_file_data).add(flineno)
|
|
269
|
+
self.last_line = flineno
|
|
270
|
+
|
|
271
|
+
elif event == "return":
|
|
272
|
+
if self.trace_arcs and self.cur_file_data:
|
|
273
|
+
# Record an arc leaving the function, but beware that a
|
|
274
|
+
# "return" event might just mean yielding from a generator.
|
|
275
|
+
code = frame.f_code.co_code
|
|
276
|
+
lasti = frame.f_lasti
|
|
277
|
+
if RESUME is not None:
|
|
278
|
+
if len(code) == lasti + 2:
|
|
279
|
+
# A return from the end of a code object is a real return.
|
|
280
|
+
real_return = True
|
|
281
|
+
else:
|
|
282
|
+
# It is a real return if we aren't going to resume next.
|
|
283
|
+
if env.PYBEHAVIOR.lasti_is_yield:
|
|
284
|
+
lasti += 2
|
|
285
|
+
real_return = code[lasti] != RESUME
|
|
286
|
+
else:
|
|
287
|
+
if code[lasti] == RETURN_VALUE:
|
|
288
|
+
real_return = True
|
|
289
|
+
elif code[lasti] == YIELD_VALUE:
|
|
290
|
+
real_return = False
|
|
291
|
+
elif len(code) <= lasti + YIELD_FROM_OFFSET:
|
|
292
|
+
real_return = True
|
|
293
|
+
elif code[lasti + YIELD_FROM_OFFSET] == YIELD_FROM:
|
|
294
|
+
real_return = False
|
|
295
|
+
else:
|
|
296
|
+
real_return = True
|
|
297
|
+
if real_return:
|
|
298
|
+
first = frame.f_code.co_firstlineno
|
|
299
|
+
cast(set_TArc, self.cur_file_data).add((self.last_line, -first))
|
|
300
|
+
|
|
301
|
+
# Leaving this function, pop the filename stack.
|
|
302
|
+
self.cur_file_data, self.cur_file_name, self.last_line, self.started_context = (
|
|
303
|
+
self.data_stack.pop()
|
|
304
|
+
)
|
|
305
|
+
# Leaving a context?
|
|
306
|
+
if self.started_context:
|
|
307
|
+
assert self.switch_context is not None
|
|
308
|
+
self.context = None
|
|
309
|
+
self.switch_context(None) # pylint: disable=not-callable
|
|
310
|
+
|
|
311
|
+
return self._cached_bound_method_trace
|
|
312
|
+
|
|
313
|
+
def start(self) -> TTraceFn:
|
|
314
|
+
"""Start this Tracer.
|
|
315
|
+
|
|
316
|
+
Return a Python function suitable for use with sys.settrace().
|
|
317
|
+
|
|
318
|
+
"""
|
|
319
|
+
self.stopped = False
|
|
320
|
+
if self.threading:
|
|
321
|
+
if self.thread is None:
|
|
322
|
+
self.thread = self.threading.current_thread()
|
|
323
|
+
|
|
324
|
+
sys.settrace(self._cached_bound_method_trace)
|
|
325
|
+
return self._cached_bound_method_trace
|
|
326
|
+
|
|
327
|
+
def stop(self) -> None:
|
|
328
|
+
"""Stop this Tracer."""
|
|
329
|
+
# Get the active tracer callback before setting the stop flag to be
|
|
330
|
+
# able to detect if the tracer was changed prior to stopping it.
|
|
331
|
+
tf = sys.gettrace()
|
|
332
|
+
|
|
333
|
+
# Set the stop flag. The actual call to sys.settrace(None) will happen
|
|
334
|
+
# in the self._trace callback itself to make sure to call it from the
|
|
335
|
+
# right thread.
|
|
336
|
+
self.stopped = True
|
|
337
|
+
|
|
338
|
+
if self.threading:
|
|
339
|
+
assert self.thread is not None
|
|
340
|
+
if self.thread.ident != self.threading.current_thread().ident:
|
|
341
|
+
# Called on a different thread than started us: we can't unhook
|
|
342
|
+
# ourselves, but we've set the flag that we should stop, so we
|
|
343
|
+
# won't do any more tracing.
|
|
344
|
+
# self.log("~", "stopping on different threads")
|
|
345
|
+
return
|
|
346
|
+
|
|
347
|
+
# PyPy clears the trace function before running atexit functions,
|
|
348
|
+
# so don't warn if we are in atexit on PyPy and the trace function
|
|
349
|
+
# has changed to None. Metacoverage also messes this up, so don't
|
|
350
|
+
# warn if we are measuring ourselves.
|
|
351
|
+
suppress_warning = (env.PYPY and self.in_atexit and tf is None) or env.METACOV
|
|
352
|
+
if self.warn and not suppress_warning:
|
|
353
|
+
if tf != self._cached_bound_method_trace: # pylint: disable=comparison-with-callable
|
|
354
|
+
self.warn(
|
|
355
|
+
"Trace function changed, data is likely wrong: "
|
|
356
|
+
+ f"{tf!r} != {self._cached_bound_method_trace!r}",
|
|
357
|
+
slug="trace-changed",
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
def activity(self) -> bool:
|
|
361
|
+
"""Has there been any activity?"""
|
|
362
|
+
return self._activity
|
|
363
|
+
|
|
364
|
+
def reset_activity(self) -> None:
|
|
365
|
+
"""Reset the activity() flag."""
|
|
366
|
+
self._activity = False
|
|
367
|
+
|
|
368
|
+
def get_stats(self) -> dict[str, int] | None:
|
|
369
|
+
"""Return a dictionary of statistics, or None."""
|
|
370
|
+
return None
|
coverage/regions.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
|
|
2
|
+
# For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
|
|
3
|
+
|
|
4
|
+
"""Find functions and classes in Python code."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ast
|
|
9
|
+
import dataclasses
|
|
10
|
+
from typing import cast
|
|
11
|
+
|
|
12
|
+
from coverage.plugin import CodeRegion
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclasses.dataclass
|
|
16
|
+
class Context:
|
|
17
|
+
"""The nested named context of a function or class."""
|
|
18
|
+
|
|
19
|
+
name: str
|
|
20
|
+
kind: str
|
|
21
|
+
lines: set[int]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class RegionFinder:
|
|
25
|
+
"""An ast visitor that will find and track regions of code.
|
|
26
|
+
|
|
27
|
+
Functions and classes are tracked by name. Results are in the .regions
|
|
28
|
+
attribute.
|
|
29
|
+
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(self) -> None:
|
|
33
|
+
self.regions: list[CodeRegion] = []
|
|
34
|
+
self.context: list[Context] = []
|
|
35
|
+
|
|
36
|
+
def parse_source(self, source: str) -> None:
|
|
37
|
+
"""Parse `source` and walk the ast to populate the .regions attribute."""
|
|
38
|
+
self.handle_node(ast.parse(source))
|
|
39
|
+
|
|
40
|
+
def fq_node_name(self) -> str:
|
|
41
|
+
"""Get the current fully qualified name we're processing."""
|
|
42
|
+
return ".".join(c.name for c in self.context)
|
|
43
|
+
|
|
44
|
+
def handle_node(self, node: ast.AST) -> None:
|
|
45
|
+
"""Recursively handle any node."""
|
|
46
|
+
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
47
|
+
self.handle_FunctionDef(node)
|
|
48
|
+
elif isinstance(node, ast.ClassDef):
|
|
49
|
+
self.handle_ClassDef(node)
|
|
50
|
+
else:
|
|
51
|
+
self.handle_node_body(node)
|
|
52
|
+
|
|
53
|
+
def handle_node_body(self, node: ast.AST) -> None:
|
|
54
|
+
"""Recursively handle the nodes in this node's body, if any."""
|
|
55
|
+
for body_node in getattr(node, "body", ()):
|
|
56
|
+
self.handle_node(body_node)
|
|
57
|
+
|
|
58
|
+
def handle_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None:
|
|
59
|
+
"""Called for `def` or `async def`."""
|
|
60
|
+
lines = set(range(node.body[0].lineno, cast(int, node.body[-1].end_lineno) + 1))
|
|
61
|
+
if self.context and self.context[-1].kind == "class":
|
|
62
|
+
# Function bodies are part of their enclosing class.
|
|
63
|
+
self.context[-1].lines |= lines
|
|
64
|
+
# Function bodies should be excluded from the nearest enclosing function.
|
|
65
|
+
for ancestor in reversed(self.context):
|
|
66
|
+
if ancestor.kind == "function":
|
|
67
|
+
ancestor.lines -= lines
|
|
68
|
+
break
|
|
69
|
+
self.context.append(Context(node.name, "function", lines))
|
|
70
|
+
self.regions.append(
|
|
71
|
+
CodeRegion(
|
|
72
|
+
kind="function",
|
|
73
|
+
name=self.fq_node_name(),
|
|
74
|
+
start=node.lineno,
|
|
75
|
+
lines=lines,
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
self.handle_node_body(node)
|
|
79
|
+
self.context.pop()
|
|
80
|
+
|
|
81
|
+
def handle_ClassDef(self, node: ast.ClassDef) -> None:
|
|
82
|
+
"""Called for `class`."""
|
|
83
|
+
# The lines for a class are the lines in the methods of the class.
|
|
84
|
+
# We start empty, and count on visit_FunctionDef to add the lines it
|
|
85
|
+
# finds.
|
|
86
|
+
lines: set[int] = set()
|
|
87
|
+
self.context.append(Context(node.name, "class", lines))
|
|
88
|
+
self.regions.append(
|
|
89
|
+
CodeRegion(
|
|
90
|
+
kind="class",
|
|
91
|
+
name=self.fq_node_name(),
|
|
92
|
+
start=node.lineno,
|
|
93
|
+
lines=lines,
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
self.handle_node_body(node)
|
|
97
|
+
self.context.pop()
|
|
98
|
+
# Class bodies should be excluded from the enclosing classes.
|
|
99
|
+
for ancestor in reversed(self.context):
|
|
100
|
+
if ancestor.kind == "class":
|
|
101
|
+
ancestor.lines -= lines
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def code_regions(source: str) -> list[CodeRegion]:
|
|
105
|
+
"""Find function and class regions in source code.
|
|
106
|
+
|
|
107
|
+
Analyzes the code in `source`, and returns a list of :class:`CodeRegion`
|
|
108
|
+
objects describing functions and classes as regions of the code::
|
|
109
|
+
|
|
110
|
+
[
|
|
111
|
+
CodeRegion(kind="function", name="func1", start=8, lines={10, 11, 12}),
|
|
112
|
+
CodeRegion(kind="function", name="MyClass.method", start=30, lines={34, 35, 36}),
|
|
113
|
+
CodeRegion(kind="class", name="MyClass", start=25, lines={34, 35, 36}),
|
|
114
|
+
]
|
|
115
|
+
|
|
116
|
+
The line numbers will include comments and blank lines. Later processing
|
|
117
|
+
will need to ignore those lines as needed.
|
|
118
|
+
|
|
119
|
+
Nested functions and classes are excluded from their enclosing region. No
|
|
120
|
+
line should be reported as being part of more than one function, or more
|
|
121
|
+
than one class. Lines in methods are reported as being in a function and
|
|
122
|
+
in a class.
|
|
123
|
+
|
|
124
|
+
"""
|
|
125
|
+
rf = RegionFinder()
|
|
126
|
+
rf.parse_source(source)
|
|
127
|
+
return rf.regions
|