aildv 1.0.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.
- aildv/__init__.py +0 -0
- aildv/adapters.py +265 -0
- aildv/api_db.py +323 -0
- aildv/cache.py +87 -0
- aildv/ci_reader.py +554 -0
- aildv/cli.py +655 -0
- aildv/component_classifier.py +430 -0
- aildv/config_reader.py +105 -0
- aildv/diagnosis.py +178 -0
- aildv/environment.py +193 -0
- aildv/feature.py +271 -0
- aildv/inspector.py +288 -0
- aildv/onboarding.py +222 -0
- aildv/orchestration.py +230 -0
- aildv/project_reader.py +408 -0
- aildv/redaction.py +97 -0
- aildv/results.py +17 -0
- aildv/traceability.py +178 -0
- aildv/verification.py +257 -0
- aildv-1.0.0.dist-info/METADATA +220 -0
- aildv-1.0.0.dist-info/RECORD +25 -0
- aildv-1.0.0.dist-info/WHEEL +5 -0
- aildv-1.0.0.dist-info/entry_points.txt +2 -0
- aildv-1.0.0.dist-info/licenses/LICENSE +21 -0
- aildv-1.0.0.dist-info/top_level.txt +1 -0
aildv/__init__.py
ADDED
|
File without changes
|
aildv/adapters.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""Adapter interfaces and registries (v0.8.0).
|
|
2
|
+
|
|
3
|
+
Three extension points, each a small protocol with a registry:
|
|
4
|
+
|
|
5
|
+
- ``FrameworkDetector`` — recognizes a language/framework from repository files.
|
|
6
|
+
- ``CIProvider`` — discovers local verification steps in a CI configuration.
|
|
7
|
+
- ``VerificationAdapter`` — proposes local test commands for a project type.
|
|
8
|
+
|
|
9
|
+
Adding an adapter means implementing the protocol and appending it to the
|
|
10
|
+
matching registry (``FRAMEWORK_DETECTORS``, ``CI_PROVIDERS``,
|
|
11
|
+
``VERIFICATION_ADAPTERS``). See ``docs/EXTENDING.md`` for a worked example and
|
|
12
|
+
the tests each adapter needs. The interfaces are deliberately no more abstract
|
|
13
|
+
than the concrete adapters below require.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path, PurePosixPath
|
|
20
|
+
from typing import Any, ClassVar, Protocol, runtime_checkable
|
|
21
|
+
|
|
22
|
+
from aildv.ci_reader import discover_gitlab_checks
|
|
23
|
+
from aildv.inspector import RepositoryInfo
|
|
24
|
+
|
|
25
|
+
# --------------------------------------------------------------------------- #
|
|
26
|
+
# Framework detection
|
|
27
|
+
# --------------------------------------------------------------------------- #
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@runtime_checkable
|
|
31
|
+
class FrameworkDetector(Protocol):
|
|
32
|
+
"""Recognize a language/framework from repository files."""
|
|
33
|
+
|
|
34
|
+
name: str
|
|
35
|
+
|
|
36
|
+
def detect(self, root: Path, info: RepositoryInfo) -> list[str]:
|
|
37
|
+
"""Return the framework labels this repository declares."""
|
|
38
|
+
...
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class ManifestFrameworkDetector:
|
|
42
|
+
"""Report languages whose manifest files the inspector already matched."""
|
|
43
|
+
|
|
44
|
+
name = "manifest"
|
|
45
|
+
|
|
46
|
+
_MANIFESTS: ClassVar[dict[str, Any]] = {
|
|
47
|
+
"Go": "go.mod",
|
|
48
|
+
"Java": ("pom.xml", "build.gradle", "build.gradle.kts"),
|
|
49
|
+
"Python": ("pyproject.toml", "requirements.txt"),
|
|
50
|
+
"Node.js": "package.json",
|
|
51
|
+
"Flutter/Dart": "pubspec.yaml",
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
def detect(self, root: Path, info: RepositoryInfo) -> list[str]:
|
|
55
|
+
found = []
|
|
56
|
+
for language, manifests in self._MANIFESTS.items():
|
|
57
|
+
names = (manifests,) if isinstance(manifests, str) else manifests
|
|
58
|
+
if any((root / name).is_file() for name in names):
|
|
59
|
+
found.append(language)
|
|
60
|
+
return found
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
FRAMEWORK_DETECTORS: list[FrameworkDetector] = [ManifestFrameworkDetector()]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def detect_frameworks(root: Path, info: RepositoryInfo) -> list[str]:
|
|
67
|
+
"""Run every registered framework detector and merge the results."""
|
|
68
|
+
found: set[str] = set()
|
|
69
|
+
for detector in FRAMEWORK_DETECTORS:
|
|
70
|
+
found.update(detector.detect(root, info))
|
|
71
|
+
return sorted(found)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
# --------------------------------------------------------------------------- #
|
|
75
|
+
# CI providers
|
|
76
|
+
# --------------------------------------------------------------------------- #
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@runtime_checkable
|
|
80
|
+
class CIProvider(Protocol):
|
|
81
|
+
"""Discover local verification steps in one CI configuration format."""
|
|
82
|
+
|
|
83
|
+
name: str
|
|
84
|
+
|
|
85
|
+
def files(self) -> tuple[str, ...]:
|
|
86
|
+
"""Return the CI file names this provider understands."""
|
|
87
|
+
...
|
|
88
|
+
|
|
89
|
+
def discover(self, root: Path) -> list[dict[str, Any]]:
|
|
90
|
+
"""Return plan steps (never executing CI configuration)."""
|
|
91
|
+
...
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class GitLabCIProvider:
|
|
95
|
+
"""GitLab CI discovery (wraps :func:`aildv.ci_reader.discover_gitlab_checks`)."""
|
|
96
|
+
|
|
97
|
+
name = "gitlab"
|
|
98
|
+
|
|
99
|
+
def files(self) -> tuple[str, ...]:
|
|
100
|
+
return (".gitlab-ci.yml", ".gitlab-ci.yaml")
|
|
101
|
+
|
|
102
|
+
def discover(self, root: Path) -> list[dict[str, Any]]:
|
|
103
|
+
return discover_gitlab_checks(root)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
CI_PROVIDERS: list[CIProvider] = [GitLabCIProvider()]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def discover_ci_checks(root: Path) -> list[dict[str, Any]]:
|
|
110
|
+
"""Run every registered CI provider and merge the discovered steps."""
|
|
111
|
+
steps: list[dict[str, Any]] = []
|
|
112
|
+
for provider in CI_PROVIDERS:
|
|
113
|
+
steps.extend(provider.discover(root))
|
|
114
|
+
return steps
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# --------------------------------------------------------------------------- #
|
|
118
|
+
# Verification adapters
|
|
119
|
+
# --------------------------------------------------------------------------- #
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@runtime_checkable
|
|
123
|
+
class VerificationAdapter(Protocol):
|
|
124
|
+
"""Propose local test commands for one project type."""
|
|
125
|
+
|
|
126
|
+
name: str
|
|
127
|
+
|
|
128
|
+
def plan(
|
|
129
|
+
self,
|
|
130
|
+
root: Path,
|
|
131
|
+
info: RepositoryInfo,
|
|
132
|
+
projects: list[dict[str, Any]],
|
|
133
|
+
package_config: dict[str, Any] | None,
|
|
134
|
+
) -> list[dict[str, Any]]:
|
|
135
|
+
"""Return planned steps; the caller deduplicates them."""
|
|
136
|
+
...
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _step(name: str, argv: list[str], cwd: Path) -> dict[str, Any]:
|
|
140
|
+
return {"name": name, "argv": argv, "cwd": str(cwd), "status": "planned", "category": "local-unit"}
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class GoAdapter:
|
|
144
|
+
name = "go"
|
|
145
|
+
|
|
146
|
+
def plan(self, root, info, projects, package_config):
|
|
147
|
+
if "Go tests" in info.test_tools and (root / "go.mod").is_file():
|
|
148
|
+
return [_step("Go tests", ["go", "test", "./..."], root)]
|
|
149
|
+
return []
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class FlutterAdapter:
|
|
153
|
+
name = "flutter"
|
|
154
|
+
|
|
155
|
+
def plan(self, root, info, projects, package_config):
|
|
156
|
+
if "Flutter tests" in info.test_tools and (root / "pubspec.yaml").is_file():
|
|
157
|
+
return [_step("Flutter tests", ["flutter", "test"], root)]
|
|
158
|
+
return []
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class PytestAdapter:
|
|
162
|
+
name = "pytest"
|
|
163
|
+
|
|
164
|
+
def plan(self, root, info, projects, package_config):
|
|
165
|
+
if "pytest" in info.test_tools and (
|
|
166
|
+
(root / "pyproject.toml").is_file() or (root / "pytest.ini").is_file()
|
|
167
|
+
):
|
|
168
|
+
return [_step("Python tests", ["python", "-m", "pytest", "-q"], root)]
|
|
169
|
+
return []
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
class NpmAdapter:
|
|
173
|
+
name = "npm"
|
|
174
|
+
|
|
175
|
+
def plan(self, root, info, projects, package_config):
|
|
176
|
+
if not (package_config and (root / "package.json").is_file()):
|
|
177
|
+
return []
|
|
178
|
+
scripts = package_config.get("scripts", {})
|
|
179
|
+
manager = str(package_config.get("package_manager") or "npm").split("@")[0]
|
|
180
|
+
if manager not in {"npm", "pnpm", "yarn", "bun"}:
|
|
181
|
+
return []
|
|
182
|
+
steps = []
|
|
183
|
+
for name in ("test", "lint", "typecheck"):
|
|
184
|
+
if name in scripts:
|
|
185
|
+
command = ["npm", "run", name] if manager == "npm" else [manager, "run", name]
|
|
186
|
+
steps.append(_step(f"JavaScript {name}", command, root))
|
|
187
|
+
return steps
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class DotNetAdapter:
|
|
191
|
+
name = "dotnet"
|
|
192
|
+
|
|
193
|
+
def plan(self, root, info, projects, package_config):
|
|
194
|
+
steps = []
|
|
195
|
+
for group in projects:
|
|
196
|
+
if group.get("language") != ".NET":
|
|
197
|
+
continue
|
|
198
|
+
for detail in group.get("project_details", []):
|
|
199
|
+
if detail.get("is_test_project"):
|
|
200
|
+
path = root / detail["path"]
|
|
201
|
+
if path.is_file():
|
|
202
|
+
steps.append(_step(".NET tests", ["dotnet", "test", str(path)], root))
|
|
203
|
+
return steps
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
class JavaAdapter:
|
|
207
|
+
name = "java"
|
|
208
|
+
|
|
209
|
+
def plan(self, root, info, projects, package_config):
|
|
210
|
+
"""Plan Maven/Gradle tests for every build root, including nested ones."""
|
|
211
|
+
if "Java tests" not in info.test_tools:
|
|
212
|
+
return []
|
|
213
|
+
steps = []
|
|
214
|
+
for path in info.matched_files.get("Maven", []):
|
|
215
|
+
if PurePosixPath(path).name != "pom.xml":
|
|
216
|
+
continue
|
|
217
|
+
build_root = root / PurePosixPath(path).parent
|
|
218
|
+
wrapper = build_root / ("mvnw.cmd" if sys.platform == "win32" else "mvnw")
|
|
219
|
+
argv = [str(wrapper), "test"] if wrapper.is_file() else ["mvn", "test"]
|
|
220
|
+
steps.append(_step("Maven tests", argv, build_root))
|
|
221
|
+
for path in info.matched_files.get("Gradle", []):
|
|
222
|
+
if PurePosixPath(path).name not in ("build.gradle", "build.gradle.kts"):
|
|
223
|
+
continue
|
|
224
|
+
build_root = root / PurePosixPath(path).parent
|
|
225
|
+
wrapper = build_root / ("gradlew.bat" if sys.platform == "win32" else "gradlew")
|
|
226
|
+
argv = [str(wrapper), "test"] if wrapper.is_file() else ["gradle", "test"]
|
|
227
|
+
steps.append(_step("Gradle tests", argv, build_root))
|
|
228
|
+
return steps
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
# Order is preserved so plan output stays stable.
|
|
232
|
+
VERIFICATION_ADAPTERS: list[VerificationAdapter] = [
|
|
233
|
+
GoAdapter(),
|
|
234
|
+
FlutterAdapter(),
|
|
235
|
+
PytestAdapter(),
|
|
236
|
+
NpmAdapter(),
|
|
237
|
+
DotNetAdapter(),
|
|
238
|
+
JavaAdapter(),
|
|
239
|
+
]
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def plan_verification(
|
|
243
|
+
root: Path,
|
|
244
|
+
info: RepositoryInfo,
|
|
245
|
+
projects: list[dict[str, Any]],
|
|
246
|
+
package_config: dict[str, Any] | None = None,
|
|
247
|
+
) -> list[dict[str, Any]]:
|
|
248
|
+
"""Merge every verification adapter's steps, then CI-discovered steps."""
|
|
249
|
+
steps: list[dict[str, Any]] = []
|
|
250
|
+
|
|
251
|
+
def add(step: dict[str, Any]) -> None:
|
|
252
|
+
key = (tuple(step["argv"]), step["cwd"])
|
|
253
|
+
if not any((tuple(existing["argv"]), existing["cwd"]) == key for existing in steps):
|
|
254
|
+
steps.append(step)
|
|
255
|
+
|
|
256
|
+
for adapter in VERIFICATION_ADAPTERS:
|
|
257
|
+
for step in adapter.plan(root, info, projects, package_config):
|
|
258
|
+
add(step)
|
|
259
|
+
|
|
260
|
+
for candidate in discover_ci_checks(root):
|
|
261
|
+
if candidate["status"] != "planned":
|
|
262
|
+
steps.append(candidate)
|
|
263
|
+
continue
|
|
264
|
+
add(candidate)
|
|
265
|
+
return steps
|
aildv/api_db.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""API and database discovery (v0.4.0).
|
|
2
|
+
|
|
3
|
+
Read-only: AILDV discovers OpenAPI/Swagger definitions and their endpoints,
|
|
4
|
+
Postman/Newman collections, database technology and migration tooling, and
|
|
5
|
+
local database services. Contract diffs report breaking changes. AILDV only
|
|
6
|
+
ever probes ``127.0.0.1`` ports: it never connects to a remote or production
|
|
7
|
+
database.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import socket
|
|
16
|
+
import tomllib
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
import yaml
|
|
21
|
+
|
|
22
|
+
from aildv.inspector import IGNORED_DIRS, RepositoryInfo
|
|
23
|
+
|
|
24
|
+
_MAX_BYTES = 1_000_000
|
|
25
|
+
_PROBE_TIMEOUT = 0.25
|
|
26
|
+
_METHODS = ("get", "post", "put", "patch", "delete", "head", "options")
|
|
27
|
+
|
|
28
|
+
_DB_IMAGES = {
|
|
29
|
+
"postgres": "PostgreSQL", "postgresql": "PostgreSQL", "mysql": "MySQL",
|
|
30
|
+
"mariadb": "MariaDB", "mongo": "MongoDB", "mongodb": "MongoDB",
|
|
31
|
+
"mssql": "SQL Server", "redis": "Redis", "sqlite": "SQLite",
|
|
32
|
+
}
|
|
33
|
+
_DB_PACKAGES = {
|
|
34
|
+
"psycopg2": "PostgreSQL", "psycopg": "PostgreSQL", "psycopg2-binary": "PostgreSQL",
|
|
35
|
+
"sqlalchemy": "SQLAlchemy", "django": "Django ORM", "pymysql": "MySQL",
|
|
36
|
+
"mysqlclient": "MySQL", "pymongo": "MongoDB", "mongoose": "MongoDB",
|
|
37
|
+
"prisma": "Prisma", "@prisma/client": "Prisma", "npgsql": "PostgreSQL (.NET)",
|
|
38
|
+
}
|
|
39
|
+
_DB_GO_MODULES = {
|
|
40
|
+
"go.mongodb.org/mongo-driver": "MongoDB",
|
|
41
|
+
"github.com/redis/go-redis": "Redis",
|
|
42
|
+
"github.com/go-redis/redis": "Redis",
|
|
43
|
+
"github.com/lib/pq": "PostgreSQL",
|
|
44
|
+
"github.com/jackc/pgx": "PostgreSQL",
|
|
45
|
+
"github.com/go-sql-driver/mysql": "MySQL",
|
|
46
|
+
"github.com/mattn/go-sqlite3": "SQLite",
|
|
47
|
+
"gorm.io/gorm": "GORM",
|
|
48
|
+
}
|
|
49
|
+
_MIGRATION_DIRS = {
|
|
50
|
+
"migrations": "generic migrations", "alembic": "Alembic",
|
|
51
|
+
"flyway": "Flyway", "liquibase": "Liquibase",
|
|
52
|
+
}
|
|
53
|
+
_MIGRATION_FILES = {
|
|
54
|
+
"alembic.ini": "Alembic", "flyway.conf": "Flyway",
|
|
55
|
+
"liquibase.properties": "Liquibase", "schema.prisma": "Prisma Migrate",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _read_document(path: Path) -> Any:
|
|
60
|
+
"""Read a bounded JSON or YAML document without following symlinks."""
|
|
61
|
+
try:
|
|
62
|
+
if path.is_symlink() or not path.is_file() or path.stat().st_size > _MAX_BYTES:
|
|
63
|
+
return None
|
|
64
|
+
text = path.read_text(encoding="utf-8-sig")
|
|
65
|
+
except (OSError, UnicodeError):
|
|
66
|
+
return None
|
|
67
|
+
try:
|
|
68
|
+
if path.suffix == ".json":
|
|
69
|
+
return json.loads(text)
|
|
70
|
+
return yaml.safe_load(text)
|
|
71
|
+
except (json.JSONDecodeError, yaml.YAMLError):
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _endpoints(document: Any) -> list[dict[str, Any]]:
|
|
76
|
+
"""Extract path/method endpoints from an OpenAPI document."""
|
|
77
|
+
paths = document.get("paths") if isinstance(document, dict) else None
|
|
78
|
+
endpoints: list[dict[str, Any]] = []
|
|
79
|
+
if not isinstance(paths, dict):
|
|
80
|
+
return endpoints
|
|
81
|
+
for path, item in paths.items():
|
|
82
|
+
if not isinstance(item, dict):
|
|
83
|
+
continue
|
|
84
|
+
for method in _METHODS:
|
|
85
|
+
operation = item.get(method)
|
|
86
|
+
if isinstance(operation, dict):
|
|
87
|
+
endpoints.append(
|
|
88
|
+
{
|
|
89
|
+
"path": str(path),
|
|
90
|
+
"method": method.upper(),
|
|
91
|
+
"operation_id": operation.get("operationId"),
|
|
92
|
+
"summary": operation.get("summary"),
|
|
93
|
+
}
|
|
94
|
+
)
|
|
95
|
+
return sorted(endpoints, key=lambda entry: (entry["path"], entry["method"]))
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _affected(endpoints: list[dict[str, Any]], tokens: set[str]) -> list[dict[str, Any]]:
|
|
99
|
+
"""Return endpoints whose path/operation matches any request token."""
|
|
100
|
+
if not tokens:
|
|
101
|
+
return []
|
|
102
|
+
matched = []
|
|
103
|
+
for endpoint in endpoints:
|
|
104
|
+
haystack = " ".join(
|
|
105
|
+
str(value) for value in (
|
|
106
|
+
endpoint["path"], endpoint["operation_id"], endpoint["summary"],
|
|
107
|
+
) if value
|
|
108
|
+
).lower()
|
|
109
|
+
hits = sorted(token for token in tokens if token in haystack)
|
|
110
|
+
if hits:
|
|
111
|
+
matched.append({**endpoint, "matched_keywords": hits})
|
|
112
|
+
return matched
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def discover_api(root: Path, info: RepositoryInfo, request: str | None = None) -> dict[str, Any]:
|
|
116
|
+
"""Report OpenAPI definitions, endpoints, and Newman collections."""
|
|
117
|
+
root = root.expanduser().resolve()
|
|
118
|
+
definitions = []
|
|
119
|
+
endpoints: list[dict[str, Any]] = []
|
|
120
|
+
for relative in info.matched_files.get("OpenAPI", []):
|
|
121
|
+
document = _read_document(root / relative)
|
|
122
|
+
if not isinstance(document, dict):
|
|
123
|
+
continue
|
|
124
|
+
info_block = document.get("info") if isinstance(document.get("info"), dict) else {}
|
|
125
|
+
found = _endpoints(document)
|
|
126
|
+
definitions.append(
|
|
127
|
+
{
|
|
128
|
+
"path": relative,
|
|
129
|
+
"title": info_block.get("title"),
|
|
130
|
+
"version": info_block.get("version"),
|
|
131
|
+
"endpoint_count": len(found),
|
|
132
|
+
}
|
|
133
|
+
)
|
|
134
|
+
for endpoint in found:
|
|
135
|
+
endpoints.append({**endpoint, "definition": relative})
|
|
136
|
+
|
|
137
|
+
tokens = {
|
|
138
|
+
token for token in re.findall(r"[a-z0-9]+", (request or "").lower())
|
|
139
|
+
if len(token) >= 3
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
"definitions": definitions,
|
|
143
|
+
"endpoints": endpoints,
|
|
144
|
+
"affected_endpoints": _affected(endpoints, tokens),
|
|
145
|
+
"newman_collections": sorted(info.matched_files.get("Postman/Newman", [])),
|
|
146
|
+
"request": request,
|
|
147
|
+
"note": "Read-only discovery; AILDV never calls a remote API.",
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _db_from_packages(root: Path) -> set[str]:
|
|
152
|
+
"""Detect database technology from declared dependencies (names only)."""
|
|
153
|
+
found: set[str] = set()
|
|
154
|
+
package_json = root / "package.json"
|
|
155
|
+
if package_json.is_file() and not package_json.is_symlink():
|
|
156
|
+
try:
|
|
157
|
+
data = json.loads(package_json.read_text(encoding="utf-8"))
|
|
158
|
+
packages = {}
|
|
159
|
+
if isinstance(data, dict):
|
|
160
|
+
for key in ("dependencies", "devDependencies"):
|
|
161
|
+
if isinstance(data.get(key), dict):
|
|
162
|
+
packages.update(data[key])
|
|
163
|
+
found.update(_DB_PACKAGES[name] for name in packages if name in _DB_PACKAGES)
|
|
164
|
+
except (OSError, UnicodeError, json.JSONDecodeError):
|
|
165
|
+
pass
|
|
166
|
+
pyproject = root / "pyproject.toml"
|
|
167
|
+
if pyproject.is_file() and not pyproject.is_symlink():
|
|
168
|
+
try:
|
|
169
|
+
data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
|
|
170
|
+
deps = list(data.get("project", {}).get("dependencies", []))
|
|
171
|
+
for name, label in _DB_PACKAGES.items():
|
|
172
|
+
if any(str(dep).lower().startswith(name) for dep in deps):
|
|
173
|
+
found.add(label)
|
|
174
|
+
except (OSError, UnicodeError, tomllib.TOMLDecodeError):
|
|
175
|
+
pass
|
|
176
|
+
return found
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _db_from_go_mod(root: Path) -> set[str]:
|
|
180
|
+
"""Detect database drivers declared in go.mod (module names only)."""
|
|
181
|
+
path = root / "go.mod"
|
|
182
|
+
if not path.is_file() or path.is_symlink():
|
|
183
|
+
return set()
|
|
184
|
+
try:
|
|
185
|
+
text = path.read_text(encoding="utf-8", errors="replace")[:_MAX_BYTES]
|
|
186
|
+
except OSError:
|
|
187
|
+
return set()
|
|
188
|
+
return {
|
|
189
|
+
label for module, label in _DB_GO_MODULES.items() if module in text
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _migration_markers(root: Path) -> list[dict[str, str]]:
|
|
194
|
+
"""Find migration directories and files by name (bounded walk)."""
|
|
195
|
+
markers: list[dict[str, str]] = []
|
|
196
|
+
for current, dirs, files in os.walk(root, followlinks=False):
|
|
197
|
+
dirs[:] = sorted(
|
|
198
|
+
name for name in dirs
|
|
199
|
+
if name not in IGNORED_DIRS and not (Path(current) / name).is_symlink()
|
|
200
|
+
)
|
|
201
|
+
for name in dirs:
|
|
202
|
+
if name.lower() in _MIGRATION_DIRS:
|
|
203
|
+
relative = (Path(current) / name).relative_to(root).as_posix()
|
|
204
|
+
markers.append({"path": relative, "tool": _MIGRATION_DIRS[name.lower()]})
|
|
205
|
+
for name in files:
|
|
206
|
+
if name.lower() in _MIGRATION_FILES:
|
|
207
|
+
relative = (Path(current) / name).relative_to(root).as_posix()
|
|
208
|
+
markers.append({"path": relative, "tool": _MIGRATION_FILES[name.lower()]})
|
|
209
|
+
return sorted(markers, key=lambda item: item["path"])
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def discover_database(
|
|
213
|
+
root: Path, info: RepositoryInfo, projects: list[dict[str, Any]]
|
|
214
|
+
) -> dict[str, Any]:
|
|
215
|
+
"""Report database technology, migration tooling, and local services."""
|
|
216
|
+
root = root.expanduser().resolve()
|
|
217
|
+
technologies = set(_db_from_packages(root)) | _db_from_go_mod(root)
|
|
218
|
+
|
|
219
|
+
services = []
|
|
220
|
+
for compose_file in info.matched_files.get("Docker Compose", []):
|
|
221
|
+
document = _read_document(root / compose_file)
|
|
222
|
+
declared = document.get("services") if isinstance(document, dict) else None
|
|
223
|
+
if not isinstance(declared, dict):
|
|
224
|
+
continue
|
|
225
|
+
for name, service in declared.items():
|
|
226
|
+
if not isinstance(service, dict):
|
|
227
|
+
continue
|
|
228
|
+
image = str(service.get("image") or "").split(":")[0].split("/")[-1].lower()
|
|
229
|
+
if image not in _DB_IMAGES:
|
|
230
|
+
continue
|
|
231
|
+
ports = []
|
|
232
|
+
for item in service.get("ports", []) if isinstance(service.get("ports"), list) else []:
|
|
233
|
+
try:
|
|
234
|
+
ports.append(int(str(item).split("/")[0].split(":")[-1]))
|
|
235
|
+
except ValueError:
|
|
236
|
+
continue
|
|
237
|
+
technologies.add(_DB_IMAGES[image])
|
|
238
|
+
services.append(
|
|
239
|
+
{
|
|
240
|
+
"name": str(name),
|
|
241
|
+
"image": _DB_IMAGES[image],
|
|
242
|
+
"local_ports": ports,
|
|
243
|
+
"reachable": any(_local_port_open(port) for port in ports),
|
|
244
|
+
}
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
return {
|
|
248
|
+
"technologies": sorted(technologies),
|
|
249
|
+
"migrations": _migration_markers(root),
|
|
250
|
+
"local_services": sorted(services, key=lambda item: item["name"]),
|
|
251
|
+
"note": "Local 127.0.0.1 probes only; AILDV never connects to a remote or production database.",
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _local_port_open(port: int) -> bool:
|
|
256
|
+
"""Probe a local port only; never a remote host."""
|
|
257
|
+
try:
|
|
258
|
+
with socket.create_connection(("127.0.0.1", port), timeout=_PROBE_TIMEOUT):
|
|
259
|
+
return True
|
|
260
|
+
except OSError:
|
|
261
|
+
return False
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def diff_openapi(base: Any, head: Any) -> dict[str, Any]:
|
|
265
|
+
"""Compare two OpenAPI documents and classify breaking vs additive changes."""
|
|
266
|
+
changes: list[dict[str, Any]] = []
|
|
267
|
+
base_paths = base.get("paths", {}) if isinstance(base, dict) else {}
|
|
268
|
+
head_paths = head.get("paths", {}) if isinstance(head, dict) else {}
|
|
269
|
+
base_paths = base_paths if isinstance(base_paths, dict) else {}
|
|
270
|
+
head_paths = head_paths if isinstance(head_paths, dict) else {}
|
|
271
|
+
|
|
272
|
+
for path in sorted(base_paths):
|
|
273
|
+
if path not in head_paths:
|
|
274
|
+
changes.append({"kind": "breaking", "change": "removed endpoint", "path": path})
|
|
275
|
+
continue
|
|
276
|
+
base_item = base_paths[path] if isinstance(base_paths[path], dict) else {}
|
|
277
|
+
head_item = head_paths[path] if isinstance(head_paths[path], dict) else {}
|
|
278
|
+
for method in _METHODS:
|
|
279
|
+
if method in base_item and method not in head_item:
|
|
280
|
+
changes.append(
|
|
281
|
+
{"kind": "breaking", "change": "removed method", "path": path, "method": method.upper()}
|
|
282
|
+
)
|
|
283
|
+
for path in sorted(head_paths):
|
|
284
|
+
if path not in base_paths:
|
|
285
|
+
changes.append({"kind": "additive", "change": "added endpoint", "path": path})
|
|
286
|
+
|
|
287
|
+
def schemas(document: Any) -> dict[str, Any]:
|
|
288
|
+
components = document.get("components", {}) if isinstance(document, dict) else {}
|
|
289
|
+
result = components.get("schemas", {}) if isinstance(components, dict) else {}
|
|
290
|
+
return result if isinstance(result, dict) else {}
|
|
291
|
+
|
|
292
|
+
base_schemas, head_schemas = schemas(base), schemas(head)
|
|
293
|
+
for name in sorted(base_schemas):
|
|
294
|
+
base_schema = base_schemas[name] if isinstance(base_schemas[name], dict) else {}
|
|
295
|
+
if name not in head_schemas:
|
|
296
|
+
changes.append({"kind": "breaking", "change": "removed schema", "schema": name})
|
|
297
|
+
continue
|
|
298
|
+
head_schema = head_schemas[name] if isinstance(head_schemas[name], dict) else {}
|
|
299
|
+
new_required = set(head_schema.get("required", []) or []) - set(base_schema.get("required", []) or [])
|
|
300
|
+
for prop in sorted(new_required):
|
|
301
|
+
changes.append(
|
|
302
|
+
{"kind": "breaking", "change": "new required property", "schema": name, "property": prop}
|
|
303
|
+
)
|
|
304
|
+
base_props = base_schema.get("properties", {}) or {}
|
|
305
|
+
head_props = head_schema.get("properties", {}) or {}
|
|
306
|
+
for prop in sorted(base_props):
|
|
307
|
+
if prop not in head_props:
|
|
308
|
+
changes.append(
|
|
309
|
+
{"kind": "breaking", "change": "removed property", "schema": name, "property": prop}
|
|
310
|
+
)
|
|
311
|
+
elif (
|
|
312
|
+
isinstance(base_props[prop], dict) and isinstance(head_props[prop], dict)
|
|
313
|
+
and base_props[prop].get("type") != head_props[prop].get("type")
|
|
314
|
+
):
|
|
315
|
+
changes.append(
|
|
316
|
+
{"kind": "breaking", "change": "changed property type", "schema": name, "property": prop}
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
return {
|
|
320
|
+
"breaking": [change for change in changes if change["kind"] == "breaking"],
|
|
321
|
+
"additive": [change for change in changes if change["kind"] == "additive"],
|
|
322
|
+
"changes": changes,
|
|
323
|
+
}
|
aildv/cache.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Local cache with signature-based invalidation (v0.8.0).
|
|
2
|
+
|
|
3
|
+
The cache is opt-in and lives in ``.aildv/cache.json``. An entry is only
|
|
4
|
+
returned when the repository signature (file paths, sizes, and mtimes) still
|
|
5
|
+
matches, so a changed repository always recomputes. A malformed or missing
|
|
6
|
+
cache file is treated as empty.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from aildv.inspector import IGNORED_DIRS
|
|
18
|
+
|
|
19
|
+
CACHE_FILE = ".aildv/cache.json"
|
|
20
|
+
_MAX_ENTRIES = 20
|
|
21
|
+
_MAX_FILES = 20000
|
|
22
|
+
|
|
23
|
+
# The cache directory must not be part of the signature, or writing the cache
|
|
24
|
+
# would invalidate its own entry.
|
|
25
|
+
_SIGNATURE_IGNORED = IGNORED_DIRS | {".aildv"}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def repo_signature(root: Path) -> str:
|
|
29
|
+
"""Hash repository paths, sizes, and mtimes (ignoring generated dirs)."""
|
|
30
|
+
root = root.expanduser().resolve()
|
|
31
|
+
digest = hashlib.sha256()
|
|
32
|
+
count = 0
|
|
33
|
+
for current, dirs, files in os.walk(root, followlinks=False):
|
|
34
|
+
dirs[:] = sorted(
|
|
35
|
+
name for name in dirs
|
|
36
|
+
if name not in _SIGNATURE_IGNORED and not (Path(current) / name).is_symlink()
|
|
37
|
+
)
|
|
38
|
+
for name in sorted(files):
|
|
39
|
+
path = Path(current) / name
|
|
40
|
+
if path.is_symlink():
|
|
41
|
+
continue
|
|
42
|
+
try:
|
|
43
|
+
stat = path.stat()
|
|
44
|
+
except OSError:
|
|
45
|
+
continue
|
|
46
|
+
relative = path.relative_to(root).as_posix()
|
|
47
|
+
digest.update(f"{relative}:{stat.st_size}:{int(stat.st_mtime)}".encode())
|
|
48
|
+
count += 1
|
|
49
|
+
if count >= _MAX_FILES:
|
|
50
|
+
break
|
|
51
|
+
if count >= _MAX_FILES:
|
|
52
|
+
break
|
|
53
|
+
return digest.hexdigest()
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _load(root: Path) -> dict[str, Any]:
|
|
57
|
+
path = root.expanduser().resolve() / CACHE_FILE
|
|
58
|
+
try:
|
|
59
|
+
if path.is_symlink() or not path.is_file():
|
|
60
|
+
return {}
|
|
61
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
62
|
+
except (OSError, UnicodeError, json.JSONDecodeError):
|
|
63
|
+
return {}
|
|
64
|
+
return data if isinstance(data, dict) else {}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def read_cache(root: Path, key: str) -> Any | None:
|
|
68
|
+
"""Return a cached value only when the repository signature still matches."""
|
|
69
|
+
entry = _load(root).get(key)
|
|
70
|
+
if not isinstance(entry, dict):
|
|
71
|
+
return None
|
|
72
|
+
if entry.get("signature") != repo_signature(root):
|
|
73
|
+
return None
|
|
74
|
+
return entry.get("value")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def write_cache(root: Path, key: str, value: Any) -> None:
|
|
78
|
+
"""Store a value under the current repository signature."""
|
|
79
|
+
root = root.expanduser().resolve()
|
|
80
|
+
data = _load(root)
|
|
81
|
+
data[key] = {"signature": repo_signature(root), "value": value}
|
|
82
|
+
if len(data) > _MAX_ENTRIES:
|
|
83
|
+
for stale in list(data)[:-_MAX_ENTRIES]:
|
|
84
|
+
del data[stale]
|
|
85
|
+
path = root / CACHE_FILE
|
|
86
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
87
|
+
path.write_text(json.dumps(data, indent=2), encoding="utf-8")
|