forked from vitali87/code-graph-rag
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathreadme_sections.py
More file actions
248 lines (200 loc) · 8.15 KB
/
Copy pathreadme_sections.py
File metadata and controls
248 lines (200 loc) · 8.15 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
from __future__ import annotations
import json
import re
import time
import tomllib
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from threading import Lock
from typing import NamedTuple
from loguru import logger
from . import cli_help as ch
from .constants import (
ENCODING_UTF8,
LANGUAGE_METADATA,
LanguageStatus,
SupportedLanguage,
)
from .language_spec import LANGUAGE_SPECS
from .tools.tool_descriptions import AGENTIC_TOOLS, MCP_TOOLS
from .types_defs import NODE_SCHEMAS, RELATIONSHIP_SCHEMAS
PYPI_CACHE_FILE = Path(__file__).parent.parent / ".pypi_cache.json"
PYPI_CACHE_TTL_SECONDS = 86400
_PYPI_CACHE_LOCK = Lock()
CHECK_MARK = "\u2713"
DASH = "-"
class MakeCommand(NamedTuple):
name: str
description: str
MAKEFILE_PATTERN = re.compile(r"^([a-zA-Z_-]+):.*?## (.+)$")
def format_markdown_table(headers: list[str], rows: list[list[str]]) -> str:
esc_headers = [str(h).replace("|", "\\|") for h in headers]
esc_rows = [[str(cell).replace("|", "\\|") for cell in row] for row in rows]
separator = "|".join("-" * max(len(h), 3) for h in esc_headers)
lines = [
"| " + " | ".join(esc_headers) + " |",
"|" + separator + "|",
]
for row in esc_rows:
lines.append("| " + " | ".join(row) + " |")
return "\n".join(lines)
def extract_makefile_commands(makefile_path: Path) -> list[MakeCommand]:
commands: list[MakeCommand] = []
content = makefile_path.read_text(encoding="utf-8")
for line in content.splitlines():
if match := MAKEFILE_PATTERN.match(line):
commands.append(
MakeCommand(name=match.group(1), description=match.group(2))
)
return commands
def format_makefile_table(commands: list[MakeCommand]) -> str:
rows = [[f"`make {cmd.name}`", cmd.description] for cmd in commands]
return format_markdown_table(["Command", "Description"], rows)
def format_full_languages_table() -> str:
headers = [
"Language",
"Status",
"Extensions",
"Functions",
"Classes/Structs",
"Modules",
"Package Detection",
"Additional Features",
]
sorted_langs = sorted(
SupportedLanguage,
key=lambda lang: (
LANGUAGE_METADATA[lang].status != LanguageStatus.FULL,
lang.value,
),
)
rows: list[list[str]] = []
for lang in sorted_langs:
spec = LANGUAGE_SPECS[lang]
meta = LANGUAGE_METADATA[lang]
rows.append(
[
meta.display_name,
meta.status.value,
", ".join(spec.file_extensions),
CHECK_MARK if spec.function_node_types else DASH,
CHECK_MARK if spec.class_node_types else DASH,
CHECK_MARK if spec.module_node_types else DASH,
CHECK_MARK if spec.package_indicators else DASH,
meta.additional_features,
]
)
return format_markdown_table(headers, rows)
def extract_node_schemas() -> list[tuple[str, str]]:
return [(schema.label.value, schema.properties) for schema in NODE_SCHEMAS]
def format_node_schemas_table(schemas: list[tuple[str, str]]) -> str:
rows = [[label, f"`{props}`"] for label, props in schemas]
return format_markdown_table(["Label", "Properties"], rows)
def extract_relationship_schemas() -> list[tuple[str, str, str]]:
result: list[tuple[str, str, str]] = []
for schema in RELATIONSHIP_SCHEMAS:
sources = ", ".join(s.value for s in schema.sources)
targets = ", ".join(t.value for t in schema.targets)
result.append((sources, schema.rel_type.value, targets))
return result
def format_relationship_schemas_table(schemas: list[tuple[str, str, str]]) -> str:
rows = [[source, rel, target] for source, rel, target in schemas]
return format_markdown_table(["Source", "Relationship", "Target"], rows)
def format_cli_commands_table() -> str:
rows = [
[f"`codebase-rag {cmd.value}`", desc] for cmd, desc in ch.CLI_COMMANDS.items()
]
return format_markdown_table(["Command", "Description"], rows)
def format_language_mappings() -> str:
sorted_langs = sorted(
SupportedLanguage,
key=lambda lang: (
LANGUAGE_METADATA[lang].status != LanguageStatus.FULL,
lang.value,
),
)
lines: list[str] = []
for lang in sorted_langs:
spec = LANGUAGE_SPECS[lang]
meta = LANGUAGE_METADATA[lang]
node_types = list(spec.function_node_types) + list(spec.class_node_types)
if not node_types:
continue
formatted_types = ", ".join(f"`{t}`" for t in sorted(node_types))
lines.append(f"- **{meta.display_name}**: {formatted_types}")
return "\n".join(lines)
def format_mcp_tools_table() -> str:
rows = [[f"`{name.value}`", desc] for name, desc in MCP_TOOLS.items()]
return format_markdown_table(["Tool", "Description"], rows)
def format_agentic_tools_table() -> str:
rows = [[f"`{name.value}`", desc] for name, desc in AGENTIC_TOOLS.items()]
return format_markdown_table(["Tool", "Description"], rows)
def extract_dependencies(pyproject_path: Path) -> list[str]:
content = pyproject_path.read_bytes()
data = tomllib.loads(content.decode(ENCODING_UTF8))
deps = data.get("project", {}).get("dependencies", [])
return [re.split(r"[<>=!~\[]", dep)[0].strip() for dep in deps]
def _load_pypi_cache() -> dict[str, tuple[str, float]]:
if not PYPI_CACHE_FILE.exists():
return {}
try:
data = json.loads(PYPI_CACHE_FILE.read_text(encoding="utf-8"))
return {k: (v[0], v[1]) for k, v in data.items()}
except (json.JSONDecodeError, KeyError, IndexError):
return {}
def _save_pypi_cache(cache: dict[str, tuple[str, float]]) -> None:
PYPI_CACHE_FILE.write_text(
json.dumps({k: list(v) for k, v in cache.items()}), encoding="utf-8"
)
def fetch_pypi_summary(package_name: str, cache: dict[str, tuple[str, float]]) -> str:
now = time.time()
with _PYPI_CACHE_LOCK:
cached = cache.get(package_name)
if cached and now - cached[1] < PYPI_CACHE_TTL_SECONDS:
return cached[0]
url = f"https://pypi.org/pypi/{package_name}/json"
try:
with urllib.request.urlopen(url, timeout=5) as response:
charset = response.headers.get_content_charset() or ENCODING_UTF8
data = json.loads(response.read().decode(charset))
summary = data.get("info", {}).get("summary", "") or ""
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as e:
logger.warning(f"Could not fetch PyPI summary for {package_name}: {e}")
return ""
with _PYPI_CACHE_LOCK:
cache[package_name] = (summary, now)
return summary
def format_dependencies(deps: list[str]) -> str:
cache = _load_pypi_cache()
try:
with ThreadPoolExecutor() as executor:
summaries = list(
executor.map(lambda dep: fetch_pypi_summary(dep, cache), deps)
)
lines: list[str] = []
for name, summary in zip(deps, summaries):
if summary:
lines.append(f"- **{name}**: {summary}")
else:
lines.append(f"- **{name}**")
return "\n".join(lines)
finally:
_save_pypi_cache(cache)
def generate_all_sections(project_root: Path) -> dict[str, str]:
makefile_commands = extract_makefile_commands(project_root / "Makefile")
node_schemas = extract_node_schemas()
rel_schemas = extract_relationship_schemas()
deps = extract_dependencies(project_root / "pyproject.toml")
return {
"makefile_commands": format_makefile_table(makefile_commands),
"supported_languages": format_full_languages_table(),
"language_mappings": format_language_mappings(),
"node_schemas": format_node_schemas_table(node_schemas),
"relationship_schemas": format_relationship_schemas_table(rel_schemas),
"cli_commands": format_cli_commands_table(),
"mcp_tools": format_mcp_tools_table(),
"agentic_tools": format_agentic_tools_table(),
"dependencies": format_dependencies(deps),
}