File size: 15,103 Bytes
372384b | 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 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 | #!/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()
|