Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ Issues = "https://github.com/EhsanAzish80/Devscope/issues"
Changelog = "https://github.com/EhsanAzish80/Devscope/releases"

[project.optional-dependencies]
graph = [
"tree-sitter-language-pack>=0.9.0; python_version >= '3.10'",
]
dev = [
"pytest>=7.4.0",
"pytest-cov>=4.1.0",
Expand Down Expand Up @@ -98,7 +101,7 @@ check_untyped_defs = true
strict_equality = true

[[tool.mypy.overrides]]
module = ["gitpython", "git.*"]
module = ["gitpython", "git.*", "tree_sitter_language_pack"]
ignore_missing_imports = true

[tool.pytest.ini_options]
Expand Down
20 changes: 4 additions & 16 deletions src/devscope/analyzers/hotspots.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@


class HotspotDetector:
"""Detects code hotspots using LOC, depth, and test proximity."""
"""Legacy size-only hotspot detector used outside PR risk ranking."""

# Risk scoring weights
WEIGHT_LOC = 0.4
WEIGHT_DEPTH = 0.3
WEIGHT_NO_TESTS = 0.3
WEIGHT_LOC = 1.0

# Thresholds
HIGH_LOC_THRESHOLD = 500
Expand Down Expand Up @@ -143,6 +141,7 @@ def _calculate_risk_score(self, loc: int, depth: int, has_nearby_tests: bool) ->
Returns:
Risk score (0-100)
"""
del depth, has_nearby_tests
# LOC component (0-100)
if loc > self.HIGH_LOC_THRESHOLD:
loc_score = 100.0
Expand All @@ -153,18 +152,7 @@ def _calculate_risk_score(self, loc: int, depth: int, has_nearby_tests: bool) ->
else:
loc_score = loc * 50 / self.MEDIUM_LOC_THRESHOLD

# Depth component (0-100)
depth_score = float(min(100, (depth / self.HIGH_DEPTH_THRESHOLD) * 100))

# Test proximity component (0 or 100)
test_score = 0 if has_nearby_tests else 100

# Weighted combination
risk_score = (
self.WEIGHT_LOC * loc_score
+ self.WEIGHT_DEPTH * depth_score
+ self.WEIGHT_NO_TESTS * test_score
)
risk_score = self.WEIGHT_LOC * loc_score

return round(risk_score, 1)

Expand Down
32 changes: 28 additions & 4 deletions src/devscope/demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def demo_report() -> dict[str, Any]:
"evidence": {"uncovered_lines": list(range(453, 465))},
}
return {
"schema_version": "1.0",
"schema_version": 2,
"kind": "review",
"demo": True,
"target_commit": "1" * 40,
Expand All @@ -38,12 +38,32 @@ def demo_report() -> dict[str, Any]:
"history": {"commits_analyzed": 40, "limit": 200, "revision": "1" * 40},
"packages": [],
"package_summary": [],
"model": {"fitted": False},
"changed_source_files": 2,
"checklist": [
{
"path": "billing/service.py",
"line": 453,
"lines": 635,
"risk": 0.81,
"rank": 1,
"calibration": "global",
"evidence": [
{
"kind": "defect_history",
"weight": 0.34,
"text": "7 bug fixes traced to this file in 12 months",
"refs": ["a1b2c3d"],
},
{
"kind": "missing_cochange",
"weight": 0.21,
"text": "billing/models.py changed with this file in 6 commits; not in this diff",
"refs": ["billing/models.py"],
},
],
"mitigating": [],
"context": {"ai_authored_lines": 112, "owners": ["@alice"]},
"recent_commits": 12,
"related_files": [{"path": "billing/models.py", "cochanges": 6}],
"findings": [size, missed],
Expand All @@ -58,6 +78,12 @@ def demo_report() -> dict[str, Any]:
"path": "auth/session.py",
"line": 24,
"lines": 148,
"risk": 0.12,
"rank": 2,
"calibration": "global",
"evidence": [],
"mitigating": [],
"context": {},
"recent_commits": 3,
"related_files": [],
"findings": [],
Expand Down Expand Up @@ -143,9 +169,7 @@ def render_demo(console: "Console", report: dict[str, Any]) -> None:
" Check interactions",
f"{related['path']}{separator}{related['cochanges']} observed co-changes",
)
table.add_row(
second["path"], f"{second['lines']} lines{separator}no configured warning triggered"
)
table.add_row(second["path"], f"Risk {second['risk']:.2f}")
console.print(table)
console.print(
f"\n[bold]Sample patch coverage:[/bold] {report['coverage']['percent']}% of mapped added executable lines"
Expand Down
5 changes: 5 additions & 0 deletions src/devscope/graph/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Optional point-in-time source import graph."""

from devscope.graph.imports import graph_available, import_edges

__all__ = ["graph_available", "import_edges"]
108 changes: 108 additions & 0 deletions src/devscope/graph/imports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""Tree-sitter-backed import extraction for supported source languages."""

from __future__ import annotations

import re
from pathlib import PurePosixPath
from typing import Any

LANGUAGES = {
".py": "python",
".js": "javascript",
".jsx": "javascript",
".ts": "typescript",
".tsx": "tsx",
".go": "go",
".swift": "swift",
".rs": "rust",
}
IMPORT_NODES = {
"python": {"import_statement", "import_from_statement"},
"javascript": {"import_statement", "export_statement", "call_expression"},
"typescript": {"import_statement", "export_statement", "call_expression"},
"tsx": {"import_statement", "export_statement", "call_expression"},
"go": {"import_spec"},
"swift": {"import_declaration"},
"rust": {"use_declaration", "extern_crate_declaration"},
}


def _provider() -> Any | None:
try:
from tree_sitter_language_pack import get_parser
except ImportError:
return None
return get_parser


def graph_available() -> bool:
"""Return whether the optional graph parser extra is installed."""
return _provider() is not None


def _walk(node: Any) -> list[Any]:
result = [node]
for child in node.children:
result.extend(_walk(child))
return result


def _module_candidates(path: str, module: str) -> list[str]:
current = PurePosixPath(path).parent
cleaned = module.strip("'\"; ")
if cleaned.startswith("."):
relative = current.joinpath(cleaned).as_posix()
else:
relative = cleaned.replace("::", "/").replace(".", "/")
relative = re.sub(r"/+", "/", relative).lstrip("./")
parts = [part for part in relative.split("/") if part]
candidates = [relative, f"{relative}/index", f"{relative}/__init__"]
if parts:
candidates.append(parts[-1])
if parts and parts[0] in {"crate", "self", "super"}:
candidates.extend("/".join(parts[1:end]) for end in range(len(parts), 1, -1))
return candidates


def _resolve(path: str, module: str, known_paths: set[str]) -> str | None:
extensions = tuple(LANGUAGES)
for candidate in _module_candidates(path, module):
for known in known_paths:
stem = known
for extension in extensions:
if stem.endswith(extension):
stem = stem[: -len(extension)]
break
if stem == candidate or stem.endswith("/" + candidate):
return known
return None


def import_edges(path: str, source: str, known_paths: set[str]) -> set[str]:
"""Return repository paths imported by ``path`` using its syntax tree."""
language = LANGUAGES.get(PurePosixPath(path).suffix.lower())
get_parser = _provider()
if language is None or get_parser is None or not source:
return set()
tree = get_parser(language).parse(source.encode("utf-8"))
modules: set[str] = set()
data = source.encode("utf-8")
for node in _walk(tree.root_node):
if node.type not in IMPORT_NODES[language]:
continue
text = data[node.start_byte : node.end_byte].decode("utf-8", errors="replace")
quoted = re.findall(r"['\"]([^'\"]+)['\"]", text)
modules.update(quoted)
if language == "python":
match = re.search(r"(?:from|import)\s+([.\w]+)", text)
if match:
modules.add(match.group(1))
elif language == "swift":
match = re.search(r"\bimport\s+(?:\w+\s+)?([\w.]+)", text)
if match:
modules.add(match.group(1))
elif language == "rust":
match = re.search(r"\b(?:use|crate)\s+([\w:]+)", text)
if match:
modules.add(match.group(1))
return {target for module in modules if (target := _resolve(path, module, known_paths))}
82 changes: 75 additions & 7 deletions src/devscope/index/git_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import subprocess
from collections.abc import Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
Expand Down Expand Up @@ -75,12 +76,18 @@ def run(cwd: Path, *args: str, input_text: Optional[str] = None) -> str:
)
if completed.returncode != 0:
detail = completed.stderr.strip() or "Git command failed"
lowered = detail.lower()
if "promisor remote" in lowered or "lazy fetch" in lowered:
raise GitError(
"Repository is missing promised Git objects. Use a full clone or run "
"`git fetch --refetch` before indexing."
)
raise GitError(detail)
return completed.stdout

def head(self) -> str:
"""Return the current commit."""
return self.run(self.root, "rev-parse", "--verify", "HEAD").strip()
def head(self, ref: str = "HEAD") -> str:
"""Resolve a commit ref without assuming the working tree branch."""
return self.run(self.root, "rev-parse", "--verify", f"{ref}^{{commit}}").strip()

def is_ancestor(self, older: str, newer: str) -> bool:
"""Return whether older is reachable from newer."""
Expand All @@ -90,12 +97,12 @@ def is_ancestor(self, older: str, newer: str) -> bool:
return False
return True

def revisions(self, *, since: Optional[str], max_count: int) -> list[str]:
def revisions(self, *, since: Optional[str], max_count: int, ref: str = "HEAD") -> list[str]:
"""Return the selected history oldest first."""
args = ["rev-list", "--topo-order", f"--max-count={max_count}"]
if since:
args.append(f"--since={since}")
args.append("HEAD")
args.append(ref)
return list(reversed(self.run(self.root, *args).splitlines()))

def commit_info(self, sha: str) -> CommitInfo:
Expand All @@ -105,7 +112,7 @@ def commit_info(self, sha: str) -> CommitInfo:
"show",
"-s",
"--no-show-signature",
"--format=%H%x1f%P%x1f%an%x1f%ae%x1f%at%x1f%ct%x1f%B%x1e",
"--format=%H%x1f%P%x1f%aN%x1f%aE%x1f%at%x1f%ct%x1f%B%x1e",
sha,
)
fields = payload.rstrip("\n\x1e").split("\x1f", 6)
Expand All @@ -132,7 +139,7 @@ def commit_infos(self, revisions: Sequence[str]) -> dict[str, CommitInfo]:
"--stdin",
"-z",
"--no-show-signature",
"--format=%H%x00%P%x00%an%x00%ae%x00%at%x00%ct%x00%B",
"--format=%H%x00%P%x00%aN%x00%aE%x00%at%x00%ct%x00%B",
input_text="\n".join(revisions),
)
fields = payload.rstrip("\0").split("\0")
Expand All @@ -154,6 +161,67 @@ def commit_infos(self, revisions: Sequence[str]) -> dict[str, CommitInfo]:
)
return result

def landed_at_pending(
self, pending: Sequence[str], infos: dict[str, CommitInfo], ref: str = "HEAD"
) -> dict[str, int]:
"""Map only newly indexed commits to their first-parent landing timestamps."""
selected = set(pending)
if not selected:
return {}
first_parent_rows = self.run(
self.root, "rev-list", "--first-parent", "--parents", ref
).splitlines()
first_parent = [row.split()[0] for row in first_parent_rows]
parents_by_sha: dict[str, tuple[str, ...]] = {}
for row in first_parent_rows:
parts = row.split()
parents_by_sha[parts[0]] = tuple(parts[1:])
mainline = set(first_parent)
result = {
sha: infos[sha].committed_at for sha in selected.intersection(mainline) if sha in infos
}
merges = [
(sha, infos[sha].parents[0], infos[sha].committed_at)
for sha in reversed(first_parent)
if sha in infos and len(infos[sha].parents) > 1
]

def merged_commits(item: tuple[str, str, int]) -> list[str]:
merge_sha, first_parent_sha, _landed_at = item
return self.run(self.root, "rev-list", f"^{first_parent_sha}", merge_sha).splitlines()

if merges:
workers = min(8, len(merges))
with ThreadPoolExecutor(max_workers=workers) as executor:
batches = list(executor.map(merged_commits, merges))
for (_merge_sha, _first_parent_sha, landed_at), commits in zip(merges, batches):
for sha in commits:
if sha in selected and sha not in mainline and sha not in result:
result[sha] = landed_at

missing = selected.difference(result)
if missing:
new_merge_shas = {item[0] for item in merges}
for merge_sha in reversed(first_parent):
parents = parents_by_sha[merge_sha]
if len(parents) <= 1 or merge_sha in new_merge_shas:
continue
reachable = set(
self.run(self.root, "rev-list", f"^{parents[0]}", merge_sha).splitlines()
)
matched = missing.intersection(reachable)
if not matched:
continue
landed_at = self.commit_info(merge_sha).committed_at
for sha in matched:
result[sha] = landed_at
missing.difference_update(matched)
if not missing:
break
if missing:
raise GitError(f"Could not determine landing time for {len(missing)} commits")
return result

def changes(self, sha: str) -> list[FileChange]:
"""Read rename-aware numstat entries for one commit."""
raw = self.run(
Expand Down
Loading
Loading