Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /promptdriven_pdd /context /agentic_langtest_example.py
| # pdd/agentic_langtest.py | |
| from __future__ import annotations | |
| import os | |
| import shutil | |
| import sys | |
| from pathlib import Path | |
| def _which(cmd: str) -> bool: | |
| """Checks if a command-line tool exists in the system's PATH. | |
| Args: | |
| cmd: The name of the command to check (e.g., "npm", "mvn"). | |
| Returns: | |
| True if the command is found, False otherwise. | |
| """ | |
| return shutil.which(cmd) is not None | |
| def _find_project_root(start_path: str) -> Path: | |
| """Finds the project root by searching upwards for common project files. | |
| Starting from `start_path`, it traverses up the directory tree looking for | |
| marker files like `build.gradle`, `pom.xml`, or `package.json`. | |
| Args: | |
| start_path: The file or directory path to start the search from. | |
| Returns: | |
| The resolved Path to the project root directory. If no marker is found, | |
| it returns the parent of the starting path's resolved directory. | |
| """ | |
| p = Path(start_path).resolve() | |
| while p != p.parent: | |
| if any((p / f).exists() for f in [ | |
| "build.gradle", | |
| "build.gradle.kts", | |
| "pom.xml", | |
| "package.json", | |
| "jest.config.js", | |
| ]): | |
| return p | |
| p = p.parent | |
| return Path(start_path).resolve().parent | |
| def default_verify_cmd_for(lang: str, unit_test_file: str) -> str | None: | |
| """Generates a default shell command to compile and run tests for a language. | |
| This function provides a conservative, best-effort command that should work | |
| in common project setups. The command is designed to be run with `bash -lc`. | |
| Args: | |
| lang: The programming language (e.g., "python", "javascript", "java"). | |
| unit_test_file: The absolute or relative path to the test file. | |
| Returns: | |
| A shell command string to execute the tests, or None if the language | |
| is not supported or a build system cannot be detected. | |
| """ | |
| test_rel = unit_test_file | |
| lang = lang.lower() | |
| if lang == "python": | |
| return f'{sys.executable} -m pytest "{test_rel}" -q' | |
| if lang == "javascript" or lang == "typescript": | |
| example_dir = str(_find_project_root(unit_test_file)) | |
| rel_test_path = os.path.relpath(unit_test_file, example_dir) | |
| return ( | |
| "set -e\n" | |
| f'cd "{example_dir}" && ' | |
| "command -v npm >/dev/null 2>&1 || { echo 'npm missing'; exit 127; } && " | |
| "if [ -f package.json ]; then " | |
| " npm install && npm test; " | |
| "else " | |
| f' echo "No package.json in {example_dir}; running test file directly"; ' | |
| f' node -e "try {{ require(\'./{rel_test_path}\'); }} catch (e) {{ console.error(e); process.exit(1); }}"; ' | |
| "fi" | |
| ) | |
| if lang == "java": | |
| root_dir = str(_find_project_root(unit_test_file)) | |
| # Prefer Maven if pom.xml is present | |
| if "pom.xml" in os.listdir(root_dir): | |
| return f"cd '{root_dir}' && mvn test" | |
| # Gradle builds | |
| elif "build.gradle" in os.listdir(root_dir) or "build.gradle.kts" in os.listdir(root_dir): | |
| if "gradlew" in os.listdir(root_dir): | |
| return f"cd '{root_dir}' && ./gradlew test" | |
| else: | |
| # Fixed incorrect quoting/backtick usage: use cd and run gradle | |
| return f"cd '{root_dir}' && gradle test" | |
| else: | |
| return None | |
| return None | |
| def missing_tool_hints(lang: str, verify_cmd: str | None, project_root: Path) -> str | None: | |
| """Checks for missing toolchains and returns helpful installation hints. | |
| This function inspects the environment and the generated verification command | |
| to identify missing dependencies (like npm, javac, etc.) and provides | |
| user-friendly, colored installation instructions for common platforms. | |
| Args: | |
| lang: The programming language. | |
| verify_cmd: The verification command generated by `default_verify_cmd_for`. | |
| project_root: The root directory of the project being tested. | |
| Returns: | |
| A formatted string with installation hints if tools are missing, | |
| otherwise None. | |
| """ | |
| if not verify_cmd: | |
| return None | |
| need = [] | |
| if lang in ("typescript", "javascript"): | |
| if not _which("npm"): | |
| need.append("npm (Node.js)") | |
| if lang == "java": | |
| if not _which("javac") or not _which("java"): | |
| need.append("Java JDK (javac, java)") | |
| jar_present = any( | |
| p.name.endswith(".jar") and "junit" in p.name.lower() and "console" in p.name.lower() | |
| for p in project_root.glob("*.jar") | |
| ) | |
| if not jar_present: | |
| need.append("JUnit ConsoleLauncher jar (e.g. junit-platform-console-standalone.jar)") | |
| if lang == "cpp": | |
| if not _which("g++"): | |
| need.append("g++") | |
| if not need: | |
| return None | |
| install_lines = [] | |
| if "npm (Node.js)" in need: | |
| install_lines += [ | |
| "macOS: brew install node", | |
| "Ubuntu: sudo apt-get update && sudo apt-get install -y nodejs npm", | |
| ] | |
| if "Java JDK (javac, java)" in need: | |
| install_lines += [ | |
| "macOS: brew install openjdk", | |
| "Ubuntu: sudo apt-get update && sudo apt-get install -y openjdk-17-jdk", | |
| ] | |
| if "JUnit ConsoleLauncher jar (e.g. junit-platform-console-standalone.jar)" in need: | |
| install_lines += [ | |
| "Download the ConsoleLauncher jar from Maven Central and place it in your project root, e.g:", | |
| " curl -LO https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console-standalone/1.10.2/junit-platform-console-standalone-1.10.2.jar", | |
| ] | |
| if "g++" in need: | |
| install_lines += [ | |
| "macOS: xcode-select --install # or: brew install gcc", | |
| "Ubuntu: sudo apt-get update && sudo apt-get install -y build-essential", | |
| ] | |
| return ( | |
| "[yellow]Some tools required to run non-Python tests seem missing.[/yellow]\n - " | |
| + "\n - ".join(need) | |
| + "\n[dim]Suggested installs:\n " | |
| + "\n ".join(install_lines) | |
| + "[/dim]" | |
| ) | |
| # example.py | |
| import tempfile | |
| from pathlib import Path | |
| from rich import print as rprint | |
| from rich.panel import Panel | |
| # Assume the module above is in pdd/agentic_langtest.py | |
| # and your current directory is the parent of 'pdd'. | |
| from pdd.agentic_langtest import default_verify_cmd_for, missing_tool_hints | |
| def demonstrate_js_project(root: Path): | |
| """ | |
| Sets up a mock JS project and demonstrates the module's functions. | |
| """ | |
| rprint(Panel("[bold cyan]Demonstrating with a JavaScript Project[/bold cyan]")) | |
| # 1. Create a mock project structure with a package.json file. | |
| # The `_find_project_root` helper will use this file as a marker. | |
| (root / "package.json").write_text( | |
| """{ | |
| "name": "my-project", | |
| "scripts": { "test": "echo 'JS tests would run here' && exit 0" } | |
| }""", | |
| encoding="utf-8", | |
| ) | |
| test_file = root / "src" / "app.test.js" | |
| test_file.parent.mkdir() | |
| test_file.touch() | |
| print(f"Created a temporary JS project at: {root}") | |
| print(f"Test file is at: {test_file}\n") | |
| # 2. Generate the default verification command for JavaScript. | |
| # The function will find the project root and generate an `npm` command. | |
| lang = "javascript" | |
| verify_cmd = default_verify_cmd_for(lang, str(test_file)) | |
| rprint(Panel( | |
| f"[bold]Generated Command:[/bold]\n{verify_cmd}", | |
| title="[green]default_verify_cmd_for Result[/green]", | |
| border_style="green", | |
| )) | |
| # 3. Check for missing tools (like npm) and get installation hints. | |
| # The output will depend on whether 'npm' is installed on your system. | |
| hints = missing_tool_hints(lang, verify_cmd, root) | |
| if hints: | |
| rprint(Panel( | |
| hints, | |
| title="[yellow]missing_tool_hints Result[/yellow]", | |
| border_style="yellow", | |
| )) | |
| else: | |
| rprint(Panel( | |
| "No missing tools detected. 'npm' is likely installed.", | |
| title="[green]missing_tool_hints Result[/green]", | |
| border_style="green", | |
| )) | |
| def demonstrate_python_project(root: Path): | |
| """ | |
| Shows a simpler case for a Python test file. | |
| """ | |
| rprint(Panel("\n[bold cyan]Demonstrating with a Python Project[/bold cyan]")) | |
| test_file = root / "test_simple.py" | |
| test_file.touch() | |
| print(f"Created a temporary Python test file at: {test_file}\n") | |
| # Generate the command for Python. | |
| lang = "python" | |
| verify_cmd = default_verify_cmd_for(lang, str(test_file)) | |
| rprint(Panel( | |
| f"[bold]Generated Command:[/bold]\n{verify_cmd}", | |
| title="[green]default_verify_cmd_for Result[/green]", | |
| border_style="green", | |
| )) | |
| def main(): | |
| """ | |
| Main function to run the demonstrations in a temporary directory. | |
| """ | |
| with tempfile.TemporaryDirectory() as tmpdir: | |
| project_root = Path(tmpdir) | |
| demonstrate_js_project(project_root) | |
| demonstrate_python_project(project_root) | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 9.15 kB
- Xet hash:
- 609c0eca9e53f8f339f3561c3d55451e1f53d540a7c1126832ccd03664a7cdd3
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.