Spaces:
Running
Running
File size: 10,144 Bytes
8800c81 ccd47e0 8800c81 ccd47e0 8800c81 ccd47e0 8800c81 ccd47e0 8800c81 ccd47e0 8800c81 ccd47e0 8800c81 19c5296 8800c81 ccd47e0 8800c81 19c5296 8800c81 19c5296 8800c81 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | #!/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()
|