|
| 1 | +"""Stage 0: which frameworks is this project actually using? (#27) |
| 2 | +
|
| 3 | +Gates every later stage, so a project without Celery never pays for Celery |
| 4 | +rules and cannot false-positive on a locally-defined ``shared_task``. A |
| 5 | +package counts as present if first-party source imports it OR the dependency |
| 6 | +manifest names it -- either is sufficient, since an import may be dynamic. |
| 7 | +""" |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import re |
| 11 | +from pathlib import Path |
| 12 | +from typing import Optional, Set |
| 13 | + |
| 14 | +from codeanalyzer.entrypoints.rules import RuleSet |
| 15 | +from codeanalyzer.schema.py_schema import PyApplication |
| 16 | + |
| 17 | +_REQ = re.compile(r"^\s*['\"]?([A-Za-z0-9_.\-]+)") |
| 18 | +_DEPS_START = re.compile(r"dependencies\s*=\s*\[") |
| 19 | +_TABLE_HEADER = re.compile(r"(?m)^[ \t]*\[") |
| 20 | +_PKG = re.compile(r"['\"]([A-Za-z0-9][A-Za-z0-9_.\-]*)") |
| 21 | + |
| 22 | + |
| 23 | +def detected_frameworks(app: PyApplication, project_dir: Path, rules: RuleSet) -> Set[str]: |
| 24 | + # `present` (imports, manifest names) and `detect:` values are both |
| 25 | + # lowercased before comparison -- manifest names were already lowercased |
| 26 | + # (PyPI/pip is case-insensitive) but imports and `detect:` were not, so |
| 27 | + # a `detect: [Flask]` user rule silently never matched a `flask` import. |
| 28 | + present = _imported_packages(app) | _manifest_packages(project_dir) |
| 29 | + return { |
| 30 | + name |
| 31 | + for name, fw in rules.frameworks.items() |
| 32 | + if any(pkg.lower() in present for pkg in (fw.detect or [name])) |
| 33 | + } |
| 34 | + |
| 35 | + |
| 36 | +def _imported_packages(app: PyApplication) -> Set[str]: |
| 37 | + out: Set[str] = set() |
| 38 | + for mod in app.symbol_table.values(): |
| 39 | + for imp in mod.imports or []: |
| 40 | + # `from flask import Flask` puts the package in `module`, not `name`. |
| 41 | + # Prefer `module`; fall back to `name` for a bare `import flask`. |
| 42 | + spelling = (getattr(imp, "module", "") or getattr(imp, "name", "") or "") |
| 43 | + spelling = spelling.lstrip(".") |
| 44 | + if spelling: |
| 45 | + out.add(spelling.split(".", 1)[0].lower()) |
| 46 | + return out |
| 47 | + |
| 48 | + |
| 49 | +def _manifest_packages(project_dir: Path) -> Set[str]: |
| 50 | + out: Set[str] = set() |
| 51 | + pyproject = project_dir / "pyproject.toml" |
| 52 | + if pyproject.exists(): |
| 53 | + # PEP 621 `[project] dependencies = [...]` -- single- or multi-line, |
| 54 | + # possibly containing nested `[...]` extras (`celery[redis]`). |
| 55 | + span = _deps_array_span(_strip_comments(pyproject.read_text())) |
| 56 | + if span is not None: |
| 57 | + for pm in _PKG.finditer(span): |
| 58 | + out.add(pm.group(1).split("[", 1)[0].lower()) |
| 59 | + requirements = project_dir / "requirements.txt" |
| 60 | + if requirements.exists(): |
| 61 | + for line in requirements.read_text().splitlines(): |
| 62 | + m = _REQ.match(line) |
| 63 | + if m: |
| 64 | + out.add(m.group(1).split("[", 1)[0].lower()) |
| 65 | + return out |
| 66 | + |
| 67 | + |
| 68 | +def _strip_comments(text: str) -> str: |
| 69 | + """Drop everything from an unquoted ``#`` to end of line. |
| 70 | +
|
| 71 | + # ponytail: quote tracking resets each line, so a `#` inside a |
| 72 | + # triple-quoted string spanning lines could be mis-stripped. TOML |
| 73 | + # dependency arrays don't use those in practice; revisit if they do. |
| 74 | + """ |
| 75 | + out_lines = [] |
| 76 | + for line in text.splitlines(): |
| 77 | + in_str = None |
| 78 | + cut = len(line) |
| 79 | + for i, ch in enumerate(line): |
| 80 | + if in_str: |
| 81 | + if ch == in_str: |
| 82 | + in_str = None |
| 83 | + elif ch in ("'", '"'): |
| 84 | + in_str = ch |
| 85 | + elif ch == "#": |
| 86 | + cut = i |
| 87 | + break |
| 88 | + out_lines.append(line[:cut]) |
| 89 | + return "\n".join(out_lines) |
| 90 | + |
| 91 | + |
| 92 | +def _deps_array_span(text: str) -> Optional[str]: |
| 93 | + """Return the contents between the `dependencies = [` and its matching |
| 94 | + `]`, counting bracket depth so a nested `[...]` (extras, e.g. |
| 95 | + `celery[redis]`) doesn't close the span early. |
| 96 | +
|
| 97 | + Bounded by the next TOML table header (a `[` starting a line): if the |
| 98 | + array never closes before then, it's unterminated (truncated/corrupt |
| 99 | + file) and this returns None rather than harvesting quoted strings out |
| 100 | + of whatever table follows. |
| 101 | + """ |
| 102 | + m = _DEPS_START.search(text) |
| 103 | + if not m: |
| 104 | + return None |
| 105 | + boundary = _TABLE_HEADER.search(text, m.end()) |
| 106 | + limit = boundary.start() if boundary else len(text) |
| 107 | + depth = 1 |
| 108 | + in_str = None |
| 109 | + i = m.end() |
| 110 | + while i < limit and depth > 0: |
| 111 | + ch = text[i] |
| 112 | + if in_str: |
| 113 | + if ch == in_str: |
| 114 | + in_str = None |
| 115 | + elif ch in ("'", '"'): |
| 116 | + in_str = ch |
| 117 | + elif ch == "[": |
| 118 | + depth += 1 |
| 119 | + elif ch == "]": |
| 120 | + depth -= 1 |
| 121 | + i += 1 |
| 122 | + if depth != 0: |
| 123 | + return None |
| 124 | + return text[m.end() : i - 1] |
0 commit comments