"""Repository scanner and path resolver.""" from __future__ import annotations from pathlib import PurePosixPath import hashlib from .repo_extract import _is_parser_failure, extract_references, language_name from .repo_graph import dependency_first_order, strongly_connected_components from .repo_model import DependencyEdge, Diagnostic, FileInfo, ReferenceInfo, Repo, RepoInfo from .repo_planning import build_concatenation_tree from .repo_resolver import Resolver SOURCE_EXTENSIONS = {".py", ".js", ".jsx", ".ts", ".tsx", ".c", ".h", ".cc", ".cpp", ".cxx", ".hpp", ".go", ".java", ".cs", ".rs", ".rb", ".php", ".kt", ".swift"} def _text(content: bytes | str, encoding: str | None) -> str: if isinstance(content, str): return content return content.decode(encoding or "utf-8", errors="replace") def scan(repo: Repo, *, use_treesitter: bool = True, include_weak: bool = False) -> RepoInfo: """Scan one repository revision without mutating or materializing content.""" files = list(repo.iter_files()) normalized = {PurePosixPath(file.path).as_posix().lstrip("/"): file for file in files} paths = set(normalized) texts = {path: _text(file.content, file.encoding) for path, file in normalized.items()} resolver = Resolver(texts) infos: list[FileInfo] = [] edges: list[DependencyEdge] = [] diagnostics: list[Diagnostic] = [] reference_infos: list[ReferenceInfo] = [] unresolved = external = ambiguous = parsed = ast_files = fallback_files = 0 for file in files: path = PurePosixPath(file.path).as_posix().lstrip("/") raw = file.content if isinstance(file.content, bytes) else file.content.encode() text = texts[path] lang = language_name(file.language, path) try: refs, backend = extract_references(text, lang, path, use_treesitter=use_treesitter) except BaseException as error: # Keep batch processing alive even if a third-party parser raises # outside its normal exception hierarchy. if not _is_parser_failure(error): raise refs, backend = extract_references(text, lang, path, use_treesitter=False) diagnostics.append(Diagnostic( path, "warning", f"reference parser failed: {type(error).__name__}", "stackbuild", )) if backend == "tree-sitter": ast_files += 1 else: fallback_files += 1 if refs: parsed += 1 references: list[str] = [] for ref in refs: resolution = resolver.resolve(path, ref.name, lang) reference_infos.append(ReferenceInfo( path, ref.name, ref.kind, resolution.status, resolution.target, resolution.candidates, resolution.confidence, ref.evidence, resolution.evidence, )) if resolution.status == "internal" and resolution.target: edges.append(DependencyEdge(path, resolution.target, ref.kind, resolution.confidence, "resolved", ref.evidence)) references.append(resolution.target) elif resolution.status == "ambiguous": ambiguous += 1 if resolution.evidence in {"java-wildcard-package", "go-package", "c-include-candidates"}: for target in resolution.candidates: if target != path: confidence = ( 0.75 if resolution.evidence != "c-include-candidates" else 0.65 ) edges.append(DependencyEdge(path, target, ref.kind, confidence, "resolved", ref.evidence)) elif include_weak: for target in resolution.candidates[:4]: if target != path: edges.append(DependencyEdge(path, target, ref.kind, 0.45, "ambiguous", ref.evidence)) elif resolution.status == "external": external += 1 elif resolution.status == "unresolved": unresolved += 1 infos.append(FileInfo(path, lang, len(raw), hashlib.sha1(raw).hexdigest(), tuple(references))) nodes = sorted(paths) edges = list(dict.fromkeys(edges)) reference_infos = list(dict.fromkeys(reference_infos)) components = strongly_connected_components(nodes, edges) order = dependency_first_order(nodes, edges) if unresolved: diagnostics.append(Diagnostic("", "info", f"{unresolved} references could not be resolved", "stackbuild")) if ambiguous: diagnostics.append(Diagnostic("", "info", f"{ambiguous} references have multiple candidates", "stackbuild")) sorted_infos = tuple(sorted(infos, key=lambda item: item.path)) edge_tuple = tuple(edges) component_tuple = tuple(components) tree = build_concatenation_tree(repo.repo_id, sorted_infos, edge_tuple, order, component_tuple) return RepoInfo(repo_id=repo.repo_id, revision_id=repo.revision_id, files=sorted_infos, edges=edge_tuple, topological_order=order, strongly_connected_components=component_tuple, diagnostics=tuple(diagnostics), stats={ "files": len(files), "parsed_files": parsed, "tree_sitter_files": ast_files, "regex_fallback_files": fallback_files, "resolved_edges": sum(edge.status == "resolved" for edge in edges), "references": len(reference_infos), "internal_references": sum(ref.status == "internal" for ref in reference_infos), "external_references": sum(ref.status == "external" for ref in reference_infos), "unresolved_references": sum(ref.status == "unresolved" for ref in reference_infos), "ambiguous_references": sum(ref.status == "ambiguous" for ref in reference_infos), }, references=tuple(reference_infos), concatenation_tree=tree)