Spaces:
Paused

yaz / scripts /dev /dev_setup.py
anaselamr's picture
Sprint 28: Platform Hardening & Optimization Complete (55/55 points)
372384b
Raw History Blame Contribute Delete
15.1 kB
#!/usr/bin/env python3
"""
YAZ Care Platform - Development Setup Automation
Automated setup for new developers
"""
import argparse
import os
import subprocess
import sys
from pathlib import Path
from typing import List, Tuple
class DevSetup:
"""Automated development environment setup"""
def __init__(self, skip_deps: bool = False, skip_db: bool = False):
self.project_root = Path(__file__).parent.parent.parent
self.skip_deps = skip_deps
self.skip_db = skip_db
self.steps_completed = []
self.steps_failed = []
def run_setup(self):
"""Run complete setup"""
print("\n🚀 YAZ Care Platform - Development Setup")
print("="*60)
print(f"📍 Project Root: {self.project_root}\n")
steps = [
("Checking Python version", self._check_python),
("Checking Git", self._check_git),
("Creating virtual environment", self._create_venv),
("Installing Python dependencies", self._install_dependencies),
("Setting up environment file", self._setup_env_file),
("Checking Docker", self._check_docker),
("Starting Docker services", self._start_docker_services),
("Waiting for services", self._wait_for_services),
("Running database migrations", self._run_migrations),
("Seeding database", self._seed_database),
("Verifying installation", self._verify_installation),
]
for step_name, step_func in steps:
if not self._run_step(step_name, step_func):
print(f"\n❌ Setup failed at: {step_name}")
self._print_summary()
return False
self._print_summary()
self._print_next_steps()
return True
def _run_step(self, name: str, func) -> bool:
"""Run a setup step"""
print(f"\n{'='*60}")
print(f"📌 {name}...")
print(f"{'='*60}")
try:
result = func()
if result:
self.steps_completed.append(name)
print(f"✅ {name} - SUCCESS")
return True
else:
self.steps_failed.append(name)
print(f"❌ {name} - FAILED")
return False
except Exception as e:
self.steps_failed.append(name)
print(f"❌ {name} - ERROR: {e}")
return False
def _check_python(self) -> bool:
"""Check Python version"""
version = sys.version_info
print(f" Python version: {version.major}.{version.minor}.{version.micro}")
if version.major < 3 or (version.major == 3 and version.minor < 9):
print(" ❌ Python 3.9+ required")
return False
print(" ✓ Python version is compatible")
return True
def _check_git(self) -> bool:
"""Check Git installation"""
try:
result = subprocess.run(
["git", "--version"],
capture_output=True,
text=True,
check=True
)
print(f" {result.stdout.strip()}")
print(" ✓ Git is installed")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
print(" ❌ Git is not installed")
return False
def _create_venv(self) -> bool:
"""Create virtual environment"""
venv_path = self.project_root / ".venv"
if venv_path.exists():
print(f" Virtual environment already exists at: {venv_path}")
return True
print(f" Creating virtual environment at: {venv_path}")
try:
subprocess.run(
[sys.executable, "-m", "venv", str(venv_path)],
check=True,
cwd=self.project_root
)
print(" ✓ Virtual environment created")
return True
except subprocess.CalledProcessError as e:
print(f" ❌ Failed to create virtual environment: {e}")
return False
def _install_dependencies(self) -> bool:
"""Install Python dependencies"""
if self.skip_deps:
print(" ⏭️ Skipping dependency installation")
return True
requirements_file = self.project_root / "requirements.txt"
if not requirements_file.exists():
print(f" ❌ requirements.txt not found")
return False
venv_python = self._get_venv_python()
print(f" Installing from: {requirements_file}")
try:
subprocess.run(
[str(venv_python), "-m", "pip", "install", "--upgrade", "pip"],
check=True,
cwd=self.project_root
)
subprocess.run(
[str(venv_python), "-m", "pip", "install", "-r", str(requirements_file)],
check=True,
cwd=self.project_root
)
print(" ✓ Dependencies installed")
return True
except subprocess.CalledProcessError as e:
print(f" ❌ Failed to install dependencies: {e}")
return False
def _setup_env_file(self) -> bool:
"""Setup environment file"""
env_file = self.project_root / ".env"
env_example = self.project_root / ".env.example"
if env_file.exists():
print(f" .env file already exists")
return True
if not env_example.exists():
print(f" ⚠️ .env.example not found, creating minimal .env")
self._create_minimal_env()
return True
print(f" Copying .env.example to .env")
try:
import shutil
shutil.copy(env_example, env_file)
print(" ✓ .env file created")
print(" ⚠️ Please review and update .env with your configuration")
return True
except Exception as e:
print(f" ❌ Failed to create .env: {e}")
return False
def _create_minimal_env(self):
"""Create minimal .env file"""
env_content = """# YAZ Care Platform - Environment Configuration
# Application
APP_ENV=development
DEBUG=true
SECRET_KEY=dev-secret-key-change-in-production
# Database
DATABASE_URL=postgresql+asyncpg://yazcare:yazcare@localhost:5432/yazcare
# Redis
REDIS_URL=redis://localhost:6379/0
# API
API_HOST=0.0.0.0
API_PORT=8000
# Security
JWT_SECRET_KEY=dev-jwt-secret-change-in-production
JWT_ALGORITHM=HS256
JWT_EXPIRATION_MINUTES=30
"""
env_file = self.project_root / ".env"
env_file.write_text(env_content)
def _check_docker(self) -> bool:
"""Check Docker installation"""
try:
result = subprocess.run(
["docker", "--version"],
capture_output=True,
text=True,
check=True
)
print(f" {result.stdout.strip()}")
result = subprocess.run(
["docker-compose", "--version"],
capture_output=True,
text=True,
check=True
)
print(f" {result.stdout.strip()}")
print(" ✓ Docker and Docker Compose are installed")
return True
except (subprocess.CalledProcessError, FileNotFoundError):
print(" ❌ Docker or Docker Compose is not installed")
return False
def _start_docker_services(self) -> bool:
"""Start Docker services"""
compose_file = self.project_root / "deployment" / "docker-compose.yml"
if not compose_file.exists():
print(f" ❌ docker-compose.yml not found at: {compose_file}")
return False
print(f" Starting services from: {compose_file}")
try:
subprocess.run(
["docker-compose", "-f", str(compose_file), "up", "-d"],
check=True,
cwd=self.project_root
)
print(" ✓ Docker services started")
return True
except subprocess.CalledProcessError as e:
print(f" ❌ Failed to start Docker services: {e}")
return False
def _wait_for_services(self) -> bool:
"""Wait for services to be ready"""
import time
print(" Waiting for services to be ready...")
services = [
("PostgreSQL", "localhost", 5432),
("Redis", "localhost", 6379),
]
for service_name, host, port in services:
print(f" Checking {service_name}...")
max_attempts = 30
for attempt in range(max_attempts):
if self._check_port(host, port):
print(f" ✓ {service_name} is ready")
break
time.sleep(1)
if attempt == max_attempts - 1:
print(f" ❌ {service_name} did not start in time")
return False
print(" ✓ All services are ready")
return True
def _check_port(self, host: str, port: int) -> bool:
"""Check if port is open"""
import socket
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.settimeout(1)
result = sock.connect_ex((host, port))
return result == 0
except Exception:
return False
def _run_migrations(self) -> bool:
"""Run database migrations"""
if self.skip_db:
print(" ⏭️ Skipping database migrations")
return True
venv_python = self._get_venv_python()
print(" Running Alembic migrations...")
try:
subprocess.run(
[str(venv_python), "-m", "alembic", "upgrade", "head"],
check=True,
cwd=self.project_root
)
print(" ✓ Migrations completed")
return True
except subprocess.CalledProcessError as e:
print(f" ⚠️ Migrations failed (this may be normal for first setup): {e}")
return True # Don't fail setup if migrations fail
def _seed_database(self) -> bool:
"""Seed database with sample data"""
if self.skip_db:
print(" ⏭️ Skipping database seeding")
return True
seed_script = self.project_root / "scripts" / "dev" / "seed_database.py"
if not seed_script.exists():
print(" ⚠️ Seed script not found, skipping")
return True
venv_python = self._get_venv_python()
print(" Seeding database with sample data...")
try:
subprocess.run(
[str(venv_python), str(seed_script)],
check=True,
cwd=self.project_root
)
print(" ✓ Database seeded")
return True
except subprocess.CalledProcessError as e:
print(f" ⚠️ Seeding failed: {e}")
return True # Don't fail setup if seeding fails
def _verify_installation(self) -> bool:
"""Verify installation"""
venv_python = self._get_venv_python()
print(" Verifying Python packages...")
try:
result = subprocess.run(
[str(venv_python), "-m", "pip", "list"],
capture_output=True,
text=True,
check=True
)
package_count = len(result.stdout.strip().split('\n')) - 2 # Subtract header lines
print(f" ✓ {package_count} packages installed")
# Check key packages
key_packages = ["fastapi", "sqlalchemy", "alembic", "pydantic", "redis"]
for package in key_packages:
if package.lower() in result.stdout.lower():
print(f" ✓ {package} installed")
else:
print(f" ⚠️ {package} not found")
return True
except subprocess.CalledProcessError as e:
print(f" ❌ Verification failed: {e}")
return False
def _get_venv_python(self) -> Path:
"""Get path to virtual environment Python"""
venv_path = self.project_root / ".venv"
if sys.platform == "win32":
return venv_path / "Scripts" / "python.exe"
return venv_path / "bin" / "python"
def _print_summary(self):
"""Print setup summary"""
print("\n" + "="*60)
print("📊 Setup Summary")
print("="*60)
print(f"\n✅ Completed steps ({len(self.steps_completed)}):")
for step in self.steps_completed:
print(f" ✓ {step}")
if self.steps_failed:
print(f"\n❌ Failed steps ({len(self.steps_failed)}):")
for step in self.steps_failed:
print(f" ✗ {step}")
def _print_next_steps(self):
"""Print next steps"""
print("\n" + "="*60)
print("🎯 Next Steps")
print("="*60)
print("""
1. Activate virtual environment:
source .venv/bin/activate # Linux/Mac
.venv\\Scripts\\activate # Windows
2. Review and update .env file with your configuration
3. Start the development server:
python main.py serve --debug
4. Access the application:
- API: http://localhost:8000
- Docs: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
5. Run tests:
pytest tests/
6. Generate a new module:
python scripts/dev/generate_module.py mymodule "My module description"
7. Seed additional data:
python scripts/dev/seed_database.py
Happy coding! 🚀
""")
def main():
"""Main CLI entry point"""
parser = argparse.ArgumentParser(
description="YAZ Care Platform - Development Setup",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Full setup
python dev_setup.py
# Skip dependency installation
python dev_setup.py --skip-deps
# Skip database setup
python dev_setup.py --skip-db
# Quick setup (skip deps and db)
python dev_setup.py --skip-deps --skip-db
"""
)
parser.add_argument(
"--skip-deps",
action="store_true",
help="Skip Python dependency installation"
)
parser.add_argument(
"--skip-db",
action="store_true",
help="Skip database migrations and seeding"
)
args = parser.parse_args()
setup = DevSetup(
skip_deps=args.skip_deps,
skip_db=args.skip_db
)
try:
success = setup.run_setup()
sys.exit(0 if success else 1)
except KeyboardInterrupt:
print("\n\n❌ Setup interrupted by user")
sys.exit(1)
except Exception as e:
print(f"\n❌ Setup failed: {e}")
import traceback
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()