Spaces:
Running
Running
Download citadel/github_deployment_engine.py from DJ-Goanna-Coding/Oppo-TIA: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/spaces/DJ-Goanna-Coding/Oppo-TIA/resolve/main/citadel/github_deployment_engine.py
- Command line
-
hf download hf://spaces/DJ-Goanna-Coding/Oppo-TIA/citadel/github_deployment_engine.py
-
curl -L -o github_deployment_engine.py https://huggingface.co/spaces/DJ-Goanna-Coding/Oppo-TIA/resolve/main/citadel/github_deployment_engine.py
12.6 kB
| """GitHub Deployment Engine — Bidirectional code refinery and cloud deployment. | |
| Part of OMNI_DEPLOY_WIRING v22.2155: Enables TIA to push code directly to GitHub | |
| repositories and trigger automated deployments to Render, Redis, Vercel, GCP, Firebase. | |
| """ | |
| import json | |
| import logging | |
| import os | |
| import time | |
| from pathlib import Path | |
| from typing import Dict, List, Optional, Any | |
| import subprocess | |
| logger = logging.getLogger(__name__) | |
| class GitHubDeploymentEngine: | |
| """Bidirectional deployment engine for GitHub → Cloud pipeline.""" | |
| SUPPORTED_PLATFORMS = ["render", "redis", "vercel", "gcp", "firebase", "huggingface"] | |
| STABILITY_THRESHOLD = 9293 | |
| def __init__( | |
| self, | |
| github_token: Optional[str] = None, | |
| project_root: str = "/home/runner/work/Oppo-TIA/Oppo-TIA" | |
| ): | |
| """Initialize GitHub deployment engine. | |
| Args: | |
| github_token: GitHub API token for repo access | |
| project_root: Root directory of the project | |
| """ | |
| self.github_token = github_token or os.getenv("GITHUB_TOKEN") or os.getenv("GITHUB_PAT") | |
| self.project_root = Path(project_root) | |
| self.deployment_history = [] | |
| def validate_code_quality(self, code: str, file_path: str) -> Dict: | |
| """Validate code quality before deployment. | |
| Args: | |
| code: Code content to validate | |
| file_path: Target file path | |
| Returns: | |
| Validation result dict | |
| """ | |
| validation = { | |
| "valid": True, | |
| "errors": [], | |
| "warnings": [], | |
| "stability_score": 0 | |
| } | |
| # Basic syntax validation for Python files | |
| if file_path.endswith(".py"): | |
| try: | |
| compile(code, file_path, "exec") | |
| validation["stability_score"] += 3000 | |
| except SyntaxError as exc: | |
| validation["valid"] = False | |
| validation["errors"].append(f"Syntax error: {exc}") | |
| return validation | |
| # Check for security vulnerabilities | |
| security_patterns = [ | |
| ("eval(", "Dangerous eval() usage"), | |
| ("exec(", "Dangerous exec() usage"), | |
| ("__import__", "Dynamic import risk"), | |
| ("os.system", "Shell command injection risk") | |
| ] | |
| for pattern, warning in security_patterns: | |
| if pattern in code: | |
| validation["warnings"].append(warning) | |
| validation["stability_score"] -= 500 | |
| # Code quality checks | |
| if len(code.strip()) < 10: | |
| validation["warnings"].append("Code too short") | |
| validation["stability_score"] -= 1000 | |
| # Length and complexity scoring | |
| lines = code.split("\n") | |
| validation["stability_score"] += min(len(lines) * 10, 3000) | |
| # Docstring bonus | |
| if '"""' in code or "'''" in code: | |
| validation["stability_score"] += 500 | |
| # Type hints bonus | |
| if ":" in code and "->" in code: | |
| validation["stability_score"] += 500 | |
| # Import organization bonus | |
| if "import" in code[:200]: # Imports at top | |
| validation["stability_score"] += 293 | |
| # Final validation | |
| validation["stable"] = validation["stability_score"] >= self.STABILITY_THRESHOLD | |
| return validation | |
| def write_to_github_repo( | |
| self, | |
| repo_name: str, | |
| file_path: str, | |
| code_content: str, | |
| branch: str = "main", | |
| commit_message: Optional[str] = None | |
| ) -> Dict: | |
| """Write code directly to GitHub repository. | |
| Args: | |
| repo_name: Repository name (e.g., "DJ-Goanna-Coding/TIA") | |
| file_path: Target file path in repo | |
| code_content: Code to write | |
| branch: Target branch (default: main) | |
| commit_message: Commit message | |
| Returns: | |
| Write result dict | |
| """ | |
| if not self.github_token: | |
| return { | |
| "status": "FAILED", | |
| "error": "No GitHub token available" | |
| } | |
| # Validate code first | |
| validation = self.validate_code_quality(code_content, file_path) | |
| if not validation["valid"]: | |
| return { | |
| "status": "VALIDATION_FAILED", | |
| "validation": validation | |
| } | |
| if not validation["stable"]: | |
| return { | |
| "status": "UNSTABLE", | |
| "validation": validation, | |
| "message": f"Stability score {validation['stability_score']} below threshold {self.STABILITY_THRESHOLD}" | |
| } | |
| try: | |
| import requests | |
| import base64 | |
| # Get current file SHA if exists | |
| url = f"https://api.github.com/repos/{repo_name}/contents/{file_path}?ref={branch}" | |
| headers = { | |
| "Authorization": f"token {self.github_token}", | |
| "Accept": "application/vnd.github.v3+json" | |
| } | |
| sha = None | |
| response = requests.get(url, headers=headers, timeout=10) | |
| if response.status_code == 200: | |
| sha = response.json().get("sha") | |
| # Prepare commit | |
| message = commit_message or f"feat: TIA deployment to {file_path}" | |
| encoded_content = base64.b64encode(code_content.encode()).decode() | |
| payload = { | |
| "message": message, | |
| "content": encoded_content, | |
| "branch": branch | |
| } | |
| if sha: | |
| payload["sha"] = sha | |
| # Write file | |
| response = requests.put(url, headers=headers, json=payload, timeout=30) | |
| if response.status_code in [200, 201]: | |
| result = { | |
| "status": "SUCCESS", | |
| "repository": repo_name, | |
| "file_path": file_path, | |
| "branch": branch, | |
| "commit": response.json().get("commit", {}).get("sha"), | |
| "validation": validation, | |
| "timestamp": time.time() | |
| } | |
| self.deployment_history.append(result) | |
| logger.info(f"Successfully wrote {file_path} to {repo_name}") | |
| return result | |
| else: | |
| return { | |
| "status": "GITHUB_API_ERROR", | |
| "error": f"HTTP {response.status_code}: {response.text}", | |
| "repository": repo_name, | |
| "file_path": file_path | |
| } | |
| except Exception as exc: | |
| logger.error(f"Failed to write to GitHub: {exc}") | |
| return { | |
| "status": "EXCEPTION", | |
| "error": str(exc) | |
| } | |
| def trigger_deployment( | |
| self, | |
| repo_name: str, | |
| platforms: List[str], | |
| branch: str = "main" | |
| ) -> Dict: | |
| """Trigger automated deployment to cloud platforms. | |
| Args: | |
| repo_name: Repository name | |
| platforms: List of platforms to deploy to | |
| branch: Source branch | |
| Returns: | |
| Deployment trigger result | |
| """ | |
| results = { | |
| "status": "TRIGGERED", | |
| "repository": repo_name, | |
| "branch": branch, | |
| "platforms": {}, | |
| "timestamp": time.time() | |
| } | |
| for platform in platforms: | |
| if platform not in self.SUPPORTED_PLATFORMS: | |
| results["platforms"][platform] = { | |
| "status": "UNSUPPORTED", | |
| "error": f"Platform {platform} not in supported list" | |
| } | |
| continue | |
| # Trigger GitHub Actions workflow for each platform | |
| workflow_result = self._trigger_github_workflow( | |
| repo_name, | |
| f"deploy_{platform}.yml", | |
| branch | |
| ) | |
| results["platforms"][platform] = workflow_result | |
| return results | |
| def _trigger_github_workflow( | |
| self, | |
| repo_name: str, | |
| workflow_file: str, | |
| branch: str | |
| ) -> Dict: | |
| """Trigger a GitHub Actions workflow. | |
| Args: | |
| repo_name: Repository name | |
| workflow_file: Workflow filename | |
| branch: Branch to run on | |
| Returns: | |
| Workflow trigger result | |
| """ | |
| if not self.github_token: | |
| return { | |
| "status": "FAILED", | |
| "error": "No GitHub token" | |
| } | |
| try: | |
| import requests | |
| url = f"https://api.github.com/repos/{repo_name}/actions/workflows/{workflow_file}/dispatches" | |
| headers = { | |
| "Authorization": f"token {self.github_token}", | |
| "Accept": "application/vnd.github.v3+json" | |
| } | |
| payload = { | |
| "ref": branch | |
| } | |
| response = requests.post(url, headers=headers, json=payload, timeout=10) | |
| if response.status_code == 204: | |
| return { | |
| "status": "TRIGGERED", | |
| "workflow": workflow_file, | |
| "branch": branch | |
| } | |
| else: | |
| return { | |
| "status": "TRIGGER_FAILED", | |
| "error": f"HTTP {response.status_code}", | |
| "workflow": workflow_file | |
| } | |
| except Exception as exc: | |
| return { | |
| "status": "EXCEPTION", | |
| "error": str(exc), | |
| "workflow": workflow_file | |
| } | |
| def refine_and_deploy( | |
| self, | |
| repo_name: str, | |
| file_path: str, | |
| code_content: str, | |
| platforms: Optional[List[str]] = None, | |
| branch: str = "main", | |
| commit_message: Optional[str] = None | |
| ) -> Dict: | |
| """Complete refine-and-deploy pipeline. | |
| Args: | |
| repo_name: Target repository | |
| file_path: File path in repo | |
| code_content: Code to deploy | |
| platforms: Platforms to deploy to (default: all supported) | |
| branch: Target branch | |
| commit_message: Commit message | |
| Returns: | |
| Complete deployment result | |
| """ | |
| result = { | |
| "mission": "REFINE_AND_DEPLOY", | |
| "repository": repo_name, | |
| "file_path": file_path, | |
| "branch": branch, | |
| "timestamp": time.time() | |
| } | |
| # Step 1: Write code to GitHub | |
| write_result = self.write_to_github_repo( | |
| repo_name, | |
| file_path, | |
| code_content, | |
| branch, | |
| commit_message | |
| ) | |
| result["github_write"] = write_result | |
| if write_result["status"] != "SUCCESS": | |
| result["status"] = "WRITE_FAILED" | |
| return result | |
| # Step 2: Trigger deployments | |
| if platforms: | |
| deployment_result = self.trigger_deployment( | |
| repo_name, | |
| platforms, | |
| branch | |
| ) | |
| result["deployments"] = deployment_result | |
| result["status"] = "DEPLOYED" | |
| else: | |
| result["status"] = "WRITE_ONLY" | |
| return result | |
| def get_deployment_history(self, limit: int = 10) -> List[Dict]: | |
| """Get recent deployment history. | |
| Args: | |
| limit: Maximum number of records to return | |
| Returns: | |
| List of deployment records | |
| """ | |
| return self.deployment_history[-limit:] | |
| def get_status(self) -> Dict: | |
| """Get deployment engine status. | |
| Returns: | |
| Status dict | |
| """ | |
| return { | |
| "engine": "ACTIVE", | |
| "github_token_present": self.github_token is not None, | |
| "supported_platforms": self.SUPPORTED_PLATFORMS, | |
| "deployment_count": len(self.deployment_history), | |
| "stability_threshold": self.STABILITY_THRESHOLD, | |
| "project_root": str(self.project_root) | |
| } | |
| def main(): | |
| """CLI entry point for GitHub Deployment Engine.""" | |
| engine = GitHubDeploymentEngine() | |
| print(json.dumps(engine.get_status(), indent=2)) | |
| if __name__ == "__main__": | |
| main() | |