codewatch-scan 0.1.0__py3-none-any.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.
Files changed (136) hide show
  1. codewatch/__init__.py +0 -0
  2. codewatch/__main__.py +14 -0
  3. codewatch/asgi.py +16 -0
  4. codewatch/settings.py +175 -0
  5. codewatch/urls.py +40 -0
  6. codewatch/wsgi.py +16 -0
  7. codewatch_scan-0.1.0.dist-info/METADATA +81 -0
  8. codewatch_scan-0.1.0.dist-info/RECORD +136 -0
  9. codewatch_scan-0.1.0.dist-info/WHEEL +5 -0
  10. codewatch_scan-0.1.0.dist-info/entry_points.txt +4 -0
  11. codewatch_scan-0.1.0.dist-info/licenses/LICENSE +21 -0
  12. codewatch_scan-0.1.0.dist-info/top_level.txt +2 -0
  13. core/__init__.py +0 -0
  14. core/analyzers/__init__.py +19 -0
  15. core/analyzers/accessibility.py +199 -0
  16. core/analyzers/base.py +192 -0
  17. core/analyzers/body_models.py +154 -0
  18. core/analyzers/codewatch_checks.py +394 -0
  19. core/analyzers/constant_branches.py +251 -0
  20. core/analyzers/containers.py +316 -0
  21. core/analyzers/coverage.py +131 -0
  22. core/analyzers/dependencies.py +347 -0
  23. core/analyzers/drf_serializers.py +65 -0
  24. core/analyzers/else_branches.py +106 -0
  25. core/analyzers/extra.py +400 -0
  26. core/analyzers/flask_resources.py +65 -0
  27. core/analyzers/inline_scripts.py +50 -0
  28. core/analyzers/jinja_sandboxes.py +63 -0
  29. core/analyzers/match_statements.py +148 -0
  30. core/analyzers/multi_tools.py +888 -0
  31. core/analyzers/php_template_sinks.py +444 -0
  32. core/analyzers/project_checks.py +150 -0
  33. core/analyzers/python_tools.py +333 -0
  34. core/analyzers/route_converters.py +237 -0
  35. core/analyzers/slices.py +94 -0
  36. core/analyzers/starred_targets.py +42 -0
  37. core/analyzers/stored_fields.py +386 -0
  38. core/analyzers/summaries.py +1387 -0
  39. core/analyzers/template_sinks.py +162 -0
  40. core/api.py +360 -0
  41. core/apps.py +6 -0
  42. core/benchmark.py +955 -0
  43. core/bundled/catalog/codewatch/rules/javascript-crypto.yml +224 -0
  44. core/bundled/catalog/codewatch/rules/javascript-injection.yml +116 -0
  45. core/bundled/catalog/codewatch/rules/javascript-taint.yml +1539 -0
  46. core/bundled/catalog/codewatch/rules/javascript-web.yml +562 -0
  47. core/bundled/catalog/codewatch/rules/php-web.yml +719 -0
  48. core/bundled/catalog/codewatch/rules/python-crypto.yml +203 -0
  49. core/bundled/catalog/codewatch/rules/python-django.yml +267 -0
  50. core/bundled/catalog/codewatch/rules/python-injection.yml +115 -0
  51. core/bundled/catalog/codewatch/rules/python-web.yml +3382 -0
  52. core/bundled/catalog/custom/mappings.json +360 -0
  53. core/bundled/catalog/custom/overrides.json +4 -0
  54. core/bundled/catalog/custom/rules/django-settings.yml +19 -0
  55. core/bundled/catalog/imported/changes.json +5 -0
  56. core/bundled/catalog/imported/docs.json +1143 -0
  57. core/bundled/catalog/imported/meta.json +54 -0
  58. core/bundled/catalog/imported/rules.json +85421 -0
  59. core/bundled/catalog/imported/standards.json +11191 -0
  60. core/bundled/tools/analyzers.lock +786 -0
  61. core/bundled/tools/axe-scan.mjs +45 -0
  62. core/bundled/tools/checkov.lock +2463 -0
  63. core/bundled/tools/codewatch-checks.mjs +99 -0
  64. core/bundled/tools/eslint-a11y.config.js +16 -0
  65. core/bundled/tools/eslint-quality.config.js +63 -0
  66. core/bundled/tools/eslint-typed.config.js +18 -0
  67. core/bundled/tools/package-lock.json +6102 -0
  68. core/bundled/tools/package.json +32 -0
  69. core/bundled/tools/rule-metadata.mjs +56 -0
  70. core/bundled/tools/semgrep.lock +1232 -0
  71. core/bundled/tools/stylelint.config.json +11 -0
  72. core/catalog/__init__.py +190 -0
  73. core/catalog/build.py +84 -0
  74. core/catalog/merge.py +122 -0
  75. core/catalog/sources.py +418 -0
  76. core/catalog/standards.py +119 -0
  77. core/catalog/update.py +99 -0
  78. core/catalog_views.py +115 -0
  79. core/client.py +645 -0
  80. core/collect.py +518 -0
  81. core/duplicates.py +60 -0
  82. core/fingerprint.py +25 -0
  83. core/folders.py +73 -0
  84. core/gate.py +77 -0
  85. core/git.py +149 -0
  86. core/jobs.py +86 -0
  87. core/management/__init__.py +0 -0
  88. core/management/commands/__init__.py +0 -0
  89. core/management/commands/addproject.py +40 -0
  90. core/management/commands/buildcatalog.py +15 -0
  91. core/management/commands/scan.py +74 -0
  92. core/management/commands/updatecatalog.py +14 -0
  93. core/mcp_server.py +140 -0
  94. core/middleware.py +17 -0
  95. core/migrations/0001_initial.py +115 -0
  96. core/migrations/0002_auth_tokens_a11y.py +60 -0
  97. core/migrations/0003_default_admin.py +43 -0
  98. core/migrations/0004_project_members.py +28 -0
  99. core/migrations/0005_uploads_and_sources.py +55 -0
  100. core/migrations/0006_thresholds.py +28 -0
  101. core/migrations/0007_also_reported_by.py +18 -0
  102. core/migrations/0008_new_code_period.py +18 -0
  103. core/migrations/0009_resolution_safe.py +18 -0
  104. core/migrations/0010_analysis_progress.py +18 -0
  105. core/migrations/0011_overall_gate_conditions.py +20 -0
  106. core/migrations/__init__.py +0 -0
  107. core/models.py +323 -0
  108. core/network.py +41 -0
  109. core/paths.py +29 -0
  110. core/ratings.py +67 -0
  111. core/runner.py +168 -0
  112. core/templates/core/account.html +30 -0
  113. core/templates/core/analysis.html +49 -0
  114. core/templates/core/base.html +121 -0
  115. core/templates/core/form_table.html +12 -0
  116. core/templates/core/gate_badge.html +1 -0
  117. core/templates/core/index.html +26 -0
  118. core/templates/core/issues.html +38 -0
  119. core/templates/core/login.html +13 -0
  120. core/templates/core/new_project.html +27 -0
  121. core/templates/core/password_change.html +10 -0
  122. core/templates/core/project.html +40 -0
  123. core/templates/core/rating.html +1 -0
  124. core/templates/core/ratings.html +32 -0
  125. core/templates/core/rule.html +33 -0
  126. core/templates/core/rules.html +42 -0
  127. core/templates/core/scan_progress.html +2 -0
  128. core/templates/core/settings.html +36 -0
  129. core/templates/core/source.html +15 -0
  130. core/templates/core/standards.html +30 -0
  131. core/templates/core/user_edit.html +15 -0
  132. core/templates/core/users.html +18 -0
  133. core/templatetags/__init__.py +0 -0
  134. core/templatetags/codewatch.py +42 -0
  135. core/tool_setup.py +68 -0
  136. core/views.py +564 -0
@@ -0,0 +1,316 @@
1
+ """Rewrite local containers in Python so Semgrep's taint analysis tracks each slot on its own.
2
+
3
+ Semgrep tracks taint per attribute, but not per constant dict key or list position: after `m["a"] = param;
4
+ m["b"] = "x"` a read of m["a"] comes out clean, and once request data is in a list or ConfigParser every slot reads
5
+ as tainted. In the copy Semgrep scans (never run; every token stays on its line):
6
+
7
+ - constant-key reads and writes of a local dict, and ConfigParser set/get with a constant section and option,
8
+ become attributes (m.k_a), which Semgrep tracks one by one;
9
+ - a constant-index read of a local list, after appends, inserts and pops that run straight-line from where the
10
+ list was created, becomes the literal that slot must hold.
11
+ """
12
+ import ast
13
+ import re
14
+
15
+ SCOPES = (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef)
16
+ CONFIG_PARSERS = {"ConfigParser", "RawConfigParser", "SafeConfigParser"}
17
+ BODY_FIELDS = ("body", "orelse", "finalbody")
18
+
19
+
20
+ def scope_nodes(scope):
21
+ """Nodes in a scope, not descending into nested functions, classes or lambdas."""
22
+ stack = list(ast.iter_child_nodes(scope))
23
+ while stack:
24
+ node = stack.pop()
25
+ yield node
26
+ if not isinstance(node, (*SCOPES, ast.ClassDef, ast.Lambda)):
27
+ stack.extend(ast.iter_child_nodes(node))
28
+
29
+
30
+ def is_dict_value(node):
31
+ return isinstance(node, ast.Dict) or (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
32
+ and node.func.id == "dict" and not node.args)
33
+
34
+
35
+ def is_config_parser(node):
36
+ if not isinstance(node, ast.Call):
37
+ return False
38
+ func = node.func
39
+ return (isinstance(func, ast.Name) and func.id in CONFIG_PARSERS) or (
40
+ isinstance(func, ast.Attribute) and func.attr in CONFIG_PARSERS)
41
+
42
+
43
+ OTHER_BINDINGS = (ast.AnnAssign, ast.AugAssign, ast.NamedExpr, ast.For, ast.AsyncFor, ast.comprehension, ast.withitem,
44
+ ast.Delete)
45
+
46
+
47
+ def assign_bindings(node):
48
+ return [(name.id, node.value if target is name else None)
49
+ for target in node.targets for name in stored_names(target)]
50
+
51
+
52
+ def other_bindings(node):
53
+ targets = getattr(node, "targets", None) or [getattr(node, "target", None) or node.optional_vars]
54
+ return [(name.id, None) for target in targets if target is not None for name in stored_names(target)]
55
+
56
+
57
+ def node_bindings(node):
58
+ """(name, value) for each name a node binds, value None for anything but a plain `name = value`."""
59
+ if isinstance(node, ast.Assign):
60
+ return assign_bindings(node)
61
+ if isinstance(node, OTHER_BINDINGS):
62
+ return other_bindings(node)
63
+ if isinstance(node, (ast.Global, ast.Nonlocal)):
64
+ return [(n, None) for n in node.names]
65
+ return []
66
+
67
+
68
+ def bound_names(nodes):
69
+ """{name: [values assigned to it]}, with None for bindings other than a plain `name = value`."""
70
+ bindings = {}
71
+ for node in nodes:
72
+ for name, value in node_bindings(node):
73
+ bindings.setdefault(name, []).append(value)
74
+ return bindings
75
+
76
+
77
+ def stored_names(target):
78
+ """Names a target binds; m in m["k"] = v is only read."""
79
+ return [n for n in ast.walk(target) if isinstance(n, ast.Name) and isinstance(n.ctx, (ast.Store, ast.Del))]
80
+
81
+
82
+ def only_bound_to(bindings, test):
83
+ return {name for name, values in bindings.items() if all(v is not None and test(v) for v in values)}
84
+
85
+
86
+ def field_name(*keys):
87
+ return "k_" + re.sub(r"\W", "_", "_".join(keys))
88
+
89
+
90
+ def constant_strings(args):
91
+ return all(isinstance(a, ast.Constant) and isinstance(a.value, str) for a in args)
92
+
93
+
94
+ def one_line(node):
95
+ return getattr(node, "lineno", None) is not None and node.lineno == node.end_lineno
96
+
97
+
98
+ def method_call(node, names, method):
99
+ """The call `name.method(...)` on one of names, or None."""
100
+ if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == method
101
+ and isinstance(node.func.value, ast.Name) and node.func.value.id in names):
102
+ return node
103
+ return None
104
+
105
+
106
+ def dict_subscript_edit(node, dicts):
107
+ if (isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and node.value.id in dicts
108
+ and constant_strings([node.slice])):
109
+ return replace(node, f"{node.value.id}.{field_name(node.slice.value)}")
110
+ return None
111
+
112
+
113
+ def dict_get_edit(node, dicts):
114
+ if (call := method_call(node, dicts, "get")) and len(call.args) == 1 and constant_strings(call.args):
115
+ return replace(call, f"{call.func.value.id}.{field_name(call.args[0].value)}")
116
+ return None
117
+
118
+
119
+ def parser_get_edit(node, parsers):
120
+ if (call := method_call(node, parsers, "get")) and len(call.args) == 2 and constant_strings(call.args):
121
+ return replace(call, f"{call.func.value.id}.{field_name(*(a.value for a in call.args))}")
122
+ return None
123
+
124
+
125
+ def parser_set_edit(source, node, parsers):
126
+ if not isinstance(node, ast.Expr):
127
+ return None
128
+ call = method_call(node.value, parsers, "set")
129
+ if not call or len(call.args) != 3 or not constant_strings(call.args[:2]):
130
+ return None
131
+ value = ast.get_source_segment(source, call.args[2])
132
+ return replace(call, f"{call.func.value.id}.{field_name(call.args[0].value, call.args[1].value)} = {value}")
133
+
134
+
135
+ def slot_edit(source, node, dicts, parsers):
136
+ """The rewrite of one constant-key dict or ConfigParser access, or None."""
137
+ return (dict_subscript_edit(node, dicts) or dict_get_edit(node, dicts) or parser_get_edit(node, parsers)
138
+ or parser_set_edit(source, node, parsers))
139
+
140
+
141
+ def slot_edits(source, nodes, dicts, parsers):
142
+ return [edit for node in nodes if one_line(node) and (edit := slot_edit(source, node, dicts, parsers))]
143
+
144
+
145
+ def statement_lists(nodes):
146
+ for node in nodes:
147
+ for field in BODY_FIELDS:
148
+ body = getattr(node, field, None)
149
+ if isinstance(body, list) and body and isinstance(body[0], ast.stmt):
150
+ yield body
151
+ if isinstance(node, ast.ExceptHandler):
152
+ yield node.body
153
+
154
+
155
+ COMPOUND = (ast.If, ast.For, ast.AsyncFor, ast.While, ast.With, ast.AsyncWith, ast.Try, ast.Match, *SCOPES, ast.ClassDef)
156
+
157
+
158
+ def is_slot_read(node, name):
159
+ """`name[3]`: a load of a constant int index."""
160
+ return (isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and node.value.id == name
161
+ and isinstance(node.ctx, ast.Load) and isinstance(node.slice, ast.Constant)
162
+ and type(node.slice.value) is int)
163
+
164
+
165
+ def constant_index_reads(stmt, name):
166
+ """Constant-index loads of `name` in a simple statement, or None if it uses the list any other way."""
167
+ if isinstance(stmt, COMPOUND):
168
+ return None
169
+ reads = [node for node in ast.walk(stmt) if is_slot_read(node, name)]
170
+ inside = {id(node.value) for node in reads}
171
+ uses = [n for n in ast.walk(stmt) if isinstance(n, ast.Name) and n.id == name]
172
+ return reads if all(id(n) in inside for n in uses) else None
173
+
174
+
175
+ def int_indexes(args):
176
+ return [a.value for a in args[:1] if isinstance(a, ast.Constant) and type(a.value) is int]
177
+
178
+
179
+ def append_slot(slots, args):
180
+ if len(args) != 1:
181
+ return False
182
+ slots.append(args[0])
183
+ return True
184
+
185
+
186
+ def insert_slot(slots, args):
187
+ if len(args) != 2 or not int_indexes(args):
188
+ return False
189
+ slots.insert(int_indexes(args)[0], args[1])
190
+ return True
191
+
192
+
193
+ def pop_slot(slots, args):
194
+ if not args and slots:
195
+ slots.pop()
196
+ return True
197
+ if len(args) == 1 and int_indexes(args):
198
+ slots.pop(int_indexes(args)[0])
199
+ return True
200
+ return False
201
+
202
+
203
+ def reverse_slots(slots, args):
204
+ if args:
205
+ return False
206
+ slots.reverse()
207
+ return True
208
+
209
+
210
+ def extend_slots(slots, args):
211
+ if len(args) != 1 or not isinstance(args[0], (ast.List, ast.Tuple)):
212
+ return False
213
+ slots.extend(args[0].elts)
214
+ return True
215
+
216
+
217
+ LIST_METHODS = {"append": append_slot, "insert": insert_slot, "pop": pop_slot, "reverse": reverse_slots,
218
+ "extend": extend_slots}
219
+
220
+
221
+ def list_method_call(stmt, name):
222
+ """`name.method(...)` as a whole statement, or None."""
223
+ if not (isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call)
224
+ and isinstance(stmt.value.func, ast.Attribute)):
225
+ return None
226
+ return method_call(stmt.value, {name}, stmt.value.func.attr)
227
+
228
+
229
+ def mutate(slots, stmt, name):
230
+ """Apply a list method call statement to the simulated slots; False if it isn't one we can follow."""
231
+ call = list_method_call(stmt, name)
232
+ if call is None or call.keywords or call.func.attr not in LIST_METHODS:
233
+ return False
234
+ try:
235
+ return LIST_METHODS[call.func.attr](slots, call.args)
236
+ except IndexError:
237
+ return False
238
+
239
+
240
+ def list_literal(stmt):
241
+ """(name, [its slots]) for `name = [a, b]` without starred items, else None."""
242
+ if (isinstance(stmt, ast.Assign) and len(stmt.targets) == 1 and isinstance(stmt.targets[0], ast.Name)
243
+ and isinstance(stmt.value, ast.List) and not any(isinstance(e, ast.Starred) for e in stmt.value.elts)):
244
+ return stmt.targets[0].id, list(stmt.value.elts)
245
+ return None
246
+
247
+
248
+ def read_edits(source, reads, slots):
249
+ """Each read replaced by the literal its slot holds, where both are on one line."""
250
+ edits = []
251
+ for read in reads:
252
+ index = read.slice.value
253
+ slot = slots[index] if -len(slots) <= index < len(slots) else None
254
+ if isinstance(slot, ast.Constant) and one_line(read) and one_line(slot):
255
+ edits.append(replace(read, ast.get_source_segment(source, slot)))
256
+ return edits
257
+
258
+
259
+ def followed_list_edits(source, later_statements, name, slots):
260
+ """Edits for a list's constant-index reads, following its mutations until a use that can't be followed."""
261
+ edits = []
262
+ for later in later_statements:
263
+ if not any(isinstance(n, ast.Name) and n.id == name for n in ast.walk(later)) or mutate(slots, later, name):
264
+ continue
265
+ reads = constant_index_reads(later, name)
266
+ if reads is None:
267
+ break
268
+ edits += read_edits(source, reads, slots)
269
+ return edits
270
+
271
+
272
+ def list_edits(source, nodes):
273
+ edits = []
274
+ for body in statement_lists(nodes):
275
+ for start, stmt in enumerate(body):
276
+ if found := list_literal(stmt):
277
+ edits += followed_list_edits(source, body[start + 1:], *found)
278
+ return edits
279
+
280
+
281
+ def replace(node, text):
282
+ return node.lineno, node.col_offset, node.end_col_offset, text
283
+
284
+
285
+ def container_edits(source):
286
+ tree = ast.parse(source)
287
+ edits = []
288
+ for scope in [n for n in ast.walk(tree) if isinstance(n, SCOPES)]:
289
+ nodes = list(scope_nodes(scope))
290
+ bindings = bound_names(nodes)
291
+ dicts, parsers = only_bound_to(bindings, is_dict_value), only_bound_to(bindings, is_config_parser)
292
+ edits += slot_edits(source, nodes, dicts, parsers)
293
+ edits += list_edits(source, nodes)
294
+ return edits
295
+
296
+
297
+ def track_slots(source):
298
+ """The source with container slots rewritten (see the module docstring), or None if nothing changes."""
299
+ if "[" not in source and "ConfigParser" not in source:
300
+ return None
301
+ try:
302
+ edits = container_edits(source)
303
+ except (SyntaxError, ValueError):
304
+ return None
305
+ if not edits:
306
+ return None
307
+ lines = source.splitlines(keepends=True)
308
+ applied = {}
309
+ # Reverse order keeps earlier columns valid; an edit nested in one already made is dropped.
310
+ for row, start, end, new in sorted(set(edits), key=lambda e: (e[0], e[1], -e[2]), reverse=True):
311
+ if any(start < s_end and s_start < end for s_start, s_end in applied.get(row, [])):
312
+ continue
313
+ raw = lines[row - 1].encode()
314
+ lines[row - 1] = (raw[:start] + new.encode() + raw[end:]).decode()
315
+ applied.setdefault(row, []).append((start, end))
316
+ return "".join(lines)
@@ -0,0 +1,131 @@
1
+ import ast
2
+ from pathlib import Path
3
+
4
+ import defusedxml.ElementTree as ET
5
+
6
+ from .base import Analyzer, Result, is_test_file
7
+ from .codewatch_checks import docstring_nodes
8
+
9
+
10
+ class Coverage(Analyzer):
11
+ """Imports a Cobertura XML (coverage.py, istanbul) or LCOV report produced by the project's own test run."""
12
+
13
+ name = "coverage"
14
+
15
+ def available(self):
16
+ return True
17
+
18
+ def applies(self, ctx):
19
+ return ctx.coverage_report is not None
20
+
21
+ def run(self, ctx):
22
+ if ctx.coverage_report is None:
23
+ return Result()
24
+ report = Path(ctx.coverage_report)
25
+ lines = parse_lcov(report) if report.suffix in (".info", ".lcov") else parse_cobertura(report)
26
+ result = Result()
27
+ # Tests run in full by definition; counting them would inflate coverage of the code under test.
28
+ sources = [f for f in ctx.files if not is_test_file(f)]
29
+ collect(result, lines, set(sources), Path(ctx.coverage_base or report.parent))
30
+ if any(p.endswith(".py") for p in result.coverable_lines):
31
+ add_unreported(result, Path(ctx.root), sources)
32
+ result.metrics.update(summary(result))
33
+ return result
34
+
35
+
36
+ def summary(result):
37
+ coverable = sum(len(v) for v in result.coverable_lines.values())
38
+ covered = sum(len(v) for v in result.covered_lines.values())
39
+ metrics: dict[str, float] = {"lines_to_cover": coverable, "uncovered_lines": coverable - covered}
40
+ if coverable:
41
+ metrics["coverage"] = round(100 * covered / coverable, 1)
42
+ return metrics
43
+
44
+
45
+ def collect(result, lines, tracked, base):
46
+ by_name = {}
47
+ for f in tracked:
48
+ by_name.setdefault(Path(f).name, []).append(f)
49
+ for candidates, hits in lines:
50
+ path = next((p for p in (resolve(c, base) for c in candidates) if p in tracked), None)
51
+ path = path or match_suffix(candidates, by_name)
52
+ if path is None:
53
+ continue
54
+ result.coverable_lines.setdefault(path, set()).update(hits)
55
+ result.covered_lines.setdefault(path, set()).update(n for n, count in hits.items() if count > 0)
56
+
57
+
58
+ def add_unreported(result, root, files):
59
+ """Python files the test run never imported are untested, not unmeasured: count all their statements."""
60
+ for path in files:
61
+ if not path.endswith(".py") or path in result.coverable_lines:
62
+ continue
63
+ try:
64
+ lines = statement_lines((root / path).read_text(errors="replace"))
65
+ except (OSError, SyntaxError, ValueError):
66
+ continue
67
+ if lines:
68
+ result.coverable_lines[path] = lines
69
+ result.covered_lines[path] = set()
70
+
71
+
72
+ def statement_lines(source):
73
+ """Executable lines as coverage.py reports them: statements, decorators and except clauses, not docstrings."""
74
+ tree = ast.parse(source)
75
+ docstrings = docstring_nodes(tree)
76
+ lines = set()
77
+ for node in ast.walk(tree):
78
+ if isinstance(node, ast.ExceptHandler):
79
+ lines.add(node.lineno)
80
+ elif isinstance(node, ast.stmt) and not (isinstance(node, ast.Expr) and id(node.value) in docstrings):
81
+ lines.add(node.lineno)
82
+ lines.update(d.lineno for d in getattr(node, "decorator_list", []))
83
+ return lines
84
+
85
+
86
+ def match_suffix(candidates, by_name):
87
+ """Reports from CI or another checkout carry absolute paths from that machine; match on the path tail."""
88
+ for c in candidates:
89
+ options = [f for f in by_name.get(Path(c).name, []) if c.replace("\\", "/").endswith("/" + f) or c == f]
90
+ if options:
91
+ return max(options, key=len)
92
+ return None
93
+
94
+
95
+ def resolve(candidate, base):
96
+ p = Path(candidate)
97
+ if p.is_absolute():
98
+ try:
99
+ return str(p.resolve().relative_to(base.resolve()))
100
+ except ValueError:
101
+ return str(p)
102
+ return str(p).removeprefix("./")
103
+
104
+
105
+ def parse_cobertura(report):
106
+ root = ET.parse(report).getroot()
107
+ if root is None:
108
+ return
109
+ sources = [s.text.strip() for s in root.iter("source") if s.text and s.text.strip()]
110
+ for cls in root.iter("class"):
111
+ filename = cls.get("filename")
112
+ if not filename:
113
+ continue
114
+ hits = {}
115
+ for line in cls.iter("line"):
116
+ n = int(line.get("number", "0"))
117
+ hits[n] = max(hits.get(n, 0), int(line.get("hits", "0")))
118
+ yield [str(Path(s) / filename) for s in sources] + [filename], hits
119
+
120
+
121
+ def parse_lcov(report):
122
+ path, hits = None, {}
123
+ for raw in report.read_text().splitlines():
124
+ if raw.startswith("SF:"):
125
+ path, hits = raw[3:], {}
126
+ elif raw.startswith("DA:") and path:
127
+ line, count = raw[3:].split(",")[:2]
128
+ hits[int(line)] = int(count)
129
+ elif raw == "end_of_record" and path:
130
+ yield [path], hits
131
+ path = None