|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
| 5 | +import json |
5 | 6 | import os |
| 7 | +import subprocess |
6 | 8 | import sys |
7 | 9 | from pathlib import Path |
8 | 10 |
|
9 | 11 | from loadpath.config import LoadpathConfig |
10 | 12 | from loadpath.types import Edge, EdgeType, ExtractedGraph, Node, NodeType, node_id |
11 | 13 |
|
| 14 | +BOOT_JSON_MARKER = "__LOADPATH_BOOT_JSON__" |
| 15 | + |
12 | 16 |
|
13 | 17 | def try_boot_models(repo_root: Path, config: LoadpathConfig) -> ExtractedGraph: |
| 18 | + """Boot Django in a subprocess so django.setup() is not process-global.""" |
| 19 | + if os.environ.get("LOADPATH_BOOT_INPROCESS") == "1": |
| 20 | + return _boot_inprocess(repo_root, config) |
| 21 | + return _boot_subprocess(repo_root, config) |
| 22 | + |
| 23 | + |
| 24 | +def _boot_subprocess(repo_root: Path, config: LoadpathConfig) -> ExtractedGraph: |
| 25 | + src_root = Path(__file__).resolve().parents[2] |
| 26 | + env = os.environ.copy() |
| 27 | + env["LOADPATH_BOOT_INPROCESS"] = "1" |
| 28 | + env["PYTHONPATH"] = str(src_root) + os.pathsep + env.get("PYTHONPATH", "") |
| 29 | + payload = json.dumps( |
| 30 | + { |
| 31 | + "repo_root": str(repo_root.resolve()), |
| 32 | + "django_root": config.django_root, |
| 33 | + } |
| 34 | + ) |
| 35 | + code = ( |
| 36 | + "import io,json,sys\n" |
| 37 | + "from contextlib import redirect_stdout\n" |
| 38 | + "from pathlib import Path\n" |
| 39 | + "from loadpath.config import load_config\n" |
| 40 | + "from loadpath.extractors.django_boot import _boot_inprocess\n" |
| 41 | + "meta=json.loads(sys.argv[1])\n" |
| 42 | + "root=Path(meta['repo_root'])\n" |
| 43 | + "cfg=load_config(root)\n" |
| 44 | + "cfg.django_root=meta['django_root']\n" |
| 45 | + "cfg.boot_django=True\n" |
| 46 | + "buf=io.StringIO()\n" |
| 47 | + "with redirect_stdout(buf):\n" |
| 48 | + " g=_boot_inprocess(root,cfg)\n" |
| 49 | + "print(" + repr(BOOT_JSON_MARKER) + " + json.dumps(" |
| 50 | + "{'nodes':[n.to_row() for n in g.nodes]," |
| 51 | + "'edges':[e.to_row() for e in g.edges],'residuals':g.residuals}))\n" |
| 52 | + ) |
| 53 | + try: |
| 54 | + proc = subprocess.run( |
| 55 | + [sys.executable, "-c", code, payload], |
| 56 | + capture_output=True, |
| 57 | + text=True, |
| 58 | + timeout=45, |
| 59 | + env=env, |
| 60 | + cwd=str(repo_root), |
| 61 | + ) |
| 62 | + except subprocess.TimeoutExpired: |
| 63 | + graph = ExtractedGraph() |
| 64 | + graph.residuals.append("django.setup() skipped: boot subprocess timed out") |
| 65 | + return graph |
| 66 | + if proc.returncode != 0: |
| 67 | + graph = ExtractedGraph() |
| 68 | + err = (proc.stderr or proc.stdout or "unknown error").strip().splitlines() |
| 69 | + tail = err[-1] if err else "unknown error" |
| 70 | + graph.residuals.append(f"django.setup() skipped: {tail}") |
| 71 | + return graph |
| 72 | + data = _parse_boot_payload(proc.stdout) |
| 73 | + if data is None: |
| 74 | + graph = ExtractedGraph() |
| 75 | + graph.residuals.append("django.setup() skipped: boot subprocess returned invalid JSON") |
| 76 | + return graph |
| 77 | + return _graph_from_boot_data(data) |
| 78 | + |
| 79 | + |
| 80 | +def _graph_from_boot_data(data: dict) -> ExtractedGraph: |
| 81 | + graph = ExtractedGraph() |
| 82 | + graph.residuals.extend(data.get("residuals") or []) |
| 83 | + try: |
| 84 | + for row in data.get("nodes") or []: |
| 85 | + extra = row.get("extra") or {} |
| 86 | + if isinstance(extra, str): |
| 87 | + extra = json.loads(extra) |
| 88 | + graph.nodes.append( |
| 89 | + Node( |
| 90 | + id=row["id"], |
| 91 | + type=NodeType(row["type"]), |
| 92 | + name=row["name"], |
| 93 | + qualified_name=row["qualified_name"], |
| 94 | + file_path=row.get("file_path"), |
| 95 | + start_line=row.get("start_line"), |
| 96 | + end_line=row.get("end_line"), |
| 97 | + context=row.get("context"), |
| 98 | + extra=extra if isinstance(extra, dict) else {}, |
| 99 | + ) |
| 100 | + ) |
| 101 | + for row in data.get("edges") or []: |
| 102 | + extra = row.get("extra") or {} |
| 103 | + if isinstance(extra, str): |
| 104 | + extra = json.loads(extra) |
| 105 | + graph.edges.append( |
| 106 | + Edge( |
| 107 | + src=row["src"], |
| 108 | + dst=row["dst"], |
| 109 | + type=EdgeType(row["type"]), |
| 110 | + confidence=float(row.get("confidence") or 1), |
| 111 | + extra=extra if isinstance(extra, dict) else {}, |
| 112 | + ) |
| 113 | + ) |
| 114 | + except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc: |
| 115 | + graph = ExtractedGraph() |
| 116 | + graph.residuals.append(f"django.setup() skipped: boot payload malformed ({exc})") |
| 117 | + return graph |
| 118 | + |
| 119 | + |
| 120 | +def _parse_boot_payload(stdout: str | None) -> dict | None: |
| 121 | + text = stdout or "" |
| 122 | + idx = text.rfind(BOOT_JSON_MARKER) |
| 123 | + blob = text[idx + len(BOOT_JSON_MARKER) :] if idx >= 0 else text |
| 124 | + blob = blob.strip().splitlines()[0] if blob.strip() else "" |
| 125 | + if not blob: |
| 126 | + return None |
| 127 | + try: |
| 128 | + data = json.loads(blob) |
| 129 | + except json.JSONDecodeError: |
| 130 | + return None |
| 131 | + return data if isinstance(data, dict) else None |
| 132 | + |
| 133 | + |
| 134 | +def _boot_inprocess(repo_root: Path, config: LoadpathConfig) -> ExtractedGraph: |
14 | 135 | graph = ExtractedGraph() |
15 | 136 | settings_mod = _discover_settings_module(repo_root, config.django_root) |
16 | 137 | if not settings_mod: |
|
0 commit comments