Spaces:
Running
Running
Download scripts/quality_gate.py from iamfebin/algospaced-dsa: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/scripts/quality_gate.py
- Command line
-
hf download hf://spaces/iamfebin/algospaced-dsa/scripts/quality_gate.py
-
curl -L -o quality_gate.py https://huggingface.co/spaces/iamfebin/algospaced-dsa/resolve/main/scripts/quality_gate.py
10.1 kB
| #!/usr/bin/env python3 | |
| """ | |
| AlgoSpaced-DSA-Review — Pre-Flight Automated Quality Gate Runner | |
| Executes comprehensive pre-flight verification: | |
| 1. Secret & Credential Hygiene Scan | |
| 2. Backend Python Lint (ruff) | |
| 3. Frontend TypeScript Compilation & Vite Production Bundle (npm run build) | |
| Exit codes: | |
| 0 - All gates passed cleanly. Ready for merge/deployment. | |
| 1 - One or more quality gates failed. | |
| """ | |
| import re | |
| import subprocess | |
| import sys | |
| import time | |
| from pathlib import Path | |
| # ANSI Color codes for formatted terminal output | |
| RESET = "\033[0m" | |
| BOLD = "\033[1m" | |
| GREEN = "\033[32m" | |
| RED = "\033[31m" | |
| YELLOW = "\033[33m" | |
| CYAN = "\033[36m" | |
| GRAY = "\033[90m" | |
| WORKSPACE_ROOT = Path(__file__).resolve().parent.parent | |
| FRONTEND_DIR = WORKSPACE_ROOT / "algospaced-ui" | |
| FORBIDDEN_FILE_PATTERNS = [ | |
| re.compile(r".*firebase-credentials.*\.json$", re.IGNORECASE), | |
| re.compile(r".*gcp-credentials.*\.json$", re.IGNORECASE), | |
| re.compile(r".*serviceAccount.*\.json$", re.IGNORECASE), | |
| re.compile(r"^\.env(\.local)?$", re.IGNORECASE), | |
| ] | |
| FORBIDDEN_CONTENT_PATTERNS = [ | |
| re.compile(r"-----BEGIN\s+(RSA|EC|DSA|OPENSSH|ENCRYPTED)?\s*PRIVATE KEY-----"), | |
| re.compile(r"AIzaSy[0-9A-Za-z\-_]{33}"), | |
| ] | |
| def print_header(): | |
| print(f"\n{BOLD}{CYAN}{'=' * 65}{RESET}") | |
| print(f"{BOLD}{CYAN} AlgoSpaced-DSA-Review — Pre-Flight CI Quality Gate{RESET}") | |
| print(f"{BOLD}{CYAN}{'=' * 65}{RESET}\n") | |
| def gate_secret_hygiene() -> tuple[bool, str]: | |
| """Scans git status and staged diffs to prevent accidental secret leaks.""" | |
| start_time = time.time() | |
| try: | |
| # Check tracked / staged / untracked files from git status | |
| res = subprocess.run( | |
| ["git", "status", "--porcelain"], | |
| cwd=WORKSPACE_ROOT, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| check=False, | |
| ) | |
| if res.returncode != 0: | |
| return False, f"Failed to inspect git status: {res.stderr.strip()}" | |
| violations = [] | |
| for line in res.stdout.splitlines(): | |
| if not line.strip(): | |
| continue | |
| status_code = line[:2] | |
| filepath = line[3:].strip().replace('"', "") | |
| # Check filename against forbidden patterns | |
| for pat in FORBIDDEN_FILE_PATTERNS: | |
| if pat.search(filepath): | |
| # Exclude sample templates | |
| if "example" in filepath.lower() or "template" in filepath.lower(): | |
| continue | |
| # Flag if staged or tracked (status codes like 'A', 'M', 'R', 'C') | |
| if any(c in status_code for c in ["A", "M", "R", "C"]): | |
| violations.append(f"Forbidden sensitive file staged in git: {filepath}") | |
| # Check git staged diff for private key strings | |
| diff_res = subprocess.run( | |
| ["git", "diff", "--cached"], | |
| cwd=WORKSPACE_ROOT, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| check=False, | |
| ) | |
| if diff_res.returncode == 0 and diff_res.stdout: | |
| added_lines = [ | |
| line | |
| for line in diff_res.stdout.splitlines() | |
| if line.startswith("+") and not line.startswith("+++") | |
| ] | |
| for pat in FORBIDDEN_CONTENT_PATTERNS: | |
| for line in added_lines: | |
| if pat.search(line): | |
| violations.append("Staged diff introduces raw private key or unmasked API credentials!") | |
| break | |
| duration = time.time() - start_time | |
| if violations: | |
| msg = "\n".join(f" • {v}" for v in violations) | |
| return False, f"Secret leak detected ({duration:.2f}s):\n{msg}" | |
| return True, f"Clean (0 secrets staged, {duration:.2f}s)" | |
| except FileNotFoundError: | |
| return False, "Git executable not found in PATH" | |
| except Exception as e: | |
| return False, f"Secret check failed with exception: {e}" | |
| def gate_backend_lint() -> tuple[bool, str]: | |
| """Runs ruff check across backend Python modules.""" | |
| start_time = time.time() | |
| try: | |
| cmd = ["uv", "run", "ruff", "check", "."] | |
| res = subprocess.run( | |
| cmd, | |
| cwd=WORKSPACE_ROOT, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| check=False, | |
| ) | |
| duration = time.time() - start_time | |
| if res.returncode == 0: | |
| return True, f"Passed with 0 errors ({duration:.2f}s)" | |
| err_output = (res.stdout + "\n" + res.stderr).strip() | |
| return False, f"Ruff linter failed ({duration:.2f}s):\n{err_output}" | |
| except FileNotFoundError: | |
| return False, "uv executable not found in PATH. Ensure uv is installed." | |
| except Exception as e: | |
| return False, f"Backend lint error: {e}" | |
| def gate_backend_tests() -> tuple[bool, str]: | |
| """Runs automated unit and integration tests via pytest.""" | |
| start_time = time.time() | |
| try: | |
| cmd = ["uv", "run", "pytest", "tests", "-q"] | |
| res = subprocess.run( | |
| cmd, | |
| cwd=WORKSPACE_ROOT, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| check=False, | |
| ) | |
| duration = time.time() - start_time | |
| if res.returncode == 0: | |
| output_lines = [line.strip() for line in res.stdout.splitlines() if line.strip()] | |
| summary = output_lines[-1] if output_lines else "All tests passed" | |
| return True, f"{summary} ({duration:.2f}s)" | |
| err_output = (res.stdout + "\n" + res.stderr).strip() | |
| lines = err_output.splitlines() | |
| if len(lines) > 25: | |
| err_output = "\n".join(lines[-25:]) | |
| return False, f"Test suite failed ({duration:.2f}s):\n{err_output}" | |
| except FileNotFoundError: | |
| return False, "uv executable not found in PATH. Ensure uv is installed." | |
| except Exception as e: | |
| return False, f"Backend test error: {e}" | |
| def gate_frontend_typecheck() -> tuple[bool, str]: | |
| """Runs strict TypeScript compilation typecheck in algospaced-ui.""" | |
| start_time = time.time() | |
| if not FRONTEND_DIR.exists(): | |
| return False, f"Frontend directory not found at {FRONTEND_DIR}" | |
| try: | |
| # Use npm.cmd on Windows, npm on POSIX | |
| npm_bin = "npm.cmd" if sys.platform == "win32" else "npm" | |
| cmd = [npm_bin, "run", "typecheck"] | |
| res = subprocess.run( | |
| cmd, | |
| cwd=FRONTEND_DIR, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| check=False, | |
| ) | |
| duration = time.time() - start_time | |
| if res.returncode == 0: | |
| return True, f"Strict typecheck passed with 0 errors ({duration:.2f}s)" | |
| err_output = (res.stdout + "\n" + res.stderr).strip() | |
| lines = err_output.splitlines() | |
| if len(lines) > 25: | |
| err_output = "\n".join(lines[-25:]) | |
| return False, f"Frontend TypeScript typecheck failed ({duration:.2f}s):\n{err_output}" | |
| except FileNotFoundError: | |
| return False, "npm executable not found in PATH. Ensure Node.js is installed." | |
| except Exception as e: | |
| return False, f"Frontend typecheck error: {e}" | |
| def gate_frontend_build() -> tuple[bool, str]: | |
| """Runs TypeScript typecheck and Vite production build in algospaced-ui.""" | |
| start_time = time.time() | |
| if not FRONTEND_DIR.exists(): | |
| return False, f"Frontend directory not found at {FRONTEND_DIR}" | |
| try: | |
| # Use npm.cmd on Windows, npm on POSIX | |
| npm_bin = "npm.cmd" if sys.platform == "win32" else "npm" | |
| cmd = [npm_bin, "run", "build"] | |
| res = subprocess.run( | |
| cmd, | |
| cwd=FRONTEND_DIR, | |
| capture_output=True, | |
| text=True, | |
| encoding="utf-8", | |
| errors="replace", | |
| check=False, | |
| ) | |
| duration = time.time() - start_time | |
| if res.returncode == 0: | |
| return True, f"Clean build & bundle ({duration:.2f}s)" | |
| err_output = (res.stdout + "\n" + res.stderr).strip() | |
| # Truncate if error output is overwhelmingly verbose | |
| lines = err_output.splitlines() | |
| if len(lines) > 25: | |
| err_output = "\n".join(lines[-25:]) | |
| return False, f"Frontend build failed ({duration:.2f}s):\n{err_output}" | |
| except FileNotFoundError: | |
| return False, "npm executable not found in PATH. Ensure Node.js is installed." | |
| except Exception as e: | |
| return False, f"Frontend build error: {e}" | |
| def main(): | |
| print_header() | |
| gates = [ | |
| ("Gate 1: Secret & Credential Hygiene", gate_secret_hygiene), | |
| ("Gate 2: Backend Python Lint (Ruff)", gate_backend_lint), | |
| ("Gate 3: Backend Automated Tests (Pytest)", gate_backend_tests), | |
| ("Gate 4: Frontend TypeScript Typecheck", gate_frontend_typecheck), | |
| ("Gate 5: Frontend Production Bundle Build", gate_frontend_build), | |
| ] | |
| all_passed = True | |
| results = [] | |
| for name, gate_func in gates: | |
| sys.stdout.write(f" {GRAY}[RUNNING]{RESET} {name} ...\r") | |
| sys.stdout.flush() | |
| passed, detail = gate_func() | |
| results.append((name, passed, detail)) | |
| if passed: | |
| print(f" {GREEN}{BOLD}[PASS]{RESET} {BOLD}{name}{RESET}: {detail}") | |
| else: | |
| print(f" {RED}{BOLD}[FAIL]{RESET} {BOLD}{name}{RESET}: {detail}") | |
| all_passed = False | |
| print(f"\n{BOLD}{CYAN}{'-' * 65}{RESET}") | |
| if all_passed: | |
| print(f"{BOLD}{GREEN} >>> SUCCESS: ALL QUALITY GATES PASSED! CODE IS READY TO SHIP. <<<{RESET}") | |
| print(f"{BOLD}{CYAN}{'=' * 65}{RESET}\n") | |
| sys.exit(0) | |
| else: | |
| print(f"{BOLD}{RED} >>> FAILED: ONE OR MORE QUALITY GATES FAILED. FIX ERRORS ABOVE. <<<{RESET}") | |
| print(f"{BOLD}{CYAN}{'=' * 65}{RESET}\n") | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() | |