codiff 0.1.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.
- codiff/__init__.py +1 -0
- codiff/__main__.py +5 -0
- codiff/cli.py +247 -0
- codiff/db/__init__.py +16 -0
- codiff/db/engine.py +31 -0
- codiff/db/models.py +119 -0
- codiff/db/operations.py +238 -0
- codiff/diff/__init__.py +1 -0
- codiff/diff/analysis.py +145 -0
- codiff/diff/differ.py +45 -0
- codiff/diff/engine.py +80 -0
- codiff/diff/indexer.py +134 -0
- codiff/diff/snapshot.py +325 -0
- codiff/export/__init__.py +5 -0
- codiff/export/json.py +43 -0
- codiff/export/mermaid.py +475 -0
- codiff/export/terminal.py +866 -0
- codiff/languages/__init__.py +29 -0
- codiff/languages/parser.py +214 -0
- codiff/languages/python/__init__.py +0 -0
- codiff/languages/python/parser.py +927 -0
- codiff/languages/python/resolver.py +178 -0
- codiff/languages/repository.py +245 -0
- codiff/languages/resolver.py +582 -0
- codiff/languages/typescript/__init__.py +0 -0
- codiff/languages/typescript/parser.py +612 -0
- codiff/languages/typescript/resolver.py +95 -0
- codiff/mcp_server.py +83 -0
- codiff/schema/__init__.py +25 -0
- codiff/schema/diff.py +110 -0
- codiff/schema/parsing.py +76 -0
- codiff/setup.py +103 -0
- codiff/utils/__init__.py +0 -0
- codiff/utils/args.py +114 -0
- codiff/utils/files.py +62 -0
- codiff/utils/git.py +101 -0
- codiff/utils/instructions.py +14 -0
- codiff/utils/instructions.yaml +50 -0
- codiff/utils/terminal.py +10 -0
- codiff-0.1.0.dist-info/METADATA +487 -0
- codiff-0.1.0.dist-info/RECORD +45 -0
- codiff-0.1.0.dist-info/WHEEL +5 -0
- codiff-0.1.0.dist-info/entry_points.txt +3 -0
- codiff-0.1.0.dist-info/licenses/LICENSE +201 -0
- codiff-0.1.0.dist-info/top_level.txt +1 -0
codiff/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""codiff — structural call-graph diff for multi-language codebases."""
|
codiff/__main__.py
ADDED
codiff/cli.py
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""CLI entry point for codiff."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from codiff.utils.args import DEFAULT_WORKERS as _DEFAULT_WORKERS
|
|
10
|
+
from codiff.utils.args import build_parser
|
|
11
|
+
from codiff.utils.instructions import load as _load_instructions
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main():
|
|
15
|
+
args = build_parser().parse_args()
|
|
16
|
+
|
|
17
|
+
level = logging.DEBUG if (args.verbose >= 2 or getattr(args, "debug", False)) else logging.INFO
|
|
18
|
+
logging.basicConfig(
|
|
19
|
+
level=level,
|
|
20
|
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
|
21
|
+
stream=sys.stderr,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
if args.command == "index":
|
|
25
|
+
from codiff.setup import setup_repository
|
|
26
|
+
|
|
27
|
+
setup_repository(args.repo_path)
|
|
28
|
+
|
|
29
|
+
elif args.command == "diff":
|
|
30
|
+
_run_diff(
|
|
31
|
+
repo_path=args.repo,
|
|
32
|
+
base_ref=args.base,
|
|
33
|
+
head_ref=args.head,
|
|
34
|
+
include_tests=args.include_tests,
|
|
35
|
+
include_deleted=args.include_deleted,
|
|
36
|
+
fmt=args.format,
|
|
37
|
+
max_workers=args.workers,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
elif args.command == "init":
|
|
41
|
+
_run_init(repo_path=args.repo, agent=args.agent)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# ---------------------------------------------------------------------------
|
|
45
|
+
# Init helpers — instructions loaded from utils/instructions.yaml
|
|
46
|
+
# ---------------------------------------------------------------------------
|
|
47
|
+
|
|
48
|
+
_instr = _load_instructions()
|
|
49
|
+
_INSTRUCTIONS_MARKER: str = _instr["marker"]
|
|
50
|
+
_INSTRUCTIONS_BODY: str = _instr["body"].rstrip("\n")
|
|
51
|
+
_INSTRUCTIONS_BLOCK: str = f"{_INSTRUCTIONS_MARKER}\n{_INSTRUCTIONS_BODY}\n<!-- /codiff -->"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _write_mcp_config(
|
|
55
|
+
path: Path,
|
|
56
|
+
label: str,
|
|
57
|
+
top_key: str,
|
|
58
|
+
server_name: str,
|
|
59
|
+
server_cfg: dict,
|
|
60
|
+
) -> None:
|
|
61
|
+
"""Write or merge an MCP server entry into a JSON config file."""
|
|
62
|
+
config: dict = {}
|
|
63
|
+
if path.exists():
|
|
64
|
+
try:
|
|
65
|
+
config = json.loads(path.read_text())
|
|
66
|
+
except json.JSONDecodeError:
|
|
67
|
+
config = {}
|
|
68
|
+
servers: dict = config.setdefault(top_key, {})
|
|
69
|
+
if server_name in servers:
|
|
70
|
+
print(f" ~ {label:<30} codiff MCP already registered, skipped")
|
|
71
|
+
else:
|
|
72
|
+
servers[server_name] = server_cfg
|
|
73
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
74
|
+
path.write_text(json.dumps(config, indent=2) + "\n")
|
|
75
|
+
print(f" + {label:<30} registered codiff-mcp server")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _write_instructions(path: Path, label: str, block: str) -> None:
|
|
79
|
+
"""Create or append a codiff instructions block to a markdown file."""
|
|
80
|
+
if path.exists():
|
|
81
|
+
existing = path.read_text()
|
|
82
|
+
if _INSTRUCTIONS_MARKER in existing:
|
|
83
|
+
print(f" ~ {label:<30} codiff instructions already present, skipped")
|
|
84
|
+
else:
|
|
85
|
+
path.write_text(existing.rstrip("\n") + "\n\n" + block + "\n")
|
|
86
|
+
print(f" + {label:<30} appended codiff instructions")
|
|
87
|
+
else:
|
|
88
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
89
|
+
path.write_text(block + "\n")
|
|
90
|
+
print(f" + {label:<30} created with codiff instructions")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# ---------------------------------------------------------------------------
|
|
94
|
+
# Per-agent init functions
|
|
95
|
+
# ---------------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _init_claude(repo_path: str) -> None:
|
|
99
|
+
"""Claude Code: .mcp.json + CLAUDE.md"""
|
|
100
|
+
repo = Path(repo_path)
|
|
101
|
+
_write_mcp_config(
|
|
102
|
+
repo / ".mcp.json", ".mcp.json", "mcpServers", "codiff", {"command": "codiff-mcp"}
|
|
103
|
+
)
|
|
104
|
+
_write_instructions(repo / "CLAUDE.md", "CLAUDE.md", _INSTRUCTIONS_BLOCK)
|
|
105
|
+
print("\n Restart Claude Code to load the new MCP server.\n")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
_CODEX_TOML_ENTRY = '[mcp_servers.codiff]\ncommand = "codiff-mcp"\n'
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _init_codex(repo_path: str) -> None:
|
|
112
|
+
"""OpenAI Codex CLI: .codex/config.toml + AGENTS.md"""
|
|
113
|
+
import tomllib
|
|
114
|
+
|
|
115
|
+
repo = Path(repo_path)
|
|
116
|
+
config_path = repo / ".codex" / "config.toml"
|
|
117
|
+
label = ".codex/config.toml"
|
|
118
|
+
|
|
119
|
+
if config_path.exists():
|
|
120
|
+
try:
|
|
121
|
+
with open(config_path, "rb") as f:
|
|
122
|
+
cfg = tomllib.load(f)
|
|
123
|
+
if "codiff" in cfg.get("mcp_servers", {}):
|
|
124
|
+
print(f" ~ {label:<30} codiff MCP already registered, skipped")
|
|
125
|
+
else:
|
|
126
|
+
config_path.write_text(
|
|
127
|
+
config_path.read_text().rstrip("\n") + "\n\n" + _CODEX_TOML_ENTRY
|
|
128
|
+
)
|
|
129
|
+
print(f" + {label:<30} registered codiff-mcp server")
|
|
130
|
+
except Exception:
|
|
131
|
+
config_path.write_text(
|
|
132
|
+
config_path.read_text().rstrip("\n") + "\n\n" + _CODEX_TOML_ENTRY
|
|
133
|
+
)
|
|
134
|
+
print(f" + {label:<30} registered codiff-mcp server")
|
|
135
|
+
else:
|
|
136
|
+
config_path.parent.mkdir(parents=True, exist_ok=True)
|
|
137
|
+
config_path.write_text(_CODEX_TOML_ENTRY)
|
|
138
|
+
print(f" + {label:<30} registered codiff-mcp server")
|
|
139
|
+
|
|
140
|
+
_write_instructions(repo / "AGENTS.md", "AGENTS.md", _INSTRUCTIONS_BLOCK)
|
|
141
|
+
print()
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _init_gemini(repo_path: str) -> None:
|
|
145
|
+
"""Gemini CLI: global ~/.gemini/settings.json + GEMINI.md"""
|
|
146
|
+
repo = Path(repo_path)
|
|
147
|
+
_write_mcp_config(
|
|
148
|
+
Path.home() / ".gemini" / "settings.json",
|
|
149
|
+
"~/.gemini/settings.json",
|
|
150
|
+
"mcpServers",
|
|
151
|
+
"codiff",
|
|
152
|
+
{"command": "codiff-mcp"},
|
|
153
|
+
)
|
|
154
|
+
_write_instructions(repo / "GEMINI.md", "GEMINI.md", _INSTRUCTIONS_BLOCK)
|
|
155
|
+
print("\n Restart Gemini CLI to load the new MCP server.\n")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
_VIBE_SERVER_ENTRY: dict = {"name": "codiff", "transport": "stdio", "command": "codiff-mcp"}
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _init_vibe(repo_path: str) -> None:
|
|
162
|
+
"""Mistral Vibe: global ~/.vibe/config.toml with [[mcp_servers]] array entry.
|
|
163
|
+
|
|
164
|
+
Vibe has no separate instructions file — MCP registration is sufficient.
|
|
165
|
+
Project-level .vibe/config.toml exists but requires explicit directory trust;
|
|
166
|
+
the global file is used by default and works without any extra setup.
|
|
167
|
+
|
|
168
|
+
Vibe writes its config via tomli_w.dump() (the whole dict), so we must
|
|
169
|
+
round-trip the same way — reading with tomllib and writing with tomli_w —
|
|
170
|
+
to avoid TOML "cannot mutate immutable namespace" conflicts when the existing
|
|
171
|
+
file uses inline-array syntax for mcp_servers.
|
|
172
|
+
"""
|
|
173
|
+
import tomllib
|
|
174
|
+
|
|
175
|
+
import tomli_w
|
|
176
|
+
|
|
177
|
+
config_path = Path.home() / ".vibe" / "config.toml"
|
|
178
|
+
label = "~/.vibe/config.toml"
|
|
179
|
+
|
|
180
|
+
cfg: dict = {}
|
|
181
|
+
if config_path.exists():
|
|
182
|
+
try:
|
|
183
|
+
with open(config_path, "rb") as f:
|
|
184
|
+
cfg = tomllib.load(f)
|
|
185
|
+
except Exception:
|
|
186
|
+
cfg = {}
|
|
187
|
+
|
|
188
|
+
servers: list = cfg.get("mcp_servers", []) if isinstance(cfg.get("mcp_servers"), list) else []
|
|
189
|
+
if any(isinstance(s, dict) and s.get("name") == "codiff" for s in servers):
|
|
190
|
+
print(f" ~ {label:<30} codiff MCP already registered, skipped")
|
|
191
|
+
print()
|
|
192
|
+
return
|
|
193
|
+
|
|
194
|
+
cfg["mcp_servers"] = servers + [_VIBE_SERVER_ENTRY]
|
|
195
|
+
config_path.parent.mkdir(parents=True, exist_ok=True)
|
|
196
|
+
with open(config_path, "wb") as f:
|
|
197
|
+
tomli_w.dump(cfg, f)
|
|
198
|
+
print(f" + {label:<30} registered codiff-mcp server")
|
|
199
|
+
|
|
200
|
+
print("\n Restart Vibe to load the new MCP server.\n")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
_INIT_AGENTS = {
|
|
204
|
+
"claude": _init_claude,
|
|
205
|
+
"codex": _init_codex,
|
|
206
|
+
"gemini": _init_gemini,
|
|
207
|
+
"vibe": _init_vibe,
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _run_init(repo_path: str, agent: str) -> None:
|
|
212
|
+
repo_path = os.path.abspath(repo_path)
|
|
213
|
+
print(f"\nConfiguring codiff for {agent} in {repo_path}\n")
|
|
214
|
+
_INIT_AGENTS[agent](repo_path)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _run_diff(
|
|
218
|
+
repo_path: str,
|
|
219
|
+
base_ref: str,
|
|
220
|
+
head_ref: str | None = None,
|
|
221
|
+
include_tests: bool = False,
|
|
222
|
+
include_deleted: bool = False,
|
|
223
|
+
fmt: str = "terminal",
|
|
224
|
+
max_workers: int = _DEFAULT_WORKERS,
|
|
225
|
+
) -> None:
|
|
226
|
+
from codiff.diff.engine import compute_diff
|
|
227
|
+
from codiff.export import render_json, render_mermaid, render_terminal
|
|
228
|
+
|
|
229
|
+
result = compute_diff(
|
|
230
|
+
repo_path,
|
|
231
|
+
base_ref=base_ref,
|
|
232
|
+
head_ref=head_ref,
|
|
233
|
+
include_tests=include_tests,
|
|
234
|
+
include_deleted=include_deleted,
|
|
235
|
+
max_workers=max_workers,
|
|
236
|
+
)
|
|
237
|
+
head_label = head_ref or "working tree"
|
|
238
|
+
if fmt == "json":
|
|
239
|
+
print(render_json(result, base_ref=base_ref, head_ref=head_label))
|
|
240
|
+
elif fmt == "mermaid":
|
|
241
|
+
print(render_mermaid(result))
|
|
242
|
+
else:
|
|
243
|
+
render_terminal(result, base_ref=base_ref, head_ref=head_label, include_tests=include_tests)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
if __name__ == "__main__":
|
|
247
|
+
main()
|
codiff/db/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from codiff.db.engine import get_db_path, make_sync_engine, make_sync_session
|
|
2
|
+
from codiff.db.models import Base, CallEdge, Class, CommitMeta, Function, Repository
|
|
3
|
+
|
|
4
|
+
__all__ = [
|
|
5
|
+
# models
|
|
6
|
+
"Base",
|
|
7
|
+
"Repository",
|
|
8
|
+
"Function",
|
|
9
|
+
"Class",
|
|
10
|
+
"CallEdge",
|
|
11
|
+
"CommitMeta",
|
|
12
|
+
# engine helpers
|
|
13
|
+
"get_db_path",
|
|
14
|
+
"make_sync_engine",
|
|
15
|
+
"make_sync_session",
|
|
16
|
+
]
|
codiff/db/engine.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from sqlalchemy import create_engine, event
|
|
4
|
+
from sqlalchemy.orm import sessionmaker
|
|
5
|
+
|
|
6
|
+
from codiff.db.models import Base
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_db_path(repo_path: str) -> str:
|
|
10
|
+
return os.path.join(os.path.abspath(repo_path), ".codiff.db")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def make_sync_engine(db_path: str):
|
|
14
|
+
"""Create a sync SQLAlchemy engine with WAL mode enabled."""
|
|
15
|
+
engine = create_engine(f"sqlite:///{db_path}", echo=False)
|
|
16
|
+
|
|
17
|
+
@event.listens_for(engine, "connect")
|
|
18
|
+
def _set_wal(dbapi_conn, _):
|
|
19
|
+
cur = dbapi_conn.cursor()
|
|
20
|
+
cur.execute("PRAGMA journal_mode=WAL")
|
|
21
|
+
cur.execute("PRAGMA synchronous=NORMAL")
|
|
22
|
+
cur.close()
|
|
23
|
+
|
|
24
|
+
return engine
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def make_sync_session(db_path: str):
|
|
28
|
+
"""Create a sync engine + session, ensure tables exist, return (engine, Session)."""
|
|
29
|
+
engine = make_sync_engine(db_path)
|
|
30
|
+
Base.metadata.create_all(engine)
|
|
31
|
+
return engine, sessionmaker(bind=engine)
|
codiff/db/models.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import uuid
|
|
2
|
+
from datetime import UTC, datetime
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import JSON, DateTime, ForeignKey, Index, Integer, String, Text
|
|
6
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Base(DeclarativeBase):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _new_uuid() -> str:
|
|
14
|
+
return str(uuid.uuid4())
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Repository(Base):
|
|
18
|
+
__tablename__ = "repositories"
|
|
19
|
+
|
|
20
|
+
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_new_uuid)
|
|
21
|
+
name: Mapped[str] = mapped_column(String(255), nullable=False)
|
|
22
|
+
url: Mapped[str] = mapped_column(String(512), nullable=False, default="")
|
|
23
|
+
is_parsed: Mapped[bool] = mapped_column(default=False)
|
|
24
|
+
total_functions: Mapped[int] = mapped_column(Integer, default=0)
|
|
25
|
+
total_classes: Mapped[int] = mapped_column(Integer, default=0)
|
|
26
|
+
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(UTC))
|
|
27
|
+
|
|
28
|
+
functions: Mapped[list["Function"]] = relationship(
|
|
29
|
+
"Function",
|
|
30
|
+
back_populates="repository",
|
|
31
|
+
cascade="all, delete-orphan",
|
|
32
|
+
)
|
|
33
|
+
classes: Mapped[list["Class"]] = relationship(
|
|
34
|
+
"Class",
|
|
35
|
+
back_populates="repository",
|
|
36
|
+
cascade="all, delete-orphan",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Function(Base):
|
|
41
|
+
__tablename__ = "functions"
|
|
42
|
+
|
|
43
|
+
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_new_uuid)
|
|
44
|
+
repository_id: Mapped[str] = mapped_column(
|
|
45
|
+
String(36), ForeignKey("repositories.id"), nullable=False
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
function_id: Mapped[str] = mapped_column(String(512), nullable=False, index=True)
|
|
49
|
+
name: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
|
50
|
+
file_path: Mapped[str] = mapped_column(String(512), nullable=False)
|
|
51
|
+
class_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True, index=True)
|
|
52
|
+
nested: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
|
|
53
|
+
|
|
54
|
+
code: Mapped[str] = mapped_column(Text, nullable=False)
|
|
55
|
+
docstring: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
|
56
|
+
module_docstring: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
|
57
|
+
class_docstring: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
|
58
|
+
|
|
59
|
+
start_line: Mapped[int] = mapped_column(Integer, nullable=False)
|
|
60
|
+
end_line: Mapped[int] = mapped_column(Integer, nullable=False)
|
|
61
|
+
|
|
62
|
+
parameters: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
|
63
|
+
decorators: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
|
64
|
+
return_type: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
|
65
|
+
calls: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
|
66
|
+
|
|
67
|
+
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(UTC))
|
|
68
|
+
|
|
69
|
+
repository: Mapped["Repository"] = relationship("Repository", back_populates="functions")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Class(Base):
|
|
73
|
+
__tablename__ = "classes"
|
|
74
|
+
|
|
75
|
+
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_new_uuid)
|
|
76
|
+
repository_id: Mapped[str] = mapped_column(
|
|
77
|
+
String(36), ForeignKey("repositories.id"), nullable=False
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
class_id: Mapped[str] = mapped_column(String(512), nullable=False, index=True)
|
|
81
|
+
name: Mapped[str] = mapped_column(String(255), nullable=False, index=True)
|
|
82
|
+
file_path: Mapped[str] = mapped_column(String(512), nullable=False)
|
|
83
|
+
|
|
84
|
+
code: Mapped[str] = mapped_column(Text, nullable=False)
|
|
85
|
+
docstring: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
|
86
|
+
|
|
87
|
+
start_line: Mapped[int] = mapped_column(Integer, nullable=False)
|
|
88
|
+
end_line: Mapped[int] = mapped_column(Integer, nullable=False)
|
|
89
|
+
|
|
90
|
+
decorators: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
|
91
|
+
superclasses: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
|
|
92
|
+
|
|
93
|
+
created_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(UTC))
|
|
94
|
+
|
|
95
|
+
repository: Mapped["Repository"] = relationship("Repository", back_populates="classes")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class CallEdge(Base):
|
|
99
|
+
"""Resolved call edges — one row per (caller, callee) function ID pair.
|
|
100
|
+
|
|
101
|
+
Populated during indexing so the DB is queryable as a call graph without
|
|
102
|
+
loading the full snapshot into memory.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
__tablename__ = "call_edges"
|
|
106
|
+
__table_args__ = (Index("ix_call_edges_callee_id", "callee_id"),)
|
|
107
|
+
|
|
108
|
+
caller_id: Mapped[str] = mapped_column(String(512), nullable=False, primary_key=True)
|
|
109
|
+
callee_id: Mapped[str] = mapped_column(String(512), nullable=False, primary_key=True)
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class CommitMeta(Base):
|
|
113
|
+
"""Records which git commit SHA the database was last indexed from."""
|
|
114
|
+
|
|
115
|
+
__tablename__ = "commit_meta"
|
|
116
|
+
|
|
117
|
+
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_new_uuid)
|
|
118
|
+
commit_sha: Mapped[str] = mapped_column(String(40), nullable=False)
|
|
119
|
+
indexed_at: Mapped[datetime] = mapped_column(DateTime, default=lambda: datetime.now(UTC))
|
codiff/db/operations.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""All database read/write operations for codiff.
|
|
2
|
+
|
|
3
|
+
Every function that touches SQLite lives here. Callers (indexer, snapshot)
|
|
4
|
+
only deal with domain types (ParsedRepository, GraphSnapshot) — they never
|
|
5
|
+
open sessions or reference ORM models directly.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import uuid
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from typing import TYPE_CHECKING, Generator
|
|
14
|
+
|
|
15
|
+
from sqlalchemy import text
|
|
16
|
+
from sqlalchemy.orm import Session, load_only, sessionmaker
|
|
17
|
+
|
|
18
|
+
from codiff.db.engine import make_sync_engine
|
|
19
|
+
from codiff.db.models import Base, CallEdge, Class, CommitMeta, Function, Repository
|
|
20
|
+
from codiff.schema.diff import GraphSnapshot, NodeInfo
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from codiff.languages.repository import ParsedRepository
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
# ---------------------------------------------------------------------------
|
|
27
|
+
# Session helper
|
|
28
|
+
# ---------------------------------------------------------------------------
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@contextmanager
|
|
32
|
+
def _session(db_path: str, create_tables: bool = False) -> Generator[Session, None, None]:
|
|
33
|
+
"""Open a session; commit on clean exit, rollback on error."""
|
|
34
|
+
engine = make_sync_engine(db_path)
|
|
35
|
+
if create_tables:
|
|
36
|
+
Base.metadata.create_all(engine)
|
|
37
|
+
db: Session = sessionmaker(bind=engine)()
|
|
38
|
+
try:
|
|
39
|
+
yield db
|
|
40
|
+
db.commit()
|
|
41
|
+
except Exception:
|
|
42
|
+
db.rollback()
|
|
43
|
+
raise
|
|
44
|
+
finally:
|
|
45
|
+
db.close()
|
|
46
|
+
engine.dispose()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
# Read operations
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def get_indexed_sha(db_path: str) -> str | None:
|
|
55
|
+
"""Return the commit SHA stored in commit_meta, or None if DB is empty/missing."""
|
|
56
|
+
if not os.path.exists(db_path):
|
|
57
|
+
return None
|
|
58
|
+
try:
|
|
59
|
+
with _session(db_path, create_tables=True) as db:
|
|
60
|
+
meta = db.query(CommitMeta).order_by(CommitMeta.indexed_at.desc()).first()
|
|
61
|
+
return meta.commit_sha if meta else None
|
|
62
|
+
except Exception:
|
|
63
|
+
return None
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def load_snapshot(db_path: str) -> GraphSnapshot:
|
|
67
|
+
"""Load the indexed snapshot from the SQLite database, including resolved edges."""
|
|
68
|
+
snapshot = GraphSnapshot()
|
|
69
|
+
with _session(db_path) as db:
|
|
70
|
+
for func in (
|
|
71
|
+
db.query(Function)
|
|
72
|
+
.options(
|
|
73
|
+
load_only(
|
|
74
|
+
Function.function_id,
|
|
75
|
+
Function.name,
|
|
76
|
+
Function.file_path,
|
|
77
|
+
Function.class_name,
|
|
78
|
+
Function.code,
|
|
79
|
+
Function.parameters,
|
|
80
|
+
Function.return_type,
|
|
81
|
+
Function.calls,
|
|
82
|
+
)
|
|
83
|
+
)
|
|
84
|
+
.all()
|
|
85
|
+
):
|
|
86
|
+
snapshot.nodes[func.function_id] = NodeInfo(
|
|
87
|
+
function_id=func.function_id,
|
|
88
|
+
name=func.name,
|
|
89
|
+
file_path=func.file_path,
|
|
90
|
+
class_name=func.class_name,
|
|
91
|
+
parameters=list(func.parameters or []), # type: ignore[arg-type]
|
|
92
|
+
return_type=func.return_type,
|
|
93
|
+
calls=func.calls or [],
|
|
94
|
+
code=func.code or "",
|
|
95
|
+
)
|
|
96
|
+
for cls in db.query(Class).options(load_only(Class.class_id, Class.superclasses)).all():
|
|
97
|
+
if cls.superclasses:
|
|
98
|
+
snapshot.class_parents[cls.class_id] = list(cls.superclasses)
|
|
99
|
+
|
|
100
|
+
all_ids = set(snapshot.nodes)
|
|
101
|
+
for node in snapshot.nodes.values():
|
|
102
|
+
for callee_id in node.calls:
|
|
103
|
+
if callee_id in all_ids:
|
|
104
|
+
snapshot.edges.add((node.function_id, callee_id))
|
|
105
|
+
|
|
106
|
+
return snapshot
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
# Write operations
|
|
111
|
+
# ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def write_full_snapshot(db_path: str, parsed: ParsedRepository, sha: str) -> None:
|
|
115
|
+
"""Wipe the DB and write *parsed* as the canonical snapshot at *sha*."""
|
|
116
|
+
with _session(db_path, create_tables=True) as db:
|
|
117
|
+
db.query(CallEdge).delete()
|
|
118
|
+
db.query(Function).delete()
|
|
119
|
+
db.query(Class).delete()
|
|
120
|
+
db.query(CommitMeta).delete()
|
|
121
|
+
db.query(Repository).delete()
|
|
122
|
+
db.flush()
|
|
123
|
+
|
|
124
|
+
repo_id = str(uuid.uuid4())
|
|
125
|
+
repo = Repository(id=repo_id, name="base", url="", is_parsed=False)
|
|
126
|
+
db.add(repo)
|
|
127
|
+
|
|
128
|
+
_insert_functions(db, repo_id, parsed)
|
|
129
|
+
_insert_classes(db, repo_id, parsed)
|
|
130
|
+
db.flush()
|
|
131
|
+
_insert_call_edges(db, parsed.functions)
|
|
132
|
+
|
|
133
|
+
repo.total_functions = len(parsed.functions)
|
|
134
|
+
repo.total_classes = len(parsed.classes)
|
|
135
|
+
repo.is_parsed = True
|
|
136
|
+
db.add(CommitMeta(commit_sha=sha))
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def write_incremental(
|
|
140
|
+
db_path: str,
|
|
141
|
+
fresh: ParsedRepository,
|
|
142
|
+
files_to_update: set[str],
|
|
143
|
+
old_func_ids: set[str],
|
|
144
|
+
sha: str,
|
|
145
|
+
) -> None:
|
|
146
|
+
"""Replace rows for *files_to_update* with *fresh*, then update the SHA."""
|
|
147
|
+
with _session(db_path) as db:
|
|
148
|
+
if old_func_ids:
|
|
149
|
+
db.query(CallEdge).filter(CallEdge.caller_id.in_(old_func_ids)).delete(
|
|
150
|
+
synchronize_session=False
|
|
151
|
+
)
|
|
152
|
+
db.query(Function).filter(Function.file_path.in_(files_to_update)).delete(
|
|
153
|
+
synchronize_session=False
|
|
154
|
+
)
|
|
155
|
+
db.query(Class).filter(Class.file_path.in_(files_to_update)).delete(
|
|
156
|
+
synchronize_session=False
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
repo = db.query(Repository).first()
|
|
160
|
+
assert repo is not None, "no repository row — DB may be corrupt"
|
|
161
|
+
|
|
162
|
+
_insert_functions(db, repo.id, fresh)
|
|
163
|
+
_insert_classes(db, repo.id, fresh)
|
|
164
|
+
db.flush()
|
|
165
|
+
_insert_call_edges(db, fresh.functions)
|
|
166
|
+
|
|
167
|
+
db.query(CommitMeta).delete()
|
|
168
|
+
db.add(CommitMeta(commit_sha=sha))
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def update_sha(db_path: str, sha: str) -> None:
|
|
172
|
+
"""Update the stored commit SHA without touching any other data."""
|
|
173
|
+
with _session(db_path) as db:
|
|
174
|
+
db.query(CommitMeta).delete()
|
|
175
|
+
db.add(CommitMeta(commit_sha=sha))
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
# ---------------------------------------------------------------------------
|
|
179
|
+
# Private insertion helpers
|
|
180
|
+
# ---------------------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _insert_functions(db: Session, repo_id: str, parsed: ParsedRepository) -> None:
|
|
184
|
+
for fn in parsed.functions:
|
|
185
|
+
mod_doc = parsed.module_docstrings.get(fn.file_path)
|
|
186
|
+
cls_doc = parsed.class_docstrings.get(fn.class_name) if fn.class_name else None
|
|
187
|
+
db.add(
|
|
188
|
+
Function(
|
|
189
|
+
repository_id=repo_id,
|
|
190
|
+
function_id=fn.id,
|
|
191
|
+
name=fn.name,
|
|
192
|
+
file_path=fn.file_path,
|
|
193
|
+
class_name=fn.class_name,
|
|
194
|
+
nested=fn.nested,
|
|
195
|
+
code=fn.code,
|
|
196
|
+
docstring=fn.docstring,
|
|
197
|
+
module_docstring=mod_doc,
|
|
198
|
+
class_docstring=cls_doc,
|
|
199
|
+
start_line=fn.start_line,
|
|
200
|
+
end_line=fn.end_line,
|
|
201
|
+
parameters=[p.to_dict() for p in fn.parameters] if fn.parameters else None,
|
|
202
|
+
decorators=fn.decorators,
|
|
203
|
+
return_type=fn.return_type,
|
|
204
|
+
calls=fn.calls,
|
|
205
|
+
)
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _insert_classes(db: Session, repo_id: str, parsed: ParsedRepository) -> None:
|
|
210
|
+
for cls in parsed.classes:
|
|
211
|
+
db.add(
|
|
212
|
+
Class(
|
|
213
|
+
repository_id=repo_id,
|
|
214
|
+
class_id=cls.id,
|
|
215
|
+
name=cls.name,
|
|
216
|
+
file_path=cls.file_path,
|
|
217
|
+
code=cls.code,
|
|
218
|
+
docstring=cls.docstring,
|
|
219
|
+
start_line=cls.start_line,
|
|
220
|
+
end_line=cls.end_line,
|
|
221
|
+
decorators=cls.decorators,
|
|
222
|
+
superclasses=cls.superclasses,
|
|
223
|
+
)
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _insert_call_edges(db: Session, functions) -> None:
|
|
228
|
+
pairs: set[tuple[str, str]] = {
|
|
229
|
+
(fn.id, callee_id) for fn in functions for callee_id in (fn.calls or [])
|
|
230
|
+
}
|
|
231
|
+
if pairs:
|
|
232
|
+
db.execute(
|
|
233
|
+
text(
|
|
234
|
+
"INSERT OR IGNORE INTO call_edges (caller_id, callee_id)"
|
|
235
|
+
" VALUES (:caller_id, :callee_id)"
|
|
236
|
+
),
|
|
237
|
+
[{"caller_id": c, "callee_id": e} for c, e in pairs],
|
|
238
|
+
)
|
codiff/diff/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Graph-diff layer: index → snapshot → diff → analysis → render."""
|