import json import re import tomllib from pathlib import Path from typing import Optional from afk_developer.grillme.spec_model import DetectedContext DETECTORS = { "language": { "Python": [ "pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "Pipfile", "poetry.lock", ], "JavaScript": ["package.json", "node_modules"], "TypeScript": ["tsconfig.json", "package.json"], "Rust": ["Cargo.toml", "Cargo.lock"], "Go": ["go.mod", "go.sum"], "Java": ["pom.xml", "build.gradle", "build.gradle.kts", "settings.gradle"], "Kotlin": ["build.gradle.kts", "settings.gradle.kts"], "CSharp": [".csproj", ".sln"], "Ruby": ["Gemfile", "Rakefile"], "Elixir": ["mix.exs"], "Zig": ["build.zig", "build.zig.zon"], }, "framework": { "React": ["package.json"], "Next.js": ["next.config.js", "next.config.mjs", "next.config.ts"], "Vue": ["vue.config.js", "nuxt.config.js"], "Svelte": ["svelte.config.js"], "Express": ["package.json"], "FastAPI": ["pyproject.toml", "requirements.txt"], "Flask": ["pyproject.toml", "requirements.txt"], "Django": ["manage.py"], }, "test_framework": { "pytest": ["pyproject.toml", "setup.cfg", "pytest.ini", "tox.ini", "conftest.py"], "unittest": ["test_*.py", "*_test.py"], "jest": ["jest.config.js", "jest.config.ts", "package.json"], "vitest": ["vitest.config.js", "vitest.config.ts", "vite.config.js"], "mocha": [".mocharc.js", ".mocharc.json"], }, "linter": { "ruff": ["pyproject.toml", "ruff.toml"], "flake8": [".flake8", "setup.cfg", "tox.ini"], "eslint": [ ".eslintrc.js", ".eslintrc.cjs", ".eslintrc.json", ".eslintrc.yaml", "eslint.config.js", ], }, "package_manager": { "pip": ["requirements.txt", "setup.py"], "poetry": ["poetry.lock"], "uv": ["uv.lock"], "npm": ["package-lock.json"], "yarn": ["yarn.lock"], "pnpm": ["pnpm-lock.yaml"], "cargo": ["Cargo.lock"], }, } IGNORED_DIRECTORY_NAMES = { ".git", ".mypy_cache", ".nox", ".pytest_cache", ".ruff_cache", ".tox", ".venv", "__pycache__", "build", "dist", "env", "node_modules", "site-packages", "venv", } def _is_ignored_path(path: Path) -> bool: return any(part in IGNORED_DIRECTORY_NAMES or part.endswith(".egg-info") for part in path.parts) def _check_files(project_dir: Path, patterns: list[str]) -> bool: for pattern in patterns: if any(project_dir.glob(pattern)): return True return False def _read_package_json(project_dir: Path) -> Optional[dict]: pkg_path = project_dir / "package.json" if not pkg_path.exists(): return None try: return json.loads(pkg_path.read_text(encoding="utf-8")) except (json.JSONDecodeError, OSError): return None def _deduce_js_test_framework(package_json: dict) -> str: deps = {**package_json.get("dependencies", {}), **package_json.get("devDependencies", {})} scripts = package_json.get("scripts", {}) test_script = scripts.get("test", "") if "vitest" in deps or "vitest" in test_script: return "vitest" if "jest" in deps or "jest" in test_script: return "jest" if "mocha" in deps or "mocha" in test_script: return "mocha" return "" def _deduce_js_framework(package_json: dict) -> str: deps = {**package_json.get("dependencies", {}), **package_json.get("devDependencies", {})} if "next" in deps: return "Next.js" if "@sveltejs/kit" in deps or "svelte" in deps: return "Svelte" if "nuxt" in deps or "vue" in deps: return "Vue" if "react" in deps: return "React" if "express" in deps: return "Express" return "" def _read_pyproject(project_dir: Path) -> Optional[dict]: pyproj = project_dir / "pyproject.toml" if not pyproj.exists(): return None try: data = tomllib.loads(pyproj.read_text(encoding="utf-8")) except (OSError, tomllib.TOMLDecodeError): return None project = data.get("project", {}) poetry = data.get("tool", {}).get("poetry", {}) dependencies = list(project.get("dependencies", [])) for optional_dependencies in project.get("optional-dependencies", {}).values(): dependencies.extend(optional_dependencies) dependencies.extend(poetry.get("dependencies", {}).keys()) dependencies.extend(poetry.get("group", {}).get("dev", {}).get("dependencies", {}).keys()) normalized_dependencies = { re.split(r"[<>=!~\[; ]", str(dependency), maxsplit=1)[0].lower() for dependency in dependencies } return {"dependencies": normalized_dependencies} def _deduce_python_framework(pyproject: dict) -> str: deps = pyproject.get("dependencies", []) if "fastapi" in deps: return "FastAPI" if "flask" in deps: return "Flask" if "django" in deps: return "Django" return "" def _deduce_python_test_framework(project_dir: Path, pyproject: dict) -> str: deps = pyproject.get("dependencies", []) if "pytest" in deps: return "pytest" if "unittest" in deps: return "unittest" test_files = list(project_dir.glob("test_*.py")) + list(project_dir.glob("*_test.py")) if test_files: return "pytest (detected from test files)" if _check_files(project_dir, ["conftest.py"]): return "pytest" return "" def _deduce_python_linter(project_dir: Path, pyproject: dict) -> str: deps = pyproject.get("dependencies", []) if "ruff" in deps: return "ruff" if "flake8" in deps: return "flake8" if "pylint" in deps: return "pylint" ruff_files = ["ruff.toml", ".ruff.toml"] if _check_files(project_dir, ruff_files): return "ruff" if _check_files(project_dir, ["pyproject.toml"]): content = (project_dir / "pyproject.toml").read_text(encoding="utf-8") if "tool.ruff" in content: return "ruff" return "" def count_files(project_dir: Path) -> int: count = 0 for entry in project_dir.rglob("*"): if entry.is_file() and not _is_ignored_path(entry): count += 1 return count def count_test_files(project_dir: Path) -> int: patterns = [ "test_*.py", "*_test.py", "*.test.js", "*.test.ts", "*.test.tsx", "*.spec.js", "*.spec.ts", "*.spec.tsx", ] test_files: set[Path] = set() for pattern in patterns: for _ in project_dir.rglob(pattern): if not _is_ignored_path(_): test_files.add(_) return len(test_files) def auto_discover_project(project_dir: Path) -> DetectedContext: ctx = DetectedContext() for lang, indicators in DETECTORS["language"].items(): if _check_files(project_dir, indicators): ctx.language = lang break for pm, indicators in DETECTORS["package_manager"].items(): if _check_files(project_dir, indicators): ctx.package_manager = pm break pkg_json = _read_package_json(project_dir) pyproj = _read_pyproject(project_dir) if pkg_json: ctx.framework = _deduce_js_framework(pkg_json) ctx.test_framework = _deduce_js_test_framework(pkg_json) if not ctx.linter and _check_files(project_dir, DETECTORS["linter"]["eslint"]): ctx.linter = "eslint" if pyproj: if not ctx.package_manager: ctx.package_manager = "pip" if not ctx.framework: ctx.framework = _deduce_python_framework(pyproj) if not ctx.test_framework: ctx.test_framework = _deduce_python_test_framework(project_dir, pyproj) if not ctx.linter: ctx.linter = _deduce_python_linter(project_dir, pyproj) if not ctx.test_framework: for tf, indicators in DETECTORS["test_framework"].items(): if _check_files(project_dir, indicators): ctx.test_framework = tf break if not ctx.linter: for linter, indicators in DETECTORS["linter"].items(): if _check_files(project_dir, indicators): ctx.linter = linter break ctx.existing_files_count = count_files(project_dir) ctx.existing_tests_count = count_test_files(project_dir) return ctx