The agent that turns websites into APIs!
fix: address PR review comments
kalil0321afe4682a8b63
diff --git a/src/reverse_api/cli.py b/src/reverse_api/cli.pyindex 4217d32..8115fa9 100644--- a/src/reverse_api/cli.py+++ b/src/reverse_api/cli.py@@ -2094,8 +2094,8 @@ def run_script(ctx, identifier, script_args, file_name, list_scripts):run_id = run["run_id"]output_dir = config_manager.get("output_dir")- # Discover scripts- scripts = discover_scripts(run_id, output_dir)+ # Discover scripts (prefer stored path from run metadata, fall back to output_dir)+ scripts = discover_scripts(run_id, output_dir, run_metadata=run)if not scripts:console.print(f"[red]No Python scripts found for run {run_id}[/red]")@@ -2145,11 +2145,12 @@ def run_script(ctx, identifier, script_args, file_name, list_scripts):venv_dir = scripts_dir / ".venv"if requirements.exists():- python_path = venv_dir / "bin" / "python"+ venv_bin = "Scripts" if sys.platform == "win32" else "bin"+ python_path = venv_dir / venv_bin / ("python.exe" if sys.platform == "win32" else "python")if not venv_dir.exists():console.print("Installing dependencies...", style="dim")subprocess.run([sys.executable, "-m", "venv", str(venv_dir)], check=True)- pip_path = venv_dir / "bin" / "pip"+ pip_path = venv_dir / venv_bin / ("pip.exe" if sys.platform == "win32" else "pip")subprocess.run([str(pip_path), "install", "-q", "-r", str(requirements)],check=True,diff --git a/src/reverse_api/utils.py b/src/reverse_api/utils.pyindex 531592e..fba9dff 100644--- a/src/reverse_api/utils.py+++ b/src/reverse_api/utils.py@@ -726,18 +726,44 @@ def resolve_run(identifier: str, session_manager) -> dict:return selected-def discover_scripts(run_id: str, output_dir: str | None = None) -> list[Path]:+def discover_scripts(run_id: str, output_dir: str | None = None, run_metadata: dict | None = None) -> list[Path]:"""Find all executable Python scripts in a run's script directory.+ Tries the stored script path from run metadata first, then falls back+ to the current output_dir config.+Args:run_id: The run identifieroutput_dir: Optional custom output directory+ run_metadata: Optional run dict with paths.script_path to resolve fromReturns:Sorted list of .py file Paths (excludes __pycache__, .venv, __init__.py)++ Raises:+ ValueError: If run_id contains invalid characters"""- base_dir = get_base_output_dir(output_dir)- scripts_dir = base_dir / "scripts" / run_id+ # Validate run_id (same rules as get_scripts_dir)+ if not run_id:+ raise ValueError("run_id cannot be empty")+ if not re.match(r"^[a-zA-Z0-9_-]+$", run_id):+ raise ValueError(f"Invalid run_id: {run_id}")+ if len(run_id) > 64:+ raise ValueError(f"run_id too long: {len(run_id)} characters (max 64)")++ # Try stored path from run metadata first+ scripts_dir = None+ if run_metadata:+ script_path = run_metadata.get("paths", {}).get("script_path", "")+ if script_path:+ stored_dir = Path(script_path).parent+ if stored_dir.exists():+ scripts_dir = stored_dir++ # Fall back to current output_dir+ if scripts_dir is None:+ base_dir = get_base_output_dir(output_dir)+ scripts_dir = base_dir / "scripts" / run_idif not scripts_dir.exists():return []@@ -749,8 +775,6 @@ def discover_scripts(run_id: str, output_dir: str | None = None) -> list[Path]:for f in scripts_dir.iterdir():if f.is_file() and f.suffix == ".py" and f.name not in exclude_files:scripts.append(f)- # Don't recurse into excluded dirs- # Also skip files inside excluded subdirs (shouldn't happen with iterdir but defensive)scripts = [s for s in scripts if not any(part in exclude_dirs for part in s.parts)]return sorted(scripts, key=lambda p: p.name)diff --git a/tests/test_run_command.py b/tests/test_run_command.pyindex ca97de7..bb432da 100644--- a/tests/test_run_command.py+++ b/tests/test_run_command.py@@ -239,6 +239,51 @@ class TestDiscoverScripts:for s in scripts:assert "__pycache__" not in str(s)+ def test_empty_run_id_raises(self):+ with pytest.raises(ValueError, match="cannot be empty"):+ discover_scripts("")++ def test_invalid_run_id_raises(self):+ with pytest.raises(ValueError, match="Invalid run_id"):+ discover_scripts("../../../etc")++ def test_too_long_run_id_raises(self):+ with pytest.raises(ValueError, match="too long"):+ discover_scripts("a" * 65)+++class TestDiscoverScriptsRunMetadata:+ """Test discover_scripts with run_metadata (stored path) fallback."""++ def test_uses_stored_path_from_metadata(self, tmp_path):+ """Prefers the stored script_path from run metadata over output_dir."""+ stored_dir = tmp_path / "old_output" / "scripts" / "run1"+ stored_dir.mkdir(parents=True)+ (stored_dir / "api_client.py").write_text("print('stored')")++ metadata = {"paths": {"script_path": str(stored_dir / "api_client.py")}}+ # output_dir points somewhere else entirely+ scripts = discover_scripts("run1", output_dir=str(tmp_path / "new_output"), run_metadata=metadata)+ assert len(scripts) == 1+ assert scripts[0].parent == stored_dir++ def test_falls_back_to_output_dir_when_stored_missing(self, tmp_path):+ """Falls back to output_dir when stored path doesn't exist."""+ fallback_dir = tmp_path / "scripts" / "run1"+ fallback_dir.mkdir(parents=True)+ (fallback_dir / "api_client.py").write_text("print('fallback')")++ metadata = {"paths": {"script_path": "/nonexistent/path/api_client.py"}}+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):+ scripts = discover_scripts("run1", run_metadata=metadata)+ assert len(scripts) == 1++ def test_falls_back_when_no_metadata(self, scripts_dir, tmp_path):+ """Works without run_metadata (backwards compatible)."""+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):+ scripts = discover_scripts("abc123def456", run_metadata=None)+ assert len(scripts) >= 1+# ---------------------------------------------------------------------------# CLI `run` command integration tests (using Click's CliRunner)