graphlore 0.7.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.
graphlore/scope.py ADDED
@@ -0,0 +1,362 @@
1
+ """Analysis scope: which part of the graph the analysis tools look at.
2
+
3
+ One ``scope`` string is shared by the analysis tools (god nodes, validate,
4
+ cycles, surprises, duplication scan, unreferenced, same names). By default it
5
+ leaves out what is not the project's own code — vendored or minified files and
6
+ nodes standing for external packages — and says how much it left out, so a
7
+ bundled third-party script cannot dominate a degree ranking or a cycle list.
8
+
9
+ Depends on :mod:`graphlore.graph` for the node/edge accessors and on
10
+ :mod:`graphlore.spans` for the confined, cached per-file read.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import fnmatch
15
+ import re
16
+ from collections import Counter
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+
20
+ from . import config
21
+ from .graph import _edge_ends, _is_external_node, _is_test_path, _node_file, _node_id
22
+ from .spans import _cached_file_analysis, _is_test_node, _norm_relpath
23
+
24
+ # Directory names that hold third-party code checked into the repository.
25
+ _VENDOR_DIR_PARTS = frozenset({
26
+ "vendor", "vendors", "vendored", "_vendor", "node_modules", "bower_components",
27
+ "third_party", "third-party", "thirdparty", "site-packages",
28
+ })
29
+ # Extensions whose files get shipped minified; only these are sniffed by content.
30
+ _MINIFIABLE_EXTS = frozenset({".js", ".mjs", ".cjs", ".css"})
31
+ # A build hash in a file name: ``decorate-BgofJUJ5.js``, ``main.3f2a1b9c.js``.
32
+ _HASHED_NAME = re.compile(r"[-.]([A-Za-z0-9_]{8,})\.(?:js|mjs|cjs|css)$")
33
+ # Mean line length above which a file is treated as minified. Hand-written
34
+ # source sits far below this even with the odd long line; a bundle sits far above.
35
+ _MINIFIED_MEAN_LINE = 150
36
+ _SNIFF_BYTES = 65536
37
+
38
+ # rel path -> (mtime, is-minified); same (path, mtime) scheme as the span cache.
39
+ _MINIFIED_CACHE: dict[str, tuple[float, bool]] = {}
40
+
41
+
42
+ def _looks_hashed(token: str) -> bool:
43
+ """A random-looking build hash, not a word: mixes digits with both letter
44
+ cases, or is hexadecimal with digits and letters."""
45
+ has_digit = any(c.isdigit() for c in token)
46
+ if not has_digit:
47
+ return False
48
+ if all(c in "0123456789abcdef" for c in token):
49
+ return any(c.isalpha() for c in token)
50
+ return any(c.isupper() for c in token) and any(c.islower() for c in token)
51
+
52
+
53
+ def _vendored_by_path(rel: str) -> bool:
54
+ """Vendored or minified judging by the path alone (no disk access)."""
55
+ parts = rel.split("/")
56
+ if any(p.lower() in _VENDOR_DIR_PARTS for p in parts[:-1]):
57
+ return True
58
+ name = parts[-1]
59
+ low = name.lower()
60
+ if ".min." in low or ".bundle." in low:
61
+ return True
62
+ m = _HASHED_NAME.search(name)
63
+ return bool(m and _looks_hashed(m.group(1)))
64
+
65
+
66
+ def _minified_by_content(rel: str) -> bool:
67
+ """True when a JS/CSS file's lines are far too long to be hand-written."""
68
+ dot = rel.rfind(".")
69
+ if dot < 0 or rel[dot:].lower() not in _MINIFIABLE_EXTS:
70
+ return False
71
+
72
+ def compute(src: bytes, _rel: str) -> bool:
73
+ head = src[:_SNIFF_BYTES]
74
+ if not head.strip():
75
+ return False
76
+ return len(head) / (head.count(b"\n") + 1) > _MINIFIED_MEAN_LINE
77
+
78
+ return bool(_cached_file_analysis(_MINIFIED_CACHE, rel, compute, lambda: False))
79
+
80
+
81
+ def _is_vendored_file(rel: str) -> bool:
82
+ """Vendored or minified: by directory, by name, or by the look of its lines."""
83
+ return _vendored_by_path(rel) or _minified_by_content(rel)
84
+
85
+
86
+ def _path_matches(pattern: str, path: str) -> bool:
87
+ """Match a project-relative file path against a scope/layer pattern.
88
+
89
+ A plain pattern is a path prefix at a directory boundary (``src/pkg`` covers
90
+ ``src/pkg/a.py``), or the module file itself (``src/pkg/core`` covers
91
+ ``src/pkg/core.py``). A pattern with ``*``/``?``/``[`` is a glob over the
92
+ whole path, where ``*`` also crosses ``/``.
93
+ """
94
+ if any(c in pattern for c in "*?["):
95
+ return fnmatch.fnmatchcase(path, pattern) or fnmatch.fnmatchcase(path, pattern + "/*")
96
+ if path == pattern or path.startswith(pattern + "/"):
97
+ return True
98
+ return path.rsplit(".", 1)[0] == pattern
99
+
100
+
101
+ def _clean_pattern(pattern: str) -> str:
102
+ p = _norm_relpath(pattern).strip()
103
+ for tail in ("/**", "/*", "/"):
104
+ if p.endswith(tail):
105
+ p = p[: -len(tail)]
106
+ return p
107
+
108
+
109
+ _FLAGS = {
110
+ "tests": "tests", "test": "tests",
111
+ "external": "external", "externals": "external",
112
+ "vendored": "vendored", "vendor": "vendored", "minified": "vendored",
113
+ }
114
+
115
+
116
+ @dataclass(frozen=True)
117
+ class Scope:
118
+ """A parsed ``scope`` argument. A flag is None when the caller did not say,
119
+ so each tool keeps its own default for it."""
120
+
121
+ spec: str = ""
122
+ include: tuple[str, ...] = ()
123
+ exclude: tuple[str, ...] = ()
124
+ tests: bool | None = None
125
+ external: bool | None = None
126
+ vendored: bool | None = None
127
+
128
+
129
+ def _parse_scope(spec: str) -> Scope | str:
130
+ """Parse a scope string; an error message (str) names the token it rejects.
131
+
132
+ Tokens are separated by commas or whitespace:
133
+ ``src/pkg``, ``**/*.py`` keep only files under this prefix / matching this glob
134
+ ``!docs`` leave these files out
135
+ ``+tests`` / ``-tests`` include / leave out test code
136
+ ``+external`` / ``-external`` include / leave out nodes for external packages
137
+ ``+vendored`` / ``-vendored`` include / leave out vendored and minified files
138
+ ``all`` everything: +tests +external +vendored
139
+ """
140
+ include: list[str] = []
141
+ exclude: list[str] = []
142
+ flags: dict[str, bool] = {}
143
+ for tok in re.split(r"[,\s]+", (spec or "").strip()):
144
+ if not tok:
145
+ continue
146
+ if tok.lower() == "all":
147
+ flags.update(tests=True, external=True, vendored=True)
148
+ elif tok[0] in "+-":
149
+ name = _FLAGS.get(tok[1:].lower())
150
+ if name is None:
151
+ return (
152
+ f"ERROR: unknown scope flag '{tok}'. Flags: +tests / -tests, "
153
+ "+external, +vendored, or 'all'. Anything else is a path prefix or "
154
+ "glob to keep, or '!pattern' to leave out."
155
+ )
156
+ flags[name] = tok[0] == "+"
157
+ elif tok[0] == "!":
158
+ if _clean_pattern(tok[1:]):
159
+ exclude.append(_clean_pattern(tok[1:]))
160
+ elif _clean_pattern(tok):
161
+ include.append(_clean_pattern(tok))
162
+ return Scope(
163
+ spec=" ".join((spec or "").split()),
164
+ include=tuple(include),
165
+ exclude=tuple(exclude),
166
+ tests=flags.get("tests"),
167
+ external=flags.get("external"),
168
+ vendored=flags.get("vendored"),
169
+ )
170
+
171
+
172
+ # How much of the vendored-file list each scoped result carries: a few example
173
+ # paths and the directories that hold most of them.
174
+ _VENDORED_EXAMPLES = 3
175
+ _VENDORED_DIRS_LISTED = 3
176
+
177
+
178
+ @dataclass
179
+ class ScopeView:
180
+ """The nodes and edges a scope keeps, and a count of what it left out.
181
+
182
+ When nothing is left out, ``nodes`` and ``edges`` ARE the lists passed in, so
183
+ the identity-keyed adjacency / label caches keep hitting. Otherwise the
184
+ filtered lists are built once per graph and reused (see ``_scoped``).
185
+ """
186
+
187
+ nodes: list[dict]
188
+ edges: list[dict]
189
+ scope: Scope
190
+ vendored_nodes: int = 0
191
+ vendored_files: list[str] = field(default_factory=list)
192
+ external_nodes: int = 0
193
+ test_nodes: int = 0
194
+ filtered_nodes: int = 0
195
+ keep_tests: bool = True
196
+ keep_vendored: bool = True
197
+
198
+ def keeps_file(self, rel: str) -> bool:
199
+ """Whether this scope keeps a file the graph has no node for (a routes file
200
+ with no symbols): the same path, test and vendored rules as for nodes."""
201
+ rel = _norm_relpath(rel)
202
+ if not self.keep_vendored and _is_vendored_file(rel):
203
+ return False
204
+ if not self.keep_tests and _is_test_path(rel):
205
+ return False
206
+ if self.scope.include and not any(_path_matches(p, rel) for p in self.scope.include):
207
+ return False
208
+ return not any(_path_matches(p, rel) for p in self.scope.exclude)
209
+
210
+ @property
211
+ def left_out(self) -> int:
212
+ return (
213
+ self.vendored_nodes + self.external_nodes + self.test_nodes + self.filtered_nodes
214
+ )
215
+
216
+ def vendored_dirs(self, n: int = _VENDORED_DIRS_LISTED) -> list[dict[str, Any]]:
217
+ """The ``n`` directories holding the most vendored/minified files."""
218
+ counts = Counter(f.rsplit("/", 1)[0] if "/" in f else "." for f in self.vendored_files)
219
+ return [{"dir": d, "files": c} for d, c in counts.most_common(n)]
220
+
221
+ def payload(self) -> dict[str, Any]:
222
+ """The ``scope`` object every scoped tool returns.
223
+
224
+ It rides on every analysis result, so the vendored files are summarized —
225
+ a count, a few examples and the directories holding most of them — not
226
+ listed; graphlore_validate returns the full list.
227
+ """
228
+ return {
229
+ "spec": self.scope.spec or "default",
230
+ "left_out": {
231
+ "vendored_nodes": self.vendored_nodes,
232
+ "vendored_file_count": len(self.vendored_files),
233
+ "vendored_files": self.vendored_files[:_VENDORED_EXAMPLES],
234
+ "vendored_dirs": self.vendored_dirs(),
235
+ "external_nodes": self.external_nodes,
236
+ "test_nodes": self.test_nodes,
237
+ "filtered_nodes": self.filtered_nodes,
238
+ },
239
+ }
240
+
241
+ def note(self) -> str:
242
+ """One line saying what was left out and how to get it back; "" if nothing."""
243
+ bits: list[str] = []
244
+ hints: list[str] = []
245
+ if self.vendored_nodes:
246
+ n = len(self.vendored_files)
247
+ bits.append(
248
+ f"{self.vendored_nodes} node(s) from {n} vendored/minified file(s)"
249
+ )
250
+ hints.append("+vendored")
251
+ if self.external_nodes:
252
+ bits.append(f"{self.external_nodes} external node(s)")
253
+ hints.append("+external")
254
+ if self.test_nodes:
255
+ bits.append(f"{self.test_nodes} test node(s)")
256
+ hints.append("+tests")
257
+ if self.filtered_nodes:
258
+ bits.append(f"{self.filtered_nodes} node(s) outside the include/exclude patterns")
259
+ if not bits:
260
+ return ""
261
+ how = f' (scope="{" ".join(hints)}" or "all" to include)' if hints else ""
262
+ return "Left out of scope: " + ", ".join(bits) + how + "."
263
+
264
+
265
+ # (id(nodes), id(edges)) -> {cache key: view}, with an identity guard on both
266
+ # lists — the scheme of graph._ADJ_CACHE. The filtered lists a view holds must
267
+ # stay the same objects across calls, or every identity-keyed cache downstream
268
+ # (adjacency, display labels) would miss on each call.
269
+ _SCOPE_CACHE: dict[tuple[int, int], tuple[list[dict], list[dict], dict[str, ScopeView]]] = {}
270
+ _SCOPE_CACHE_MAX = 8
271
+
272
+
273
+ def _build_view(
274
+ nodes: list[dict], edges: list[dict], scope: Scope, tests: bool, external: bool,
275
+ vendored: bool,
276
+ ) -> ScopeView:
277
+ view = ScopeView(nodes=nodes, edges=edges, scope=scope,
278
+ keep_tests=tests, keep_vendored=vendored)
279
+ vendored_cache: dict[str, bool] = {}
280
+ vendored_files: set[str] = set()
281
+ dropped: set[str] = set()
282
+ kept: list[dict] = []
283
+ for n in nodes:
284
+ rel = _norm_relpath(_node_file(n))
285
+ reason = ""
286
+ if rel and not vendored:
287
+ is_v = vendored_cache.get(rel)
288
+ if is_v is None:
289
+ is_v = vendored_cache[rel] = _is_vendored_file(rel)
290
+ if is_v:
291
+ reason = "vendored"
292
+ vendored_files.add(rel)
293
+ if not reason and not external and _is_external_node(n):
294
+ reason = "external"
295
+ if not reason and not tests and rel and _is_test_node(n):
296
+ reason = "tests"
297
+ if not reason and (scope.include or scope.exclude):
298
+ if scope.include and not (rel and any(_path_matches(p, rel) for p in scope.include)):
299
+ # an explicitly included external node has no path to match
300
+ if not (external and _is_external_node(n)):
301
+ reason = "filtered"
302
+ if not reason and rel and any(_path_matches(p, rel) for p in scope.exclude):
303
+ reason = "filtered"
304
+ if not reason:
305
+ kept.append(n)
306
+ continue
307
+ dropped.add(_node_id(n))
308
+ if reason == "vendored":
309
+ view.vendored_nodes += 1
310
+ elif reason == "external":
311
+ view.external_nodes += 1
312
+ elif reason == "tests":
313
+ view.test_nodes += 1
314
+ else:
315
+ view.filtered_nodes += 1
316
+ if not dropped:
317
+ return view # nothing left out: hand back the very lists we were given
318
+ view.vendored_files = sorted(vendored_files)
319
+ view.nodes = kept
320
+ # An edge survives when neither endpoint was left out. An endpoint that is no
321
+ # node at all (a dangling edge) is kept: that is graphlore_validate's finding.
322
+ view.edges = [
323
+ e for e in edges
324
+ if not any(end in dropped for end in _edge_ends(e))
325
+ ]
326
+ return view
327
+
328
+
329
+ def _scoped(
330
+ nodes: list[dict], edges: list[dict], spec: str = "", default_tests: bool = True,
331
+ navigation: bool = False,
332
+ ) -> ScopeView | str:
333
+ """The view of ``nodes``/``edges`` that ``spec`` keeps, or an error string.
334
+
335
+ ``default_tests`` is what a tool does about test code when the spec does not
336
+ say (``+tests`` / ``-tests`` always win). ``navigation`` is for the tools that
337
+ walk out from one node the caller named (impact, subgraph, neighbors): they
338
+ leave nothing out unless the spec asks, where the tools that rank or audit
339
+ the whole graph leave out vendored files and external nodes by default.
340
+ """
341
+ scope = _parse_scope(spec)
342
+ if isinstance(scope, str):
343
+ return scope
344
+ tests = default_tests if scope.tests is None else scope.tests
345
+ external = navigation if scope.external is None else scope.external
346
+ vendored = navigation if scope.vendored is None else scope.vendored
347
+ key = f"{config.PROJECT_DIR}\0{scope.spec}\0{tests}\0{external}\0{vendored}"
348
+ ident = (id(nodes), id(edges))
349
+ cached = _SCOPE_CACHE.get(ident)
350
+ if cached is not None and cached[0] is nodes and cached[1] is edges:
351
+ views = cached[2]
352
+ else:
353
+ if ident not in _SCOPE_CACHE and len(_SCOPE_CACHE) >= _SCOPE_CACHE_MAX:
354
+ _SCOPE_CACHE.pop(next(iter(_SCOPE_CACHE)), None) # FIFO
355
+ views = {}
356
+ _SCOPE_CACHE[ident] = (nodes, edges, views)
357
+ view = views.get(key)
358
+ if view is None:
359
+ if len(views) >= 16:
360
+ views.pop(next(iter(views)), None)
361
+ view = views[key] = _build_view(nodes, edges, scope, tests, external, vendored)
362
+ return view