-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
79 lines (61 loc) · 2.52 KB
/
Copy pathserver.py
File metadata and controls
79 lines (61 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Serve the codebase graph as JSON to a static frontend.
Usage: python server.py <path_to_python_codebase> [--exclude DIR ...] [--port PORT]
"""
import argparse
import sys
from pathlib import Path
import uvicorn
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from walker import walk_python_files
from parser import parse_codebase
from graph import Graph, build_graph
STATIC_DIR = Path(__file__).parent / "static"
def build_codebase_graph(codebase_path: Path, exclude: set[str]) -> tuple[Graph, dict]:
root = codebase_path.resolve()
files = list(walk_python_files(root, extra_skip=exclude))
if not files:
raise SystemExit(f"no python files found under {root}")
parsed = parse_codebase(root, files)
failed = [p for p in parsed if p.parse_error]
for p in failed:
print(f"warn: {p.relpath}: {p.parse_error}", file=sys.stderr)
g = build_graph(parsed)
meta = {
"root": str(root),
"file_count": len(parsed),
"failed_count": len(failed),
"node_count": len(g.nodes),
"edge_count": len(g.edges),
}
print(f"loaded {meta['file_count']} files ({meta['failed_count']} failed), "
f"{meta['node_count']} nodes, {meta['edge_count']} edges", file=sys.stderr)
return g, meta
def create_app(codebase_path: Path, exclude: set[str]) -> FastAPI:
g, meta = build_codebase_graph(codebase_path, exclude)
payload = {**g.to_dict(), "meta": meta}
app = FastAPI(title="codemap")
@app.middleware("http")
async def no_cache(request, call_next):
response = await call_next(request)
response.headers["Cache-Control"] = "no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
return response
@app.get("/graph.json", response_class=JSONResponse)
def graph_json() -> dict:
return payload
app.mount("/", StaticFiles(directory=STATIC_DIR, html=True), name="static")
return app
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("path", help="path to a Python codebase")
ap.add_argument("--exclude", action="append", default=[],
help="directory name to skip (can be passed multiple times)")
ap.add_argument("--host", default="127.0.0.1")
ap.add_argument("--port", type=int, default=8000)
args = ap.parse_args()
app = create_app(Path(args.path), set(args.exclude))
uvicorn.run(app, host=args.host, port=args.port, log_level="warning")
if __name__ == "__main__":
main()