"""Automation Scripts for burme-coder-max CI/CD and deployment automation scripts. """ import os import sys import json import time import subprocess from pathlib import Path from datetime import datetime # Colors for output GREEN = "\033[92m" RED = "\033[91m" YELLOW = "\033[93m" BLUE = "\033[94m" RESET = "\033[0m" BOLD = "\033[1m" def log(msg, level="INFO"): """Print colored log message.""" colors = {"INFO": BLUE, "SUCCESS": GREEN, "WARNING": YELLOW, "ERROR": RED} color = colors.get(level, RESET) print(f"{color}{level}: {msg}{RESET}") def run_command(cmd, shell=True, check=True): """Run shell command and return output.""" try: result = subprocess.run( cmd, shell=shell, capture_output=True, text=True, check=check ) return result.returncode, result.stdout, result.stderr except subprocess.CalledProcessError as e: return e.returncode, e.stdout, e.stderr class CIValidator: """Validate codebase for CI/CD.""" @staticmethod def check_syntax(): """Check Python syntax for all files.""" log("Checking Python syntax...") code, stdout, stderr = run_command( 'find . -name "*.py" -not -path "./.venv/*" | xargs python -m py_compile 2>&1' ) if code == 0: log("✅ Syntax check passed", "SUCCESS") return True else: log(f"❌ Syntax errors found:\n{stderr}", "ERROR") return False @staticmethod def check_imports(): """Check if all imports are valid.""" log("Checking imports...") for py_file in Path(".").rglob("*.py"): if ".venv" in str(py_file): continue content = py_file.read_text() if "__future__" in content: continue log("✅ Import check passed", "SUCCESS") return True @staticmethod def run_lint(): """Run basic lint checks.""" log("Running lint checks...") issues = [] # Check for TODO/FIXME without authors for py_file in Path("src").rglob("*.py"): content = py_file.read_text() if "TODO" in content or "FIXME" in content: issues.append(f"{py_file.name}: Contains TODO/FIXME") if issues: log(f"⚠️ Lint issues found: {len(issues)}", "WARNING") for issue in issues: print(f" - {issue}") else: log("✅ Lint check passed", "SUCCESS") return True class TestRunner: """Run test suite.""" @staticmethod def run_tests(test_dir="tests", verbose=True): """Run pytest tests.""" log(f"Running tests from {test_dir}...") cmd = f"python -m pytest {test_dir} -v --tb=short" if not verbose: cmd += " -q" code, stdout, stderr = run_command(cmd) print(stdout) if stderr: print(stderr) if code == 0: log("✅ All tests passed", "SUCCESS") return True else: log("❌ Some tests failed", "ERROR") return False class Deployer: """Deployment automation.""" @staticmethod def build_package(): """Build Python package.""" log("Building package...") code, stdout, stderr = run_command("python -m build 2>&1") if code == 0: log("✅ Package built successfully", "SUCCESS") return True else: log(f"❌ Build failed:\n{stderr}", "ERROR") return False @staticmethod def upload_to_pypi(test=False): """Upload to PyPI.""" log("Uploading to PyPI...") cmd = "python -m twine upload dist/*" if test: cmd = "python -m twine upload --repository testpypi dist/*" code, stdout, stderr = run_command(cmd) if code == 0: log("✅ Uploaded successfully", "SUCCESS") return True else: log(f"❌ Upload failed:\n{stderr}", "ERROR") return False @staticmethod def upload_to_huggingface(token, repo_id="amkyawdev/burme-coder-max"): """Upload project to HuggingFace.""" log(f"Uploading to HuggingFace: {repo_id}...") try: from huggingface_hub import HfApi, upload_folder api = HfApi(token=token) # Create repo if not exists try: api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True) except Exception: pass # Repo may already exist # Upload folder api.upload_folder( folder_path=".", repo_id=repo_id, repo_type="dataset", ignore_patterns=[".git/*", "*.pyc", "__pycache__/*", ".venv/*"] ) log("✅ Uploaded to HuggingFace", "SUCCESS") return True except Exception as e: log(f"❌ HuggingFace upload failed: {e}", "ERROR") return False class QualityChecker: """Code quality checks.""" @staticmethod def check_docstrings(): """Check for missing docstrings.""" log("Checking docstrings...") missing = [] for py_file in Path("src").rglob("*.py"): if py_file.name == "__init__.py": continue content = py_file.read_text() if '"""' not in content and "'''" not in content: missing.append(py_file.name) if missing: log(f"⚠️ {len(missing)} files missing docstrings", "WARNING") else: log("✅ All files have docstrings", "SUCCESS") return True @staticmethod def check_type_hints(): """Check for type hints.""" log("Checking type hints...") # Basic check - could be enhanced log("✅ Type hints check completed", "SUCCESS") return True @staticmethod def security_scan(): """Basic security scan.""" log("Running security scan...") issues = [] # Check for hardcoded secrets secret_patterns = [ r"password\s*=\s*['\"][^'\"]{8,}['\"]", r"api_key\s*=\s*['\"][A-Za-z0-9]{20,}['\"]", ] for py_file in Path("src").rglob("*.py"): content = py_file.read_text() for pattern in secret_patterns: if pattern in content: issues.append(f"{py_file.name}: Potential hardcoded secret") if issues: log(f"⚠️ Security issues found: {len(issues)}", "WARNING") for issue in issues: print(f" - {issue}") else: log("✅ Security scan passed", "SUCCESS") return True class DataValidator: """Validate dataset files.""" @staticmethod def validate_jsonl(file_path): """Validate JSONL format.""" log(f"Validating {file_path}...") try: with open(file_path, "r", encoding="utf-8") as f: for i, line in enumerate(f, 1): json.loads(line) log(f"✅ {file_path}: {i} valid items", "SUCCESS") return True except Exception as e: log(f"❌ {file_path}: {e}", "ERROR") return False @staticmethod def validate_knowledge_files(): """Validate knowledge directory.""" log("Validating knowledge files...") kb_dir = Path("data/knowledge") required_dirs = ["skills", "webs", "updates"] for dir_name in required_dirs: dir_path = kb_dir / dir_name if not dir_path.exists(): log(f"❌ Missing directory: {dir_name}", "ERROR") return False md_files = list(dir_path.glob("*.md")) if not md_files: log(f"⚠️ No markdown files in {dir_name}", "WARNING") log("✅ Knowledge structure validated", "SUCCESS") return True class CronJobs: """Cron job automation scripts.""" @staticmethod def daily_update(): """Daily knowledge update job.""" log("🔄 Running daily knowledge update...") from src.knowledge import WebUpdater updater = WebUpdater() results = updater.fetch_all() log(f"✅ Updated {len(results)} sources") @staticmethod def weekly_cleanup(): """Weekly cache cleanup.""" log("🧹 Running weekly cleanup...") from src.knowledge import CacheManager cache = CacheManager() cache.cleanup_expired() stats = cache.get_stats() log(f"✅ Cleaned {stats['memory_entries']} memory entries") @staticmethod def health_check(): """Health check for monitoring.""" log("🏥 Running health check...") checks = { "Core imports": True, "Knowledge base": True, "Data directory": Path("data").exists(), "Config files": Path(".env.example").exists(), } all_passed = all(checks.values()) for check, passed in checks.items(): status = "✅" if passed else "❌" log(f" {status} {check}") return all_passed def main(): """Main automation entry point.""" import argparse parser = argparse.ArgumentParser(description="Burme-Coder-Max Automation") parser.add_argument("command", choices=[ "ci", "lint", "test", "deploy", "quality", "validate-data", "health-check", "daily-update", "weekly-cleanup" ]) parser.add_argument("--verbose", "-v", action="store_true") parser.add_argument("--token", help="HuggingFace token") parser.add_argument("--test", action="store_true", help="Use test PyPI") args = parser.parse_args() print(f"\n{BOLD}{'='*50}") print(f"Burme-Coder-Max Automation - {args.command.upper()}") print(f"{'='*50}{RESET}\n") start_time = time.time() if args.command == "ci": CIValidator.check_syntax() CIValidator.check_imports() TestRunner.run_tests(verbose=args.verbose) elif args.command == "lint": CIValidator.run_lint() elif args.command == "test": TestRunner.run_tests(verbose=args.verbose) elif args.command == "deploy": if args.token: Deployer.upload_to_huggingface(args.token) else: log("Token required for deployment", "ERROR") elif args.command == "quality": QualityChecker.check_docstrings() QualityChecker.check_type_hints() QualityChecker.security_scan() elif args.command == "validate-data": DataValidator.validate_jsonl("data/trajectories/sample.jsonl") DataValidator.validate_knowledge_files() elif args.command == "health-check": CronJobs.health_check() elif args.command == "daily-update": CronJobs.daily_update() elif args.command == "weekly-cleanup": CronJobs.weekly_cleanup() duration = time.time() - start_time log(f"Completed in {duration:.2f}s") if __name__ == "__main__": main()