Download stackgo/stackbuild/repo_resolver.py from s0duku/the-stack-go: direct link, hf CLI and curl.
- Browser
- Download file 22.8 kB
-
https://huggingface.co/datasets/s0duku/the-stack-go/resolve/main/stackgo/stackbuild/repo_resolver.py
- Command line
-
hf download hf://datasets/s0duku/the-stack-go/stackgo/stackbuild/repo_resolver.py
-
curl -L -o repo_resolver.py https://huggingface.co/datasets/s0duku/the-stack-go/resolve/main/stackgo/stackbuild/repo_resolver.py
22.8 kB
| """Language-aware resolution of extracted references to repository files.""" | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import json | |
| import posixpath | |
| import re | |
| import tomllib | |
| class Resolution: | |
| status: str | |
| target: str | None = None | |
| candidates: tuple[str, ...] = () | |
| confidence: float = 0.0 | |
| evidence: str = "" | |
| def _unique(values): | |
| return list(dict.fromkeys(value for value in values if value)) | |
| def _jsonc_loads(text: str): | |
| """Load the JSON-with-comments dialect used by tsconfig/jsconfig files.""" | |
| output: list[str] = [] | |
| index = 0 | |
| quote: str | None = None | |
| while index < len(text): | |
| char = text[index] | |
| if quote: | |
| output.append(char) | |
| if char == "\\" and index + 1 < len(text): | |
| index += 1 | |
| output.append(text[index]) | |
| elif char == quote: | |
| quote = None | |
| elif char == '"': | |
| quote = char | |
| output.append(char) | |
| elif text.startswith("//", index): | |
| index = text.find("\n", index) | |
| if index < 0: | |
| break | |
| output.append("\n") | |
| elif text.startswith("/*", index): | |
| end = text.find("*/", index + 2) | |
| index = len(text) if end < 0 else end + 1 | |
| else: | |
| output.append(char) | |
| index += 1 | |
| cleaned = "".join(output) | |
| output = [] | |
| index = 0 | |
| quote = None | |
| while index < len(cleaned): | |
| char = cleaned[index] | |
| if quote: | |
| output.append(char) | |
| if char == "\\" and index + 1 < len(cleaned): | |
| index += 1 | |
| output.append(cleaned[index]) | |
| elif char == quote: | |
| quote = None | |
| elif char == '"': | |
| quote = char | |
| output.append(char) | |
| elif char == ",": | |
| lookahead = index + 1 | |
| while lookahead < len(cleaned) and cleaned[lookahead].isspace(): | |
| lookahead += 1 | |
| if lookahead >= len(cleaned) or cleaned[lookahead] not in "]}": | |
| output.append(char) | |
| else: | |
| output.append(char) | |
| index += 1 | |
| return json.loads("".join(output)) | |
| class Resolver: | |
| """Resolve references against an immutable repository path index.""" | |
| def __init__(self, files: dict[str, str]): | |
| self.files = files | |
| self.paths = set(files) | |
| self.suffix_paths = self._suffix_paths() | |
| self.python_roots = self._python_roots() | |
| self.js_base_urls, self.js_aliases, self.js_package = self._js_config() | |
| self.go_module = self._go_module() | |
| self.rust_packages = self._rust_packages() | |
| self.elixir_modules = self._elixir_modules() | |
| self.csharp_namespaces = self._csharp_namespaces() | |
| self.swift_external_modules = self._swift_external_modules() | |
| def _suffix_paths(self) -> dict[str, tuple[str, ...]]: | |
| suffixes: dict[str, list[str]] = {} | |
| for path in sorted(self.paths): | |
| parts = path.split("/") | |
| for index in range(len(parts)): | |
| suffixes.setdefault("/".join(parts[index:]), []).append(path) | |
| return {suffix: tuple(paths) for suffix, paths in suffixes.items()} | |
| def _python_roots(self) -> tuple[str, ...]: | |
| roots = [""] | |
| if any(path.startswith("src/") for path in self.paths): | |
| roots.append("src") | |
| for path, text in self.files.items(): | |
| if path != "pyproject.toml": | |
| continue | |
| try: | |
| config = tomllib.loads(text) | |
| package_dir = config.get("tool", {}).get("setuptools", {}).get("package-dir", {}) | |
| roots.extend(value.strip("./") for value in package_dir.values() if isinstance(value, str)) | |
| where = config.get("tool", {}).get("setuptools", {}).get("packages", {}).get("find", {}).get("where", []) | |
| roots.extend(value.strip("./") for value in where if isinstance(value, str)) | |
| except (tomllib.TOMLDecodeError, AttributeError): | |
| pass | |
| return tuple(dict.fromkeys(roots)) | |
| def _js_config(self) -> tuple[tuple[str, ...], tuple[tuple[str, tuple[str, ...]], ...], str | None]: | |
| bases = [""] | |
| aliases: list[tuple[str, tuple[str, ...]]] = [] | |
| package = None | |
| for path in ("package.json", "tsconfig.json", "jsconfig.json"): | |
| text = self.files.get(path) | |
| if not text: | |
| continue | |
| try: | |
| data = _jsonc_loads(text) | |
| except json.JSONDecodeError: | |
| continue | |
| if path == "package.json": | |
| package = data.get("name") if isinstance(data.get("name"), str) else None | |
| continue | |
| options = data.get("compilerOptions", {}) | |
| base = options.get("baseUrl") | |
| if isinstance(base, str): | |
| bases.append(base.strip("./")) | |
| for pattern, targets in options.get("paths", {}).items(): | |
| if isinstance(pattern, str) and isinstance(targets, list): | |
| aliases.append((pattern, tuple(target for target in targets if isinstance(target, str)))) | |
| return tuple(dict.fromkeys(bases)), tuple(aliases), package | |
| def _go_module(self) -> str | None: | |
| text = self.files.get("go.mod", "") | |
| match = re.search(r"^\s*module\s+(\S+)", text, re.M) | |
| return match.group(1) if match else None | |
| def _rust_packages(self) -> tuple[tuple[str, str], ...]: | |
| packages = [] | |
| for path, text in self.files.items(): | |
| if path != "Cargo.toml" and not path.endswith("/Cargo.toml"): | |
| continue | |
| try: | |
| name = tomllib.loads(text).get("package", {}).get("name") | |
| except (tomllib.TOMLDecodeError, AttributeError): | |
| continue | |
| if isinstance(name, str): | |
| packages.append((posixpath.dirname(path), name.replace("-", "_"))) | |
| return tuple(packages) | |
| def _elixir_modules(self) -> dict[str, tuple[str, ...]]: | |
| modules: dict[str, list[str]] = {} | |
| pattern = re.compile(r"^\s*defmodule\s+([A-Z][\w.]*)\s+do\b", re.M) | |
| for path, text in self.files.items(): | |
| if not path.endswith((".ex", ".exs")): | |
| continue | |
| for module in pattern.findall(text): | |
| modules.setdefault(module, []).append(path) | |
| return {module: tuple(paths) for module, paths in modules.items()} | |
| def _csharp_namespaces(self) -> dict[str, tuple[str, ...]]: | |
| namespaces: dict[str, list[str]] = {} | |
| pattern = re.compile(r"^\s*namespace\s+([A-Za-z_][\w.]*)", re.M) | |
| for path, text in self.files.items(): | |
| for namespace in pattern.findall(text): | |
| namespaces.setdefault(namespace, []).append(path) | |
| return {namespace: tuple(paths) for namespace, paths in namespaces.items()} | |
| def _swift_external_modules(self) -> frozenset[str]: | |
| modules = { | |
| "AppKit", "AVFoundation", "Combine", "Compression", "CoreData", | |
| "CoreFoundation", "CoreGraphics", "CoreImage", "CoreLocation", | |
| "CoreText", "CryptoKit", "Darwin", "Dispatch", "Foundation", | |
| "FoundationNetworking", "FoundationXML", "ImageIO", "IOKit", "MapKit", | |
| "Metal", "Network", "ObjectiveC", "Observation", "OSLog", | |
| "PackageDescription", "Security", "StoreKit", "SwiftUI", "SystemConfiguration", | |
| "UIKit", "UniformTypeIdentifiers", "Vision", "WebKit", "XCTest", | |
| } | |
| for path, text in self.files.items(): | |
| if posixpath.basename(path) != "Package.swift": | |
| continue | |
| modules.update(re.findall(r"\.product\s*\(\s*name\s*:\s*\"([^\"]+)\"", text)) | |
| return frozenset(modules) | |
| def _variants(base: str, language: str | None) -> list[str]: | |
| extensions = { | |
| "python": (".py",), | |
| "javascript": (".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".json", ".vue"), | |
| "typescript": (".ts", ".tsx", ".js", ".jsx", ".d.ts", ".json", ".vue"), | |
| "go": (".go",), "java": (".java",), "c": (".h", ".c"), | |
| "cpp": (".h", ".hpp", ".hh", ".cpp", ".cc", ".cxx"), | |
| "csharp": (".cs",), "rust": (".rs",), | |
| "vue": (".vue", ".js", ".ts"), | |
| "elixir": (".ex", ".exs"), "ruby": (".rb",), | |
| "kotlin": (".kt", ".kts"), "swift": (".swift",), | |
| }.get(language or "", ("",)) | |
| values = [base] | |
| values.extend(base + extension for extension in extensions) | |
| indexes = { | |
| "python": ("__init__.py",), | |
| "javascript": ("index.js", "index.jsx", "index.ts", "index.tsx", "index.vue"), | |
| "typescript": ("index.ts", "index.tsx", "index.js", "index.jsx", "index.vue"), | |
| "vue": ("index.vue", "index.js", "index.ts"), | |
| "rust": ("mod.rs",), | |
| }.get(language or "", ()) | |
| values.extend(posixpath.join(base, index) for index in indexes) | |
| return _unique(values) | |
| def _match_bases(self, bases: list[str], language: str | None) -> list[str]: | |
| variants = _unique(variant for base in bases | |
| for variant in self._variants(base.strip("/"), language)) | |
| exact = [path for path in variants if path in self.paths] | |
| if exact: | |
| return _unique(exact) | |
| # Covers conventional roots such as src/main/java and packages nested | |
| # in a monorepo. Multiple suffix matches remain ambiguous. | |
| return _unique(path for variant in variants if variant | |
| for path in self.suffix_paths.get(variant, ())) | |
| def _match_exact_bases(self, bases: list[str], language: str | None) -> list[str]: | |
| variants = _unique(variant for base in bases | |
| for variant in self._variants(base.strip("/"), language)) | |
| return [path for path in variants if path in self.paths] | |
| def _python(self, source: str, name: str) -> tuple[list[str], bool, str]: | |
| leading = len(name) - len(name.lstrip(".")) | |
| module = name.lstrip(".").replace(".", "/") | |
| if leading: | |
| directory = posixpath.dirname(source) | |
| for _ in range(max(0, leading - 1)): | |
| directory = posixpath.dirname(directory) | |
| bases = [posixpath.normpath(posixpath.join(directory, module))] | |
| matches = self._match_exact_bases(bases, "python") | |
| while not matches and "/" in module: | |
| module = module.rsplit("/", 1)[0] | |
| bases = [posixpath.normpath(posixpath.join(directory, module))] | |
| matches = self._match_exact_bases(bases, "python") | |
| return matches, False, "python-relative" | |
| roots = list(self.python_roots) | |
| source_directory = posixpath.dirname(source) | |
| if source_directory: | |
| roots.append(source_directory) | |
| bases = [posixpath.join(root, module) if root else module for root in roots] | |
| matches = self._match_exact_bases(bases, "python") | |
| # ``from pkg.module import Symbol`` and ``from pkg import module`` have | |
| # the same syntax. Prefer the fully qualified path, then progressively | |
| # fall back to the containing module. | |
| while not matches and "/" in module: | |
| module = module.rsplit("/", 1)[0] | |
| bases = [posixpath.join(root, module) if root else module for root in roots] | |
| matches = self._match_exact_bases(bases, "python") | |
| return matches, not matches, "python-module" | |
| def _go(self, name: str) -> tuple[list[str], bool, str]: | |
| if not self.go_module or not (name == self.go_module or name.startswith(self.go_module + "/")): | |
| return [], True, "go-external-package" | |
| package = name[len(self.go_module):].strip("/") | |
| matches = sorted(path for path in self.paths | |
| if posixpath.dirname(path) == package | |
| and path.endswith(".go") and not path.endswith("_test.go")) | |
| return matches, False, "go-package" | |
| def _js(self, source: str, name: str, language: str) -> tuple[list[str], bool, str]: | |
| if name.startswith("."): | |
| base = posixpath.normpath(posixpath.join(posixpath.dirname(source), name)) | |
| return self._match_bases([base], language), False, "js-relative" | |
| bases: list[str] = [] | |
| for pattern, targets in self.js_aliases: | |
| if "*" in pattern and name.startswith(pattern.split("*", 1)[0]): | |
| wildcard = name[len(pattern.split("*", 1)[0]):] | |
| bases.extend(target.replace("*", wildcard).strip("./") for target in targets) | |
| elif name == pattern: | |
| bases.extend(target.strip("./") for target in targets) | |
| if self.js_package and (name == self.js_package or name.startswith(self.js_package + "/")): | |
| name = name[len(self.js_package):].lstrip("/") | |
| bases.extend(posixpath.join(root, name) if root else name for root in self.js_base_urls) | |
| if bases: | |
| return self._match_bases(bases, language), False, "js-alias" | |
| return [], True, "js-package" | |
| def _rust(self, source: str, name: str) -> tuple[list[str], bool, str]: | |
| clean = name.rstrip(":") | |
| source_directory = posixpath.dirname(source) | |
| if "::" not in clean: | |
| local = self._match_exact_bases( | |
| [posixpath.join(source_directory, clean)], "rust" | |
| ) | |
| if local: | |
| return local, False, "rust-local-module" | |
| if clean.split("::", 1)[0] in {"std", "core", "alloc", "proc_macro"}: | |
| return [], True, "rust-standard-crate" | |
| if not clean.startswith(("crate::", "self::", "super::", "::")): | |
| root_parts = [part for part in clean.split("::") if part] | |
| while root_parts: | |
| root_module = self._match_exact_bases( | |
| [posixpath.join("src", *root_parts)], "rust" | |
| ) | |
| if root_module: | |
| return root_module, False, "rust-root-module" | |
| root_parts.pop() | |
| cargo_directory = "" | |
| package_name = None | |
| for directory, package in sorted(self.rust_packages, key=lambda item: len(item[0]), reverse=True): | |
| if not directory or source == directory or source.startswith(directory + "/"): | |
| cargo_directory, package_name = directory, package | |
| break | |
| source_root = posixpath.join(cargo_directory, "src") if cargo_directory else "src" | |
| relative = source[len(source_root):].lstrip("/") if source.startswith(source_root + "/") else source | |
| if posixpath.basename(relative) in {"lib.rs", "main.rs", "mod.rs"}: | |
| module_parts = posixpath.dirname(relative).split("/") if posixpath.dirname(relative) else [] | |
| else: | |
| module_parts = relative.rsplit(".", 1)[0].split("/") | |
| parts = [part for part in clean.split("::") if part] | |
| external = False | |
| referenced_package = next( | |
| ((directory, package) for directory, package in self.rust_packages | |
| if parts and parts[0] == package), | |
| None, | |
| ) | |
| if referenced_package is not None: | |
| target_directory, _ = referenced_package | |
| parts.pop(0) | |
| target_root = posixpath.join(target_directory, "src") if target_directory else "src" | |
| combined = list(parts) | |
| while combined: | |
| matches = self._match_exact_bases( | |
| [posixpath.join(target_root, *combined)], "rust" | |
| ) | |
| if matches: | |
| return matches, False, "rust-workspace-crate" | |
| combined.pop() | |
| matches = self._match_exact_bases([posixpath.join(target_root, "lib")], "rust") | |
| return matches, False, "rust-workspace-crate-root" | |
| if parts and parts[0] == "crate": | |
| parts.pop(0) | |
| base_parts: list[str] = [] | |
| elif parts and parts[0] == "self": | |
| parts.pop(0) | |
| base_parts = module_parts | |
| elif parts and parts[0] == "super": | |
| base_parts = module_parts | |
| while parts and parts[0] == "super": | |
| parts.pop(0) | |
| if base_parts: | |
| base_parts.pop() | |
| else: | |
| # Bare names are also used by ``mod child``. Try a child of the | |
| # current module before classifying the first segment as a crate. | |
| local = self._match_bases( | |
| [posixpath.join(source_root, *(module_parts + parts))], "rust" | |
| ) | |
| if local: | |
| return local, False, "rust-child-module" | |
| return [], True, "rust-external-crate" | |
| combined = base_parts + parts | |
| while combined: | |
| base = posixpath.join(source_root, *combined) | |
| matches = self._match_bases([base], "rust") | |
| if matches: | |
| return matches, False, "rust-module" | |
| combined.pop() | |
| if package_name and not base_parts: | |
| matches = self._match_bases([posixpath.join(source_root, "lib")], "rust") | |
| if matches: | |
| return matches, False, "rust-crate-root" | |
| # ``use super::Type`` can refer to an item declared in the parent | |
| # module file rather than to a child module named Type. | |
| parent = posixpath.join(source_root, *base_parts) | |
| matches = self._match_bases([parent], "rust") if base_parts else [] | |
| return matches, external, "rust-parent-module" | |
| def _elixir(self, name: str) -> tuple[list[str], bool, str]: | |
| matches = list(self.elixir_modules.get(name, ())) | |
| return matches, not matches, "elixir-defmodule" | |
| def _csharp(self, name: str) -> tuple[list[str], bool, str]: | |
| # ``using System...`` and common framework namespaces are external; | |
| # repository declarations are resolved conservatively by namespace. | |
| if name == "System" or name.startswith(("System.", "Microsoft.Extensions.", "Microsoft.AspNetCore.")): | |
| return [], True, "csharp-external-namespace" | |
| matches = list(self.csharp_namespaces.get(name, ())) | |
| if matches: | |
| return matches, False, "csharp-namespace" | |
| return [], False, "csharp-namespace" | |
| def _swift(self, source: str, name: str) -> tuple[list[str], bool, str]: | |
| root = name.split(".", 1)[0] | |
| if root in self.swift_external_modules: | |
| return [], True, "swift-external-module" | |
| return self._generic(source, name, "swift") | |
| def _generic(self, source: str, name: str, language: str | None) -> tuple[list[str], bool, str]: | |
| clean = name.strip("'\";") | |
| if language == "java" and clean.endswith("."): | |
| package = clean.rstrip(".").replace(".", "/") + "/" | |
| matches = sorted(path for path in self.paths | |
| if path.endswith(".java") | |
| and (path.startswith(package) or f"/{package}" in path)) | |
| return matches, False, "java-wildcard-package" | |
| if language == "go" and self.go_module and clean.startswith(self.go_module): | |
| clean = clean[len(self.go_module):].lstrip("/") | |
| elif language == "rust": | |
| clean = clean.replace("crate::", "").replace("self::", "").replace("::", "/") | |
| elif language in {"c", "cpp"}: | |
| pass | |
| else: | |
| clean = clean.replace(".", "/") if "/" not in clean else clean | |
| bases = [clean, posixpath.normpath(posixpath.join(posixpath.dirname(source), clean))] | |
| matches = self._match_bases(bases, language) | |
| go_package = False | |
| if language == "go" and not matches: | |
| package_dir = clean.rstrip("/") + "/" | |
| matches = sorted(path for path in self.paths | |
| if path.startswith(package_dir) and path.endswith(".go") and not path.endswith("_test.go")) | |
| go_package = bool(matches) | |
| if language in {"java", "rust"}: | |
| # Imports often end in a class, method or symbol. Walk toward the | |
| # containing class/module until a repository path is found. | |
| separator = "/" | |
| while not matches and separator in clean: | |
| clean = clean.rsplit(separator, 1)[0] | |
| matches = self._match_bases( | |
| [clean, posixpath.normpath(posixpath.join(posixpath.dirname(source), clean))], | |
| language, | |
| ) | |
| external = not matches and ( | |
| (language == "go" and (not self.go_module or not name.startswith(self.go_module))) or | |
| (language == "java" and name.startswith(("java.", "javax.", "jakarta."))) or | |
| (language in {"c", "cpp"} and not name.startswith(".")) or | |
| (language == "rust" and not name.startswith(("crate::", "self::", "super::"))) | |
| ) | |
| evidence = ("go-package" if go_package else | |
| "c-include-candidates" if language in {"c", "cpp"} else | |
| "path-match") | |
| return matches, external, evidence | |
| def resolve(self, source: str, name: str, language: str | None) -> Resolution: | |
| if language == "python": | |
| matches, external, evidence = self._python(source, name) | |
| elif language in {"javascript", "typescript"}: | |
| matches, external, evidence = self._js(source, name, language) | |
| elif language == "rust": | |
| matches, external, evidence = self._rust(source, name) | |
| elif language == "elixir": | |
| matches, external, evidence = self._elixir(name) | |
| elif language == "csharp": | |
| matches, external, evidence = self._csharp(name) | |
| elif language == "swift": | |
| matches, external, evidence = self._swift(source, name) | |
| elif language == "go": | |
| matches, external, evidence = self._go(name) | |
| else: | |
| matches, external, evidence = self._generic(source, name, language) | |
| matches = [path for path in matches if path != source] | |
| if len(matches) == 1: | |
| return Resolution("internal", matches[0], tuple(matches), .98, evidence) | |
| if len(matches) > 1: | |
| candidates = (matches if evidence in {"java-wildcard-package", "go-package", | |
| "c-include-candidates"} | |
| else matches[:16]) | |
| return Resolution("ambiguous", None, tuple(candidates), .45, evidence) | |
| if external: | |
| return Resolution("external", None, (), .95, evidence) | |
| return Resolution("unresolved", None, (), 0.0, evidence) | |