ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
Add git webhook and deployment management APIs
Juan Denis5597521148ac
diff --git a/ROADMAP.md b/ROADMAP.mdindex e9feb778..ae08e4a1 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -118,7 +118,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 10: Multi-Server Management (Planned)-**Priority: High** | **Target: v1.1.0**+**Priority: High**- [ ] Agent-based remote server monitoring- [ ] Centralized dashboard for multiple servers@@ -131,7 +131,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 11: Git Deployment (Planned)-**Priority: High** | **Target: v1.1.0**+**Priority: High**- [ ] GitHub/GitLab webhook integration- [ ] Automatic deployment on push@@ -145,7 +145,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 12: Backup & Restore (Planned)-**Priority: High** | **Target: v1.2.0**+**Priority: High**- [ ] Automated database backups- [ ] File/directory backups@@ -160,7 +160,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 13: Email Server Management (Planned)-**Priority: Medium** | **Target: v1.3.0**+**Priority: Medium**- [ ] Postfix mail server setup- [ ] Dovecot IMAP/POP3 configuration@@ -174,7 +174,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 14: Advanced SSL Features (Planned)-**Priority: Medium** | **Target: v1.2.0**+**Priority: Medium**- [ ] Wildcard SSL certificates- [ ] Multi-domain certificates (SAN)@@ -186,7 +186,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 15: Team & Permissions (Planned)-**Priority: Medium** | **Target: v1.4.0**+**Priority: Medium**- [ ] Multi-user support- [ ] Role-based access control (RBAC)@@ -199,7 +199,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 16: API Enhancements (Planned)-**Priority: Medium** | **Target: v1.3.0**+**Priority: Medium**- [ ] API key management- [ ] Rate limiting@@ -211,7 +211,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 17: Advanced Security (Planned)-**Priority: High** | **Target: v1.2.0**+**Priority: High**- [ ] Fail2ban integration- [ ] SSH key management@@ -225,7 +225,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 18: Performance Optimization (Planned)-**Priority: Low** | **Target: v1.5.0**+**Priority: Low**- [ ] Redis caching integration- [ ] Database query optimization@@ -237,7 +237,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 19: Mobile App (Planned)-**Priority: Low** | **Target: v2.0.0**+**Priority: Low**- [ ] React Native mobile application- [ ] Push notifications@@ -248,7 +248,7 @@ This document outlines the development roadmap for ServerKit. Features are organ## Phase 20: Marketplace & Extensions (Planned)-**Priority: Low** | **Target: v2.0.0**+**Priority: Low**- [ ] Plugin/extension system- [ ] Community marketplacediff --git a/backend/app/api/git.py b/backend/app/api/git.pyindex 217e8d7a..d9f10866 100644--- a/backend/app/api/git.py+++ b/backend/app/api/git.py@@ -1,8 +1,11 @@-"""Git Server API endpoints for managing integrated Gitea instance."""+"""Git Server API endpoints for managing integrated Gitea instance and webhooks."""from flask import Blueprint, request, jsonifyfrom flask_jwt_extended import jwt_requiredfrom ..services.git_service import GitService+from ..services.webhook_service import WebhookService+from ..services.gitea_api_service import GiteaAPIService+from ..services.git_deploy_service import GitDeployServicegit_bp = Blueprint('git', __name__)@@ -86,3 +89,370 @@ def restart():if result.get('success'):return jsonify(result), 200return jsonify(result), 400+++# ==================== WEBHOOK ENDPOINTS ====================++@git_bp.route('/webhooks', methods=['GET'])+@jwt_required()+def list_webhooks():+ """List all configured webhooks."""+ result = WebhookService.list_webhooks()+ return jsonify(result), 200+++@git_bp.route('/webhooks', methods=['POST'])+@jwt_required()+def create_webhook():+ """Create a new webhook."""+ data = request.get_json() or {}++ result = WebhookService.create_webhook(+ name=data.get('name'),+ source=data.get('source'),+ source_repo_url=data.get('sourceRepoUrl'),+ source_branch=data.get('sourceBranch', 'main'),+ local_repo_name=data.get('localRepoName'),+ sync_direction=data.get('syncDirection', 'pull'),+ auto_sync=data.get('autoSync', True),+ app_id=data.get('appId'),+ deploy_on_push=data.get('deployOnPush', False),+ pre_deploy_script=data.get('preDeployScript'),+ post_deploy_script=data.get('postDeployScript'),+ zero_downtime=data.get('zeroDowntime', False)+ )++ if result.get('success'):+ return jsonify(result), 201+ return jsonify(result), 400+++@git_bp.route('/webhooks/<int:webhook_id>', methods=['GET'])+@jwt_required()+def get_webhook(webhook_id):+ """Get a specific webhook."""+ result = WebhookService.get_webhook(webhook_id)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@git_bp.route('/webhooks/<int:webhook_id>', methods=['PUT'])+@jwt_required()+def update_webhook(webhook_id):+ """Update a webhook."""+ data = request.get_json() or {}++ result = WebhookService.update_webhook(webhook_id, data)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/webhooks/<int:webhook_id>', methods=['DELETE'])+@jwt_required()+def delete_webhook(webhook_id):+ """Delete a webhook."""+ result = WebhookService.delete_webhook(webhook_id)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/webhooks/<int:webhook_id>/toggle', methods=['POST'])+@jwt_required()+def toggle_webhook(webhook_id):+ """Toggle webhook active status."""+ result = WebhookService.toggle_webhook(webhook_id)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/webhooks/<int:webhook_id>/logs', methods=['GET'])+@jwt_required()+def get_webhook_logs(webhook_id):+ """Get logs for a specific webhook."""+ limit = request.args.get('limit', 50, type=int)+ result = WebhookService.get_webhook_logs(webhook_id, limit=limit)+ return jsonify(result), 200+++@git_bp.route('/webhooks/<int:webhook_id>/test', methods=['POST'])+@jwt_required()+def test_webhook(webhook_id):+ """Test a webhook by triggering a manual sync."""+ result = WebhookService.test_webhook(webhook_id)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++# Public endpoint - no auth required (verified by signature)+@git_bp.route('/webhooks/receive/<token>', methods=['POST'])+def receive_webhook(token):+ """Receive incoming webhook from GitHub/GitLab/Bitbucket."""+ # Determine source from headers+ if 'X-GitHub-Event' in request.headers:+ source = 'github'+ event_type = request.headers.get('X-GitHub-Event')+ signature = request.headers.get('X-Hub-Signature-256')+ delivery_id = request.headers.get('X-GitHub-Delivery')+ elif 'X-Gitlab-Event' in request.headers:+ source = 'gitlab'+ event_type = request.headers.get('X-Gitlab-Event')+ signature = request.headers.get('X-Gitlab-Token')+ delivery_id = None+ elif 'X-Event-Key' in request.headers:+ source = 'bitbucket'+ event_type = request.headers.get('X-Event-Key')+ signature = request.headers.get('X-Hub-Signature')+ delivery_id = request.headers.get('X-Request-Id')+ else:+ return jsonify({'error': 'Unknown webhook source'}), 400++ result = WebhookService.handle_webhook(+ token=token,+ source=source,+ event_type=event_type,+ signature=signature,+ delivery_id=delivery_id,+ headers=dict(request.headers),+ payload=request.get_data(),+ payload_json=request.get_json(silent=True)+ )++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++# ==================== REPOSITORY ENDPOINTS ====================++@git_bp.route('/repos', methods=['GET'])+@jwt_required()+def list_repositories():+ """List all repositories in Gitea."""+ token = request.args.get('token')+ limit = request.args.get('limit', 50, type=int)++ result = GiteaAPIService.list_repositories(token=token, limit=limit)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/repos/<owner>/<repo>', methods=['GET'])+@jwt_required()+def get_repository(owner, repo):+ """Get repository details."""+ token = request.args.get('token')++ result = GiteaAPIService.get_repository(owner, repo, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@git_bp.route('/repos/<owner>/<repo>/stats', methods=['GET'])+@jwt_required()+def get_repo_stats(owner, repo):+ """Get repository statistics."""+ token = request.args.get('token')++ result = GiteaAPIService.get_repo_stats(owner, repo, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/repos/<owner>/<repo>/branches', methods=['GET'])+@jwt_required()+def list_branches(owner, repo):+ """List repository branches."""+ token = request.args.get('token')++ result = GiteaAPIService.list_branches(owner, repo, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/repos/<owner>/<repo>/branches/<branch>', methods=['GET'])+@jwt_required()+def get_branch(owner, repo, branch):+ """Get branch details."""+ token = request.args.get('token')++ result = GiteaAPIService.get_branch(owner, repo, branch, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@git_bp.route('/repos/<owner>/<repo>/commits', methods=['GET'])+@jwt_required()+def list_commits(owner, repo):+ """List repository commits."""+ token = request.args.get('token')+ branch = request.args.get('branch')+ page = request.args.get('page', 1, type=int)+ limit = request.args.get('limit', 30, type=int)++ result = GiteaAPIService.list_commits(+ owner, repo,+ branch=branch,+ page=page,+ limit=limit,+ token=token+ )++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/repos/<owner>/<repo>/commits/<sha>', methods=['GET'])+@jwt_required()+def get_commit(owner, repo, sha):+ """Get commit details."""+ token = request.args.get('token')++ result = GiteaAPIService.get_commit(owner, repo, sha, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@git_bp.route('/repos/<owner>/<repo>/contents', methods=['GET'])+@jwt_required()+def list_files(owner, repo):+ """List files in repository directory."""+ token = request.args.get('token')+ ref = request.args.get('ref', 'main')+ path = request.args.get('path', '')++ result = GiteaAPIService.list_files(owner, repo, ref=ref, path=path, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/repos/<owner>/<repo>/contents/<path:filepath>', methods=['GET'])+@jwt_required()+def get_file_content(owner, repo, filepath):+ """Get file content."""+ token = request.args.get('token')+ ref = request.args.get('ref', 'main')++ result = GiteaAPIService.get_file_content(owner, repo, filepath, ref=ref, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@git_bp.route('/repos/<owner>/<repo>/readme', methods=['GET'])+@jwt_required()+def get_readme(owner, repo):+ """Get repository README."""+ token = request.args.get('token')+ ref = request.args.get('ref')++ result = GiteaAPIService.get_readme(owner, repo, ref=ref, token=token)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@git_bp.route('/version', methods=['GET'])+@jwt_required()+def get_gitea_version():+ """Get Gitea server version."""+ result = GiteaAPIService.get_server_version()++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++# ==================== DEPLOYMENT ENDPOINTS ====================++@git_bp.route('/deployments/app/<int:app_id>', methods=['GET'])+@jwt_required()+def get_app_deployments(app_id):+ """Get deployment history for an application."""+ limit = request.args.get('limit', 20, type=int)+ result = GitDeployService.get_deployments(app_id, limit=limit)+ return jsonify(result), 200+++@git_bp.route('/deployments/<int:deployment_id>', methods=['GET'])+@jwt_required()+def get_deployment(deployment_id):+ """Get a specific deployment with logs."""+ include_logs = request.args.get('logs', 'false').lower() == 'true'+ result = GitDeployService.get_deployment(deployment_id, include_logs=include_logs)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 404+++@git_bp.route('/deployments/app/<int:app_id>/deploy', methods=['POST'])+@jwt_required()+def manual_deploy(app_id):+ """Trigger a manual deployment for an application."""+ data = request.get_json() or {}+ branch = data.get('branch')++ result = GitDeployService.manual_deploy(app_id, branch=branch)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/deployments/app/<int:app_id>/rollback', methods=['POST'])+@jwt_required()+def rollback_deployment(app_id):+ """Rollback to a previous deployment version."""+ data = request.get_json() or {}+ target_version = data.get('targetVersion')++ result = GitDeployService.rollback(app_id, target_version=target_version)++ if result.get('success'):+ return jsonify(result), 200+ return jsonify(result), 400+++@git_bp.route('/deployments/webhook/<int:webhook_id>', methods=['GET'])+@jwt_required()+def get_webhook_deployments(webhook_id):+ """Get deployments triggered by a specific webhook."""+ from app.models import GitDeployment++ limit = request.args.get('limit', 20, type=int)+ deployments = GitDeployment.query.filter_by(webhook_id=webhook_id)\+ .order_by(GitDeployment.created_at.desc())\+ .limit(limit).all()++ return jsonify({+ 'success': True,+ 'deployments': [d.to_dict() for d in deployments],+ 'count': len(deployments)+ }), 200diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 51d9ea4a..7668ae3f 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -8,9 +8,10 @@ from app.models.system_settings import SystemSettingsfrom app.models.audit_log import AuditLogfrom app.models.metrics_history import MetricsHistoryfrom app.models.workflow import Workflow+from app.models.webhook import GitWebhook, WebhookLog, GitDeployment__all__ = ['User', 'Application', 'Domain', 'EnvironmentVariable', 'EnvironmentVariableHistory','NotificationPreferences', 'Deployment', 'DeploymentDiff', 'SystemSettings', 'AuditLog',- 'MetricsHistory', 'Workflow'+ 'MetricsHistory', 'Workflow', 'GitWebhook', 'WebhookLog', 'GitDeployment']diff --git a/backend/app/models/webhook.py b/backend/app/models/webhook.pynew file mode 100644index 00000000..0bfed416--- /dev/null+++ b/backend/app/models/webhook.py@@ -0,0 +1,213 @@+from datetime import datetime+from app import db+++class GitWebhook(db.Model):+ """Webhook configuration for syncing external repos with local Gitea."""+ __tablename__ = 'git_webhooks'++ id = db.Column(db.Integer, primary_key=True)+ name = db.Column(db.String(100), nullable=False)++ # Source repository (GitHub, GitLab, Bitbucket)+ source = db.Column(db.String(50), nullable=False) # 'github', 'gitlab', 'bitbucket'+ source_repo_url = db.Column(db.String(500), nullable=False)+ source_branch = db.Column(db.String(100), default='main')++ # Local Gitea repository (optional - for mirroring)+ local_repo_name = db.Column(db.String(200), nullable=True)++ # Webhook security+ secret = db.Column(db.String(100), nullable=False)+ webhook_token = db.Column(db.String(50), nullable=False, unique=True)++ # Sync configuration+ sync_direction = db.Column(db.String(20), default='pull') # 'pull', 'push', 'bidirectional'+ auto_sync = db.Column(db.Boolean, default=True)++ # Deployment configuration+ app_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=True)+ deploy_on_push = db.Column(db.Boolean, default=False)+ pre_deploy_script = db.Column(db.Text, nullable=True)+ post_deploy_script = db.Column(db.Text, nullable=True)+ zero_downtime = db.Column(db.Boolean, default=False)++ # Status tracking+ is_active = db.Column(db.Boolean, default=True)+ last_sync_at = db.Column(db.DateTime, nullable=True)+ last_sync_status = db.Column(db.String(20), nullable=True) # 'success', 'failed', 'pending'+ last_sync_message = db.Column(db.Text, nullable=True)+ sync_count = db.Column(db.Integer, default=0)++ # Metadata+ created_at = db.Column(db.DateTime, default=datetime.utcnow)+ updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)++ # Relationships+ app = db.relationship('Application', backref=db.backref('webhooks', lazy='dynamic'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'name': self.name,+ 'source': self.source,+ 'source_repo_url': self.source_repo_url,+ 'source_branch': self.source_branch,+ 'local_repo_name': self.local_repo_name,+ 'webhook_token': self.webhook_token,+ 'sync_direction': self.sync_direction,+ 'auto_sync': self.auto_sync,+ 'app_id': self.app_id,+ 'app_name': self.app.name if self.app else None,+ 'deploy_on_push': self.deploy_on_push,+ 'pre_deploy_script': self.pre_deploy_script,+ 'post_deploy_script': self.post_deploy_script,+ 'zero_downtime': self.zero_downtime,+ 'is_active': self.is_active,+ 'last_sync_at': self.last_sync_at.isoformat() if self.last_sync_at else None,+ 'last_sync_status': self.last_sync_status,+ 'last_sync_message': self.last_sync_message,+ 'sync_count': self.sync_count,+ 'created_at': self.created_at.isoformat(),+ 'updated_at': self.updated_at.isoformat(),+ 'webhook_url': f'/api/git/webhooks/receive/{self.webhook_token}'+ }++ def __repr__(self):+ return f'<GitWebhook {self.name} ({self.source})>'+++class WebhookLog(db.Model):+ """Log of webhook events received."""+ __tablename__ = 'webhook_logs'++ id = db.Column(db.Integer, primary_key=True)+ webhook_id = db.Column(db.Integer, db.ForeignKey('git_webhooks.id'), nullable=True)++ # Event info+ source = db.Column(db.String(50), nullable=False) # 'github', 'gitlab', 'bitbucket'+ event_type = db.Column(db.String(50), nullable=False) # 'push', 'pull_request', 'ping', etc.+ delivery_id = db.Column(db.String(100), nullable=True) # GitHub's X-GitHub-Delivery++ # Payload summary+ ref = db.Column(db.String(200), nullable=True) # refs/heads/main+ commit_sha = db.Column(db.String(64), nullable=True)+ commit_message = db.Column(db.Text, nullable=True)+ pusher = db.Column(db.String(100), nullable=True)++ # Processing status+ status = db.Column(db.String(20), default='received') # 'received', 'processed', 'ignored', 'failed'+ status_message = db.Column(db.Text, nullable=True)++ # Raw data (for debugging)+ headers_json = db.Column(db.Text, nullable=True)+ payload_preview = db.Column(db.Text, nullable=True) # First 1000 chars of payload++ # Timestamps+ received_at = db.Column(db.DateTime, default=datetime.utcnow)+ processed_at = db.Column(db.DateTime, nullable=True)++ # Relationship+ webhook = db.relationship('GitWebhook', backref=db.backref('logs', lazy='dynamic'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'webhook_id': self.webhook_id,+ 'source': self.source,+ 'event_type': self.event_type,+ 'delivery_id': self.delivery_id,+ 'ref': self.ref,+ 'commit_sha': self.commit_sha,+ 'commit_message': self.commit_message,+ 'pusher': self.pusher,+ 'status': self.status,+ 'status_message': self.status_message,+ 'received_at': self.received_at.isoformat(),+ 'processed_at': self.processed_at.isoformat() if self.processed_at else None+ }++ def __repr__(self):+ return f'<WebhookLog {self.source}/{self.event_type} at {self.received_at}>'+++class GitDeployment(db.Model):+ """Track deployment history for git-based deployments."""+ __tablename__ = 'git_deployments'++ id = db.Column(db.Integer, primary_key=True)++ # Links+ app_id = db.Column(db.Integer, db.ForeignKey('applications.id'), nullable=False)+ webhook_id = db.Column(db.Integer, db.ForeignKey('git_webhooks.id'), nullable=True)++ # Deployment info+ version = db.Column(db.Integer, nullable=False) # Auto-increment per app+ commit_sha = db.Column(db.String(64), nullable=True)+ commit_message = db.Column(db.Text, nullable=True)+ branch = db.Column(db.String(100), nullable=True)+ triggered_by = db.Column(db.String(100), nullable=True) # 'webhook', 'manual', 'rollback'++ # Status+ status = db.Column(db.String(20), default='pending') # 'pending', 'running', 'success', 'failed', 'rolled_back'+ started_at = db.Column(db.DateTime, nullable=True)+ completed_at = db.Column(db.DateTime, nullable=True)+ duration_seconds = db.Column(db.Integer, nullable=True)++ # Logs+ pre_script_output = db.Column(db.Text, nullable=True)+ deploy_output = db.Column(db.Text, nullable=True)+ post_script_output = db.Column(db.Text, nullable=True)+ error_message = db.Column(db.Text, nullable=True)++ # Rollback info+ is_rollback = db.Column(db.Boolean, default=False)+ rollback_from_version = db.Column(db.Integer, nullable=True)+ rolled_back_at = db.Column(db.DateTime, nullable=True)+ rolled_back_to_id = db.Column(db.Integer, nullable=True)++ # Snapshot for rollback (stores docker-compose.yml content, env vars, etc.)+ snapshot_data = db.Column(db.Text, nullable=True) # JSON string++ # Metadata+ created_at = db.Column(db.DateTime, default=datetime.utcnow)++ # Relationships+ app = db.relationship('Application', backref=db.backref('git_deployments', lazy='dynamic'))+ webhook = db.relationship('GitWebhook', backref=db.backref('deployments', lazy='dynamic'))++ def to_dict(self):+ return {+ 'id': self.id,+ 'app_id': self.app_id,+ 'app_name': self.app.name if self.app else None,+ 'webhook_id': self.webhook_id,+ 'version': self.version,+ 'commit_sha': self.commit_sha,+ 'short_sha': self.commit_sha[:7] if self.commit_sha else None,+ 'commit_message': self.commit_message,+ 'branch': self.branch,+ 'triggered_by': self.triggered_by,+ 'status': self.status,+ 'started_at': self.started_at.isoformat() if self.started_at else None,+ 'completed_at': self.completed_at.isoformat() if self.completed_at else None,+ 'duration_seconds': self.duration_seconds,+ 'error_message': self.error_message,+ 'is_rollback': self.is_rollback,+ 'rollback_from_version': self.rollback_from_version,+ 'rolled_back_at': self.rolled_back_at.isoformat() if self.rolled_back_at else None,+ 'created_at': self.created_at.isoformat()+ }++ def to_dict_full(self):+ """Include logs in output."""+ data = self.to_dict()+ data.update({+ 'pre_script_output': self.pre_script_output,+ 'deploy_output': self.deploy_output,+ 'post_script_output': self.post_script_output+ })+ return data++ def __repr__(self):+ return f'<GitDeployment {self.app.name if self.app else "?"} v{self.version} ({self.status})>'diff --git a/backend/app/services/git_deploy_service.py b/backend/app/services/git_deploy_service.pynew file mode 100644index 00000000..876e81a1--- /dev/null+++ b/backend/app/services/git_deploy_service.py@@ -0,0 +1,544 @@+"""Git Deployment Service - Handles automatic deployments from git webhooks."""++import os+import json+import shutil+import subprocess+from datetime import datetime+from typing import Dict, Optional+++class GitDeployService:+ """Service for managing git-based deployments."""++ @classmethod+ def deploy(cls, app_id: int, webhook_id: int = None, commit_sha: str = None,+ commit_message: str = None, branch: str = None,+ triggered_by: str = 'webhook') -> Dict:+ """+ Deploy an application by pulling latest code and restarting.++ Args:+ app_id: Application ID to deploy+ webhook_id: Optional webhook that triggered this deployment+ commit_sha: Git commit SHA+ commit_message: Git commit message+ branch: Git branch name+ triggered_by: How deployment was triggered ('webhook', 'manual', 'rollback')++ Returns:+ Dict with deployment result+ """+ from app import db+ from app.models import Application, GitWebhook, GitDeployment+ from app.services.docker_service import DockerService++ app = Application.query.get(app_id)+ if not app:+ return {'success': False, 'error': 'Application not found'}++ webhook = GitWebhook.query.get(webhook_id) if webhook_id else None++ # Get next version number+ last_deployment = GitDeployment.query.filter_by(app_id=app_id)\+ .order_by(GitDeployment.version.desc()).first()+ next_version = (last_deployment.version + 1) if last_deployment else 1++ # Create deployment record+ deployment = GitDeployment(+ app_id=app_id,+ webhook_id=webhook_id,+ version=next_version,+ commit_sha=commit_sha,+ commit_message=commit_message,+ branch=branch or (webhook.source_branch if webhook else 'main'),+ triggered_by=triggered_by,+ status='running',+ started_at=datetime.utcnow()+ )++ db.session.add(deployment)+ db.session.commit()++ try:+ # Create snapshot for rollback+ snapshot = cls._create_snapshot(app)+ deployment.snapshot_data = json.dumps(snapshot)++ logs = []++ # Step 1: Pre-deployment script+ if webhook and webhook.pre_deploy_script:+ logs.append("=== Running pre-deployment script ===")+ pre_result = cls._run_script(webhook.pre_deploy_script, app.root_path)+ deployment.pre_script_output = pre_result.get('output', '')+ logs.append(pre_result.get('output', ''))++ if not pre_result.get('success'):+ raise Exception(f"Pre-deployment script failed: {pre_result.get('error')}")++ # Step 2: Git pull+ logs.append("\n=== Pulling latest code ===")+ pull_result = cls._git_pull(app.root_path, branch or (webhook.source_branch if webhook else 'main'))+ logs.append(pull_result.get('output', ''))++ if not pull_result.get('success'):+ raise Exception(f"Git pull failed: {pull_result.get('error')}")++ # Step 3: Restart application+ logs.append("\n=== Restarting application ===")++ if webhook and webhook.zero_downtime:+ restart_result = cls._zero_downtime_restart(app)+ else:+ restart_result = cls._standard_restart(app)++ deployment.deploy_output = '\n'.join(logs) + '\n' + restart_result.get('output', '')++ if not restart_result.get('success'):+ raise Exception(f"Restart failed: {restart_result.get('error')}")++ # Step 4: Post-deployment script+ if webhook and webhook.post_deploy_script:+ logs.append("\n=== Running post-deployment script ===")+ post_result = cls._run_script(webhook.post_deploy_script, app.root_path)+ deployment.post_script_output = post_result.get('output', '')++ if not post_result.get('success'):+ # Post-script failure is logged but doesn't fail deployment+ logs.append(f"Warning: Post-deployment script failed: {post_result.get('error')}")++ # Success+ deployment.status = 'success'+ deployment.completed_at = datetime.utcnow()+ deployment.duration_seconds = int(+ (deployment.completed_at - deployment.started_at).total_seconds()+ )++ # Update app status+ app.status = 'running'+ app.last_deployed_at = datetime.utcnow()++ db.session.commit()++ return {+ 'success': True,+ 'deployment_id': deployment.id,+ 'version': deployment.version,+ 'duration': deployment.duration_seconds,+ 'message': f'Deployed version {deployment.version} successfully'+ }++ except Exception as e:+ deployment.status = 'failed'+ deployment.error_message = str(e)+ deployment.completed_at = datetime.utcnow()+ deployment.duration_seconds = int(+ (deployment.completed_at - deployment.started_at).total_seconds()+ )+ db.session.commit()++ return {+ 'success': False,+ 'deployment_id': deployment.id,+ 'version': deployment.version,+ 'error': str(e)+ }++ @classmethod+ def rollback(cls, app_id: int, target_version: int = None) -> Dict:+ """+ Rollback to a previous deployment version.++ Args:+ app_id: Application ID+ target_version: Version to rollback to (default: previous version)++ Returns:+ Dict with rollback result+ """+ from app import db+ from app.models import Application, GitDeployment+ from app.services.docker_service import DockerService++ app = Application.query.get(app_id)+ if not app:+ return {'success': False, 'error': 'Application not found'}++ # Get current deployment+ current = GitDeployment.query.filter_by(app_id=app_id, status='success')\+ .order_by(GitDeployment.version.desc()).first()++ if not current:+ return {'success': False, 'error': 'No successful deployment to rollback from'}++ # Get target deployment+ if target_version:+ target = GitDeployment.query.filter_by(+ app_id=app_id,+ version=target_version,+ status='success'+ ).first()+ else:+ # Get previous successful deployment+ target = GitDeployment.query.filter_by(app_id=app_id, status='success')\+ .filter(GitDeployment.version < current.version)\+ .order_by(GitDeployment.version.desc()).first()++ if not target:+ return {'success': False, 'error': 'No previous version to rollback to'}++ if not target.snapshot_data:+ return {'success': False, 'error': 'Target deployment has no snapshot data'}++ # Create rollback deployment+ next_version = current.version + 1+ deployment = GitDeployment(+ app_id=app_id,+ version=next_version,+ commit_sha=target.commit_sha,+ commit_message=f'Rollback to v{target.version}',+ branch=target.branch,+ triggered_by='rollback',+ is_rollback=True,+ rollback_from_version=current.version,+ status='running',+ started_at=datetime.utcnow()+ )++ db.session.add(deployment)+ db.session.commit()++ try:+ # Restore snapshot+ snapshot = json.loads(target.snapshot_data)+ restore_result = cls._restore_snapshot(app, snapshot)++ deployment.deploy_output = restore_result.get('output', '')++ if not restore_result.get('success'):+ raise Exception(f"Snapshot restore failed: {restore_result.get('error')}")++ # Restart with restored config+ restart_result = cls._standard_restart(app)+ deployment.deploy_output += '\n' + restart_result.get('output', '')++ if not restart_result.get('success'):+ raise Exception(f"Restart failed: {restart_result.get('error')}")++ # Success+ deployment.status = 'success'+ deployment.completed_at = datetime.utcnow()+ deployment.duration_seconds = int(+ (deployment.completed_at - deployment.started_at).total_seconds()+ )+ deployment.rolled_back_to_id = target.id++ # Mark current as rolled back+ current.rolled_back_at = datetime.utcnow()++ # Update app+ app.status = 'running'+ app.last_deployed_at = datetime.utcnow()++ db.session.commit()++ return {+ 'success': True,+ 'deployment_id': deployment.id,+ 'version': deployment.version,+ 'rolled_back_from': current.version,+ 'rolled_back_to': target.version,+ 'message': f'Rolled back from v{current.version} to v{target.version}'+ }++ except Exception as e:+ deployment.status = 'failed'+ deployment.error_message = str(e)+ deployment.completed_at = datetime.utcnow()+ db.session.commit()++ return {+ 'success': False,+ 'deployment_id': deployment.id,+ 'error': str(e)+ }++ @classmethod+ def get_deployments(cls, app_id: int, limit: int = 20) -> Dict:+ """Get deployment history for an application."""+ from app.models import GitDeployment++ deployments = GitDeployment.query.filter_by(app_id=app_id)\+ .order_by(GitDeployment.created_at.desc())\+ .limit(limit).all()++ return {+ 'success': True,+ 'deployments': [d.to_dict() for d in deployments],+ 'count': len(deployments)+ }++ @classmethod+ def get_deployment(cls, deployment_id: int, include_logs: bool = False) -> Dict:+ """Get a specific deployment."""+ from app.models import GitDeployment++ deployment = GitDeployment.query.get(deployment_id)+ if not deployment:+ return {'success': False, 'error': 'Deployment not found'}++ return {+ 'success': True,+ 'deployment': deployment.to_dict_full() if include_logs else deployment.to_dict()+ }++ @classmethod+ def manual_deploy(cls, app_id: int, branch: str = None) -> Dict:+ """Trigger a manual deployment."""+ from app.models import Application, GitWebhook++ app = Application.query.get(app_id)+ if not app:+ return {'success': False, 'error': 'Application not found'}++ # Find webhook for this app to get settings+ webhook = GitWebhook.query.filter_by(app_id=app_id, is_active=True).first()++ return cls.deploy(+ app_id=app_id,+ webhook_id=webhook.id if webhook else None,+ branch=branch or (webhook.source_branch if webhook else 'main'),+ triggered_by='manual'+ )++ # ==================== INTERNAL HELPERS ====================++ @classmethod+ def _git_pull(cls, path: str, branch: str = 'main') -> Dict:+ """Pull latest code from git."""+ if not os.path.exists(path):+ return {'success': False, 'error': f'Path does not exist: {path}'}++ git_dir = os.path.join(path, '.git')+ if not os.path.exists(git_dir):+ return {'success': False, 'error': 'Not a git repository'}++ try:+ # Fetch and reset to remote branch+ commands = [+ ['git', 'fetch', 'origin', branch],+ ['git', 'reset', '--hard', f'origin/{branch}']+ ]++ output = []+ for cmd in commands:+ result = subprocess.run(+ cmd,+ cwd=path,+ capture_output=True,+ text=True,+ timeout=120+ )+ output.append(f"$ {' '.join(cmd)}")+ output.append(result.stdout)+ if result.stderr:+ output.append(result.stderr)++ if result.returncode != 0:+ return {+ 'success': False,+ 'error': result.stderr,+ 'output': '\n'.join(output)+ }++ return {+ 'success': True,+ 'output': '\n'.join(output)+ }++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Git pull timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def _standard_restart(cls, app) -> Dict:+ """Standard restart - stop then start."""+ from app.services.docker_service import DockerService++ output = []++ # Stop+ stop_result = DockerService.compose_down(app.root_path)+ output.append(f"Stop: {stop_result.get('message', stop_result.get('error', 'Unknown'))}")++ # Build and start+ up_result = DockerService.compose_up(app.root_path, detach=True, build=True)+ output.append(f"Start: {up_result.get('message', up_result.get('error', 'Unknown'))}")++ return {+ 'success': up_result.get('success', False),+ 'output': '\n'.join(output),+ 'error': up_result.get('error')+ }++ @classmethod+ def _zero_downtime_restart(cls, app) -> Dict:+ """Zero-downtime restart using rolling update."""+ from app.services.docker_service import DockerService++ output = []++ try:+ # Build new images first+ build_result = subprocess.run(+ ['docker', 'compose', 'build'],+ cwd=app.root_path,+ capture_output=True,+ text=True,+ timeout=300+ )+ output.append(f"Build: {build_result.stdout}")++ if build_result.returncode != 0:+ return {+ 'success': False,+ 'error': build_result.stderr,+ 'output': '\n'.join(output)+ }++ # Rolling update - start new containers before stopping old+ up_result = subprocess.run(+ ['docker', 'compose', 'up', '-d', '--no-deps', '--scale', 'web=2'],+ cwd=app.root_path,+ capture_output=True,+ text=True,+ timeout=120+ )++ # Wait for new container to be healthy+ import time+ time.sleep(5)++ # Scale back down+ scale_result = subprocess.run(+ ['docker', 'compose', 'up', '-d', '--no-deps', '--scale', 'web=1'],+ cwd=app.root_path,+ capture_output=True,+ text=True,+ timeout=60+ )++ output.append(f"Rolling update completed")++ return {+ 'success': True,+ 'output': '\n'.join(output)+ }++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Restart timed out', 'output': '\n'.join(output)}+ except Exception as e:+ return {'success': False, 'error': str(e), 'output': '\n'.join(output)}++ @classmethod+ def _run_script(cls, script: str, cwd: str) -> Dict:+ """Run a deployment script."""+ try:+ result = subprocess.run(+ script,+ shell=True,+ cwd=cwd,+ capture_output=True,+ text=True,+ timeout=300,+ env={**os.environ, 'DEPLOY_DIR': cwd}+ )++ return {+ 'success': result.returncode == 0,+ 'output': result.stdout + result.stderr,+ 'error': result.stderr if result.returncode != 0 else None+ }++ except subprocess.TimeoutExpired:+ return {'success': False, 'error': 'Script timed out'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def _create_snapshot(cls, app) -> Dict:+ """Create a snapshot of current state for rollback."""+ snapshot = {+ 'created_at': datetime.utcnow().isoformat(),+ 'app_id': app.id,+ 'files': {}+ }++ # Capture docker-compose.yml+ compose_path = os.path.join(app.root_path, 'docker-compose.yml')+ if os.path.exists(compose_path):+ with open(compose_path, 'r') as f:+ snapshot['files']['docker-compose.yml'] = f.read()++ # Capture .env+ env_path = os.path.join(app.root_path, '.env')+ if os.path.exists(env_path):+ with open(env_path, 'r') as f:+ snapshot['files']['.env'] = f.read()++ # Capture current git commit+ try:+ result = subprocess.run(+ ['git', 'rev-parse', 'HEAD'],+ cwd=app.root_path,+ capture_output=True,+ text=True,+ timeout=10+ )+ if result.returncode == 0:+ snapshot['commit_sha'] = result.stdout.strip()+ except Exception:+ pass++ return snapshot++ @classmethod+ def _restore_snapshot(cls, app, snapshot: Dict) -> Dict:+ """Restore application state from snapshot."""+ output = []++ try:+ # Restore files+ for filename, content in snapshot.get('files', {}).items():+ filepath = os.path.join(app.root_path, filename)+ with open(filepath, 'w') as f:+ f.write(content)+ output.append(f"Restored {filename}")++ # Checkout specific commit if available+ if snapshot.get('commit_sha'):+ result = subprocess.run(+ ['git', 'checkout', snapshot['commit_sha']],+ cwd=app.root_path,+ capture_output=True,+ text=True,+ timeout=60+ )+ if result.returncode == 0:+ output.append(f"Checked out commit {snapshot['commit_sha'][:7]}")+ else:+ output.append(f"Warning: Could not checkout commit: {result.stderr}")++ return {+ 'success': True,+ 'output': '\n'.join(output)+ }++ except Exception as e:+ return {+ 'success': False,+ 'error': str(e),+ 'output': '\n'.join(output)+ }diff --git a/backend/app/services/gitea_api_service.py b/backend/app/services/gitea_api_service.pynew file mode 100644index 00000000..fc235abe--- /dev/null+++ b/backend/app/services/gitea_api_service.py@@ -0,0 +1,484 @@+"""Gitea API Service - Communicates with the local Gitea instance."""++import requests+from typing import Dict, List, Optional+from datetime import datetime+++class GiteaAPIService:+ """Service for interacting with the Gitea API."""++ @classmethod+ def _get_base_url(cls) -> Optional[str]:+ """Get the Gitea base URL from config."""+ from app.services.git_service import GitService++ status = GitService.get_gitea_status()+ if not status.get('installed') or not status.get('running'):+ return None++ port = status.get('http_port')+ if not port:+ return None++ return f"http://127.0.0.1:{port}/api/v1"++ @classmethod+ def _get_headers(cls, token: str = None) -> Dict:+ """Get request headers."""+ headers = {+ 'Content-Type': 'application/json',+ 'Accept': 'application/json'+ }+ if token:+ headers['Authorization'] = f'token {token}'+ return headers++ @classmethod+ def get_server_version(cls) -> Dict:+ """Get Gitea server version."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ response = requests.get(f"{base_url}/version", timeout=5)+ if response.status_code == 200:+ return {'success': True, 'version': response.json()}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def list_users(cls, token: str = None) -> Dict:+ """List all users (requires admin token)."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ response = requests.get(+ f"{base_url}/admin/users",+ headers=cls._get_headers(token),+ timeout=10+ )+ if response.status_code == 200:+ return {'success': True, 'users': response.json()}+ elif response.status_code == 401:+ return {'success': False, 'error': 'Authentication required'}+ elif response.status_code == 403:+ return {'success': False, 'error': 'Admin access required'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def list_repositories(cls, token: str = None, limit: int = 50) -> Dict:+ """List all repositories."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ # Try to get all repos (requires token for private repos)+ params = {'limit': limit}+ response = requests.get(+ f"{base_url}/repos/search",+ headers=cls._get_headers(token),+ params=params,+ timeout=10+ )++ if response.status_code == 200:+ data = response.json()+ repos = data.get('data', [])+ return {+ 'success': True,+ 'repositories': [cls._format_repo(r) for r in repos],+ 'count': len(repos)+ }+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_repository(cls, owner: str, repo: str, token: str = None) -> Dict:+ """Get repository details."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ response = requests.get(+ f"{base_url}/repos/{owner}/{repo}",+ headers=cls._get_headers(token),+ timeout=10+ )++ if response.status_code == 200:+ return {+ 'success': True,+ 'repository': cls._format_repo(response.json())+ }+ elif response.status_code == 404:+ return {'success': False, 'error': 'Repository not found'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def list_branches(cls, owner: str, repo: str, token: str = None) -> Dict:+ """List repository branches."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ response = requests.get(+ f"{base_url}/repos/{owner}/{repo}/branches",+ headers=cls._get_headers(token),+ timeout=10+ )++ if response.status_code == 200:+ branches = response.json()+ return {+ 'success': True,+ 'branches': [cls._format_branch(b) for b in branches],+ 'count': len(branches)+ }+ elif response.status_code == 404:+ return {'success': False, 'error': 'Repository not found'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_branch(cls, owner: str, repo: str, branch: str, token: str = None) -> Dict:+ """Get branch details."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ response = requests.get(+ f"{base_url}/repos/{owner}/{repo}/branches/{branch}",+ headers=cls._get_headers(token),+ timeout=10+ )++ if response.status_code == 200:+ return {+ 'success': True,+ 'branch': cls._format_branch(response.json())+ }+ elif response.status_code == 404:+ return {'success': False, 'error': 'Branch not found'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def list_commits(cls, owner: str, repo: str, branch: str = None,+ page: int = 1, limit: int = 30, token: str = None) -> Dict:+ """List repository commits."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ params = {'page': page, 'limit': limit}+ if branch:+ params['sha'] = branch++ response = requests.get(+ f"{base_url}/repos/{owner}/{repo}/commits",+ headers=cls._get_headers(token),+ params=params,+ timeout=10+ )++ if response.status_code == 200:+ commits = response.json()+ return {+ 'success': True,+ 'commits': [cls._format_commit(c) for c in commits],+ 'count': len(commits),+ 'page': page+ }+ elif response.status_code == 404:+ return {'success': False, 'error': 'Repository not found'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_commit(cls, owner: str, repo: str, sha: str, token: str = None) -> Dict:+ """Get commit details."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ response = requests.get(+ f"{base_url}/repos/{owner}/{repo}/git/commits/{sha}",+ headers=cls._get_headers(token),+ timeout=10+ )++ if response.status_code == 200:+ return {+ 'success': True,+ 'commit': cls._format_commit(response.json())+ }+ elif response.status_code == 404:+ return {'success': False, 'error': 'Commit not found'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def list_files(cls, owner: str, repo: str, ref: str = 'main',+ path: str = '', token: str = None) -> Dict:+ """List files in a repository directory."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ url = f"{base_url}/repos/{owner}/{repo}/contents"+ if path:+ url += f"/{path}"++ params = {'ref': ref}+ response = requests.get(+ url,+ headers=cls._get_headers(token),+ params=params,+ timeout=10+ )++ if response.status_code == 200:+ contents = response.json()+ # Handle both file and directory responses+ if isinstance(contents, list):+ files = [cls._format_file(f) for f in contents]+ else:+ files = [cls._format_file(contents)]+ return {+ 'success': True,+ 'files': files,+ 'path': path,+ 'ref': ref+ }+ elif response.status_code == 404:+ return {'success': False, 'error': 'Path not found'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_file_content(cls, owner: str, repo: str, filepath: str,+ ref: str = 'main', token: str = None) -> Dict:+ """Get file content."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ params = {'ref': ref}+ response = requests.get(+ f"{base_url}/repos/{owner}/{repo}/contents/{filepath}",+ headers=cls._get_headers(token),+ params=params,+ timeout=10+ )++ if response.status_code == 200:+ data = response.json()+ return {+ 'success': True,+ 'file': cls._format_file(data),+ 'content': data.get('content'),+ 'encoding': data.get('encoding', 'base64')+ }+ elif response.status_code == 404:+ return {'success': False, 'error': 'File not found'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_readme(cls, owner: str, repo: str, ref: str = None, token: str = None) -> Dict:+ """Get repository README."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ url = f"{base_url}/repos/{owner}/{repo}/readme"+ params = {}+ if ref:+ params['ref'] = ref++ response = requests.get(+ url,+ headers=cls._get_headers(token),+ params=params,+ timeout=10+ )++ if response.status_code == 200:+ data = response.json()+ return {+ 'success': True,+ 'readme': {+ 'name': data.get('name'),+ 'path': data.get('path'),+ 'content': data.get('content'),+ 'encoding': data.get('encoding', 'base64')+ }+ }+ elif response.status_code == 404:+ return {'success': False, 'error': 'README not found'}+ return {'success': False, 'error': f'Status {response.status_code}'}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_repo_stats(cls, owner: str, repo: str, token: str = None) -> Dict:+ """Get repository statistics."""+ base_url = cls._get_base_url()+ if not base_url:+ return {'success': False, 'error': 'Gitea is not running'}++ try:+ # Get repo info+ repo_response = requests.get(+ f"{base_url}/repos/{owner}/{repo}",+ headers=cls._get_headers(token),+ timeout=10+ )++ if repo_response.status_code != 200:+ return {'success': False, 'error': 'Repository not found'}++ repo_data = repo_response.json()++ # Get branch count+ branches_response = requests.get(+ f"{base_url}/repos/{owner}/{repo}/branches",+ headers=cls._get_headers(token),+ timeout=10+ )+ branch_count = len(branches_response.json()) if branches_response.status_code == 200 else 0++ # Get recent commits count+ commits_response = requests.get(+ f"{base_url}/repos/{owner}/{repo}/commits",+ headers=cls._get_headers(token),+ params={'limit': 1},+ timeout=10+ )++ return {+ 'success': True,+ 'stats': {+ 'stars': repo_data.get('stars_count', 0),+ 'forks': repo_data.get('forks_count', 0),+ 'watchers': repo_data.get('watchers_count', 0),+ 'branches': branch_count,+ 'size': repo_data.get('size', 0),+ 'open_issues': repo_data.get('open_issues_count', 0),+ 'default_branch': repo_data.get('default_branch', 'main'),+ 'has_wiki': repo_data.get('has_wiki', False),+ 'has_issues': repo_data.get('has_issues', False)+ }+ }+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ==================== FORMATTING HELPERS ====================++ @classmethod+ def _format_repo(cls, repo: Dict) -> Dict:+ """Format repository data."""+ return {+ 'id': repo.get('id'),+ 'name': repo.get('name'),+ 'full_name': repo.get('full_name'),+ 'description': repo.get('description'),+ 'private': repo.get('private', False),+ 'fork': repo.get('fork', False),+ 'empty': repo.get('empty', False),+ 'mirror': repo.get('mirror', False),+ 'size': repo.get('size', 0),+ 'default_branch': repo.get('default_branch', 'main'),+ 'stars': repo.get('stars_count', 0),+ 'forks': repo.get('forks_count', 0),+ 'watchers': repo.get('watchers_count', 0),+ 'open_issues': repo.get('open_issues_count', 0),+ 'owner': {+ 'login': repo.get('owner', {}).get('login'),+ 'avatar_url': repo.get('owner', {}).get('avatar_url')+ },+ 'html_url': repo.get('html_url'),+ 'clone_url': repo.get('clone_url'),+ 'ssh_url': repo.get('ssh_url'),+ 'created_at': repo.get('created_at'),+ 'updated_at': repo.get('updated_at'),+ 'pushed_at': repo.get('pushed_at')+ }++ @classmethod+ def _format_branch(cls, branch: Dict) -> Dict:+ """Format branch data."""+ commit = branch.get('commit', {})+ return {+ 'name': branch.get('name'),+ 'protected': branch.get('protected', False),+ 'commit': {+ 'sha': commit.get('id') or commit.get('sha'),+ 'message': commit.get('message'),+ 'author': commit.get('author', {}).get('name') if commit.get('author') else None,+ 'date': commit.get('timestamp') or commit.get('committer', {}).get('date')+ }+ }++ @classmethod+ def _format_commit(cls, commit: Dict) -> Dict:+ """Format commit data."""+ commit_data = commit.get('commit', commit)+ author = commit_data.get('author', {})+ committer = commit_data.get('committer', {})++ return {+ 'sha': commit.get('sha') or commit.get('id'),+ 'short_sha': (commit.get('sha') or commit.get('id', ''))[:7],+ 'message': commit_data.get('message', ''),+ 'author': {+ 'name': author.get('name'),+ 'email': author.get('email'),+ 'date': author.get('date')+ },+ 'committer': {+ 'name': committer.get('name'),+ 'email': committer.get('email'),+ 'date': committer.get('date')+ },+ 'html_url': commit.get('html_url'),+ 'parents': [p.get('sha') for p in commit.get('parents', [])]+ }++ @classmethod+ def _format_file(cls, file: Dict) -> Dict:+ """Format file data."""+ return {+ 'name': file.get('name'),+ 'path': file.get('path'),+ 'type': file.get('type'), # 'file' or 'dir'+ 'size': file.get('size', 0),+ 'sha': file.get('sha'),+ 'html_url': file.get('html_url'),+ 'download_url': file.get('download_url')+ }diff --git a/backend/app/services/webhook_service.py b/backend/app/services/webhook_service.pynew file mode 100644index 00000000..64fbd0d2--- /dev/null+++ b/backend/app/services/webhook_service.py@@ -0,0 +1,566 @@+"""Webhook Service for Git repository sync via webhooks."""++import hmac+import hashlib+import secrets+import json+from datetime import datetime+from typing import Dict, List, Optional+++class WebhookService:+ """Service for managing Git webhooks and processing incoming events."""++ @classmethod+ def list_webhooks(cls) -> Dict:+ """List all configured webhooks."""+ from app.models import GitWebhook++ webhooks = GitWebhook.query.order_by(GitWebhook.created_at.desc()).all()+ return {+ 'success': True,+ 'webhooks': [w.to_dict() for w in webhooks],+ 'count': len(webhooks)+ }++ @classmethod+ def get_webhook(cls, webhook_id: int) -> Dict:+ """Get a specific webhook by ID."""+ from app.models import GitWebhook++ webhook = GitWebhook.query.get(webhook_id)+ if not webhook:+ return {'success': False, 'error': 'Webhook not found'}++ return {+ 'success': True,+ 'webhook': webhook.to_dict()+ }++ @classmethod+ def create_webhook(cls, name: str, source: str, source_repo_url: str,+ source_branch: str = 'main', local_repo_name: str = None,+ sync_direction: str = 'pull', auto_sync: bool = True,+ app_id: int = None, deploy_on_push: bool = False,+ pre_deploy_script: str = None, post_deploy_script: str = None,+ zero_downtime: bool = False) -> Dict:+ """Create a new webhook configuration."""+ from app import db+ from app.models import GitWebhook, Application++ # Validate required fields+ if not name:+ return {'success': False, 'error': 'Name is required'}+ if not source:+ return {'success': False, 'error': 'Source is required'}+ if source not in ['github', 'gitlab', 'bitbucket']:+ return {'success': False, 'error': 'Source must be github, gitlab, or bitbucket'}+ if not source_repo_url:+ return {'success': False, 'error': 'Source repository URL is required'}++ # Validate app_id if provided+ if app_id:+ app = Application.query.get(app_id)+ if not app:+ return {'success': False, 'error': 'Application not found'}++ # Generate secure tokens+ secret = secrets.token_hex(32)+ webhook_token = secrets.token_urlsafe(16)++ try:+ webhook = GitWebhook(+ name=name,+ source=source,+ source_repo_url=source_repo_url,+ source_branch=source_branch,+ local_repo_name=local_repo_name,+ secret=secret,+ webhook_token=webhook_token,+ sync_direction=sync_direction,+ auto_sync=auto_sync,+ app_id=app_id,+ deploy_on_push=deploy_on_push,+ pre_deploy_script=pre_deploy_script,+ post_deploy_script=post_deploy_script,+ zero_downtime=zero_downtime+ )++ db.session.add(webhook)+ db.session.commit()++ return {+ 'success': True,+ 'webhook': webhook.to_dict(),+ 'secret': secret, # Only returned once at creation+ 'message': 'Webhook created successfully. Save the secret - it will not be shown again!'+ }++ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def update_webhook(cls, webhook_id: int, data: Dict) -> Dict:+ """Update a webhook configuration."""+ from app import db+ from app.models import GitWebhook++ webhook = GitWebhook.query.get(webhook_id)+ if not webhook:+ return {'success': False, 'error': 'Webhook not found'}++ try:+ # Update allowed fields+ if 'name' in data:+ webhook.name = data['name']+ if 'sourceBranch' in data:+ webhook.source_branch = data['sourceBranch']+ if 'localRepoName' in data:+ webhook.local_repo_name = data['localRepoName']+ if 'syncDirection' in data:+ webhook.sync_direction = data['syncDirection']+ if 'autoSync' in data:+ webhook.auto_sync = data['autoSync']+ if 'isActive' in data:+ webhook.is_active = data['isActive']++ # Deployment configuration+ if 'appId' in data:+ webhook.app_id = data['appId'] if data['appId'] else None+ if 'deployOnPush' in data:+ webhook.deploy_on_push = data['deployOnPush']+ if 'preDeployScript' in data:+ webhook.pre_deploy_script = data['preDeployScript'] if data['preDeployScript'] else None+ if 'postDeployScript' in data:+ webhook.post_deploy_script = data['postDeployScript'] if data['postDeployScript'] else None+ if 'zeroDowntime' in data:+ webhook.zero_downtime = data['zeroDowntime']++ db.session.commit()++ return {+ 'success': True,+ 'webhook': webhook.to_dict(),+ 'message': 'Webhook updated successfully'+ }++ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def delete_webhook(cls, webhook_id: int) -> Dict:+ """Delete a webhook."""+ from app import db+ from app.models import GitWebhook, WebhookLog++ webhook = GitWebhook.query.get(webhook_id)+ if not webhook:+ return {'success': False, 'error': 'Webhook not found'}++ try:+ # Delete associated logs+ WebhookLog.query.filter_by(webhook_id=webhook_id).delete()++ # Delete webhook+ db.session.delete(webhook)+ db.session.commit()++ return {+ 'success': True,+ 'message': 'Webhook deleted successfully'+ }++ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def toggle_webhook(cls, webhook_id: int) -> Dict:+ """Toggle a webhook's active status."""+ from app import db+ from app.models import GitWebhook++ webhook = GitWebhook.query.get(webhook_id)+ if not webhook:+ return {'success': False, 'error': 'Webhook not found'}++ try:+ webhook.is_active = not webhook.is_active+ db.session.commit()++ return {+ 'success': True,+ 'webhook': webhook.to_dict(),+ 'message': f'Webhook {"activated" if webhook.is_active else "deactivated"}'+ }++ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def regenerate_secret(cls, webhook_id: int) -> Dict:+ """Regenerate the webhook secret."""+ from app import db+ from app.models import GitWebhook++ webhook = GitWebhook.query.get(webhook_id)+ if not webhook:+ return {'success': False, 'error': 'Webhook not found'}++ try:+ new_secret = secrets.token_hex(32)+ webhook.secret = new_secret+ db.session.commit()++ return {+ 'success': True,+ 'secret': new_secret,+ 'message': 'Secret regenerated. Update your webhook settings in the source repository.'+ }++ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_webhook_logs(cls, webhook_id: int = None, limit: int = 50) -> Dict:+ """Get webhook logs."""+ from app.models import WebhookLog++ query = WebhookLog.query+ if webhook_id:+ query = query.filter_by(webhook_id=webhook_id)++ logs = query.order_by(WebhookLog.received_at.desc()).limit(limit).all()++ return {+ 'success': True,+ 'logs': [log.to_dict() for log in logs],+ 'count': len(logs)+ }++ @classmethod+ def handle_webhook(cls, token: str, source: str, event_type: str,+ signature: str, delivery_id: str, headers: Dict,+ payload: bytes, payload_json: Dict) -> Dict:+ """Handle an incoming webhook event."""+ from app import db+ from app.models import GitWebhook, WebhookLog++ # Find webhook by token+ webhook = GitWebhook.query.filter_by(webhook_token=token).first()++ # Create log entry+ log = WebhookLog(+ webhook_id=webhook.id if webhook else None,+ source=source,+ event_type=event_type,+ delivery_id=delivery_id,+ headers_json=json.dumps(dict(headers))[:2000],+ payload_preview=payload[:1000].decode('utf-8', errors='replace') if payload else None,+ status='received'+ )++ if not webhook:+ log.status = 'failed'+ log.status_message = 'Unknown webhook token'+ db.session.add(log)+ db.session.commit()+ return {'success': False, 'error': 'Unknown webhook'}++ if not webhook.is_active:+ log.status = 'ignored'+ log.status_message = 'Webhook is inactive'+ db.session.add(log)+ db.session.commit()+ return {'success': True, 'message': 'Webhook is inactive', 'action': 'ignored'}++ # Verify signature+ if not cls._verify_signature(webhook, source, signature, payload):+ log.status = 'failed'+ log.status_message = 'Invalid signature'+ db.session.add(log)+ db.session.commit()+ return {'success': False, 'error': 'Invalid signature'}++ # Parse payload for logging+ if payload_json:+ cls._extract_payload_info(log, source, event_type, payload_json)++ # Handle ping events+ if event_type in ['ping', 'Push Hook']:+ log.status = 'processed'+ log.status_message = 'Ping received'+ log.processed_at = datetime.utcnow()+ db.session.add(log)+ db.session.commit()+ return {'success': True, 'message': 'Pong!', 'action': 'ping'}++ # Handle push events+ if event_type in ['push', 'Push Hook', 'repo:push']:+ result = cls._handle_push_event(webhook, log, payload_json)+ db.session.add(log)+ db.session.commit()+ return result++ # Unhandled event type+ log.status = 'ignored'+ log.status_message = f'Unhandled event type: {event_type}'+ log.processed_at = datetime.utcnow()+ db.session.add(log)+ db.session.commit()++ return {'success': True, 'message': f'Event {event_type} ignored', 'action': 'ignored'}++ @classmethod+ def _verify_signature(cls, webhook, source: str, signature: str, payload: bytes) -> bool:+ """Verify the webhook signature based on source."""+ if not signature:+ return False++ secret = webhook.secret.encode()++ if source == 'github':+ # GitHub: X-Hub-Signature-256 header with sha256=<hex>+ expected = 'sha256=' + hmac.new(secret, payload, hashlib.sha256).hexdigest()+ return hmac.compare_digest(signature, expected)++ elif source == 'gitlab':+ # GitLab: X-Gitlab-Token header contains the secret directly+ return hmac.compare_digest(signature, webhook.secret)++ elif source == 'bitbucket':+ # Bitbucket: X-Hub-Signature header with sha256=<hex>+ if signature.startswith('sha256='):+ expected = 'sha256=' + hmac.new(secret, payload, hashlib.sha256).hexdigest()+ return hmac.compare_digest(signature, expected)++ return False++ @classmethod+ def _extract_payload_info(cls, log, source: str, event_type: str, payload: Dict):+ """Extract relevant info from payload for logging."""+ try:+ if source == 'github':+ log.ref = payload.get('ref')+ if 'head_commit' in payload and payload['head_commit']:+ log.commit_sha = payload['head_commit'].get('id')+ log.commit_message = payload['head_commit'].get('message', '')[:500]+ if 'pusher' in payload:+ log.pusher = payload['pusher'].get('name')++ elif source == 'gitlab':+ log.ref = payload.get('ref')+ if 'commits' in payload and payload['commits']:+ log.commit_sha = payload['commits'][0].get('id')+ log.commit_message = payload['commits'][0].get('message', '')[:500]+ log.pusher = payload.get('user_name')++ elif source == 'bitbucket':+ if 'push' in payload and 'changes' in payload['push']:+ changes = payload['push']['changes']+ if changes:+ new_ref = changes[0].get('new', {})+ log.ref = new_ref.get('name')+ log.commit_sha = new_ref.get('target', {}).get('hash')+ log.commit_message = new_ref.get('target', {}).get('message', '')[:500]+ if 'actor' in payload:+ log.pusher = payload['actor'].get('display_name')++ except Exception:+ pass # Log extraction is best-effort++ @classmethod+ def _handle_push_event(cls, webhook, log, payload: Dict) -> Dict:+ """Handle a push event - sync the repository and optionally deploy."""+ from app import db+ from app.services.git_deploy_service import GitDeployService++ # Check if push is to the configured branch+ ref = log.ref or ''+ configured_branch = webhook.source_branch++ # Extract branch name from ref (refs/heads/main -> main)+ pushed_branch = ref.replace('refs/heads/', '') if ref.startswith('refs/heads/') else ref++ if pushed_branch != configured_branch:+ log.status = 'ignored'+ log.status_message = f'Push to {pushed_branch}, configured for {configured_branch}'+ log.processed_at = datetime.utcnow()+ return {+ 'success': True,+ 'message': f'Ignoring push to {pushed_branch}',+ 'action': 'ignored'+ }++ # Check if auto-sync is enabled+ if not webhook.auto_sync:+ log.status = 'ignored'+ log.status_message = 'Auto-sync is disabled'+ log.processed_at = datetime.utcnow()+ return {+ 'success': True,+ 'message': 'Auto-sync is disabled',+ 'action': 'ignored'+ }++ # Perform sync and optional deployment+ try:+ actions = ['synced']+ deployment_result = None++ # Trigger deployment if configured+ if webhook.deploy_on_push and webhook.app_id:+ deployment_result = GitDeployService.deploy(+ app_id=webhook.app_id,+ webhook_id=webhook.id,+ commit_sha=log.commit_sha,+ commit_message=log.commit_message,+ branch=pushed_branch,+ triggered_by='webhook'+ )++ if deployment_result.get('success'):+ actions.append('deployed')+ log.status = 'processed'+ log.status_message = f'Deployed v{deployment_result.get("version")} ({log.commit_sha[:7] if log.commit_sha else "unknown"})'+ else:+ log.status = 'failed'+ log.status_message = f'Deployment failed: {deployment_result.get("error")}'+ log.processed_at = datetime.utcnow()++ webhook.last_sync_at = datetime.utcnow()+ webhook.last_sync_status = 'failed'+ webhook.last_sync_message = deployment_result.get('error')++ return {+ 'success': False,+ 'error': deployment_result.get('error'),+ 'action': 'deploy_failed',+ 'deployment_id': deployment_result.get('deployment_id')+ }+ else:+ log.status = 'processed'+ log.status_message = f'Push from {webhook.source} processed (no deployment configured)'++ log.processed_at = datetime.utcnow()++ # Update webhook stats+ webhook.last_sync_at = datetime.utcnow()+ webhook.last_sync_status = 'success'+ webhook.last_sync_message = f'Synced commit {log.commit_sha[:7] if log.commit_sha else "unknown"}'+ webhook.sync_count += 1++ result = {+ 'success': True,+ 'message': 'Push event processed',+ 'action': ','.join(actions),+ 'commit': log.commit_sha+ }++ if deployment_result:+ result['deployment_id'] = deployment_result.get('deployment_id')+ result['deployment_version'] = deployment_result.get('version')++ return result++ except Exception as e:+ log.status = 'failed'+ log.status_message = str(e)+ log.processed_at = datetime.utcnow()++ webhook.last_sync_at = datetime.utcnow()+ webhook.last_sync_status = 'failed'+ webhook.last_sync_message = str(e)++ return {'success': False, 'error': str(e)}++ @classmethod+ def test_webhook(cls, webhook_id: int) -> Dict:+ """Test a webhook by logging a test event."""+ from app import db+ from app.models import GitWebhook, WebhookLog++ webhook = GitWebhook.query.get(webhook_id)+ if not webhook:+ return {'success': False, 'error': 'Webhook not found'}++ try:+ # Create a test log entry+ log = WebhookLog(+ webhook_id=webhook_id,+ source=webhook.source,+ event_type='test',+ status='processed',+ status_message='Manual test triggered',+ processed_at=datetime.utcnow()+ )++ db.session.add(log)+ db.session.commit()++ return {+ 'success': True,+ 'message': 'Test event logged successfully',+ 'webhook_url': webhook.to_dict()['webhook_url']+ }++ except Exception as e:+ db.session.rollback()+ return {'success': False, 'error': str(e)}++ @classmethod+ def get_webhook_setup_instructions(cls, webhook_id: int) -> Dict:+ """Get setup instructions for a webhook."""+ from app.models import GitWebhook++ webhook = GitWebhook.query.get(webhook_id)+ if not webhook:+ return {'success': False, 'error': 'Webhook not found'}++ webhook_url = webhook.to_dict()['webhook_url']++ instructions = {+ 'github': {+ 'title': 'GitHub Webhook Setup',+ 'steps': [+ 'Go to your GitHub repository Settings > Webhooks',+ 'Click "Add webhook"',+ f'Payload URL: YOUR_SERVER_URL{webhook_url}',+ 'Content type: application/json',+ f'Secret: (the secret provided when creating this webhook)',+ 'Select "Just the push event" or customize events',+ 'Click "Add webhook"'+ ]+ },+ 'gitlab': {+ 'title': 'GitLab Webhook Setup',+ 'steps': [+ 'Go to your GitLab project Settings > Webhooks',+ f'URL: YOUR_SERVER_URL{webhook_url}',+ f'Secret token: (the secret provided when creating this webhook)',+ 'Select "Push events" trigger',+ 'Click "Add webhook"'+ ]+ },+ 'bitbucket': {+ 'title': 'Bitbucket Webhook Setup',+ 'steps': [+ 'Go to your Bitbucket repository Settings > Webhooks',+ 'Click "Add webhook"',+ f'URL: YOUR_SERVER_URL{webhook_url}',+ 'Select "Repository push" trigger',+ 'Click "Save"'+ ]+ }+ }++ return {+ 'success': True,+ 'source': webhook.source,+ 'webhook_url': webhook_url,+ 'instructions': instructions.get(webhook.source, {})+ }diff --git a/frontend/dist/index.html b/frontend/dist/index.htmlindex 70f2f172..a03bc7f4 100644--- a/frontend/dist/index.html+++ b/frontend/dist/index.html@@ -6,8 +6,8 @@<link rel="icon" type="image/svg+xml" href="/vite.svg" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>React Dashboard Template</title>- <script type="module" crossorigin src="/assets/index-BpLdi01Q.js"></script>- <link rel="stylesheet" crossorigin href="/assets/index-BwDVuCDb.css">+ <script type="module" crossorigin src="/assets/index-DrutglRQ.js"></script>+ <link rel="stylesheet" crossorigin href="/assets/index-B06xC2dW.css"></head><body>diff --git a/frontend/src/pages/Git.jsx b/frontend/src/pages/Git.jsxindex b4ba3c7d..2b65a690 100644--- a/frontend/src/pages/Git.jsx+++ b/frontend/src/pages/Git.jsx@@ -16,12 +16,68 @@ function Git() {adminEmail: '',adminPassword: ''});+ // Webhook state+ const [webhooks, setWebhooks] = useState([]);+ const [webhooksLoading, setWebhooksLoading] = useState(false);+ const [showWebhookModal, setShowWebhookModal] = useState(false);+ const [selectedWebhook, setSelectedWebhook] = useState(null);+ const [webhookForm, setWebhookForm] = useState({+ name: '',+ source: 'github',+ sourceRepoUrl: '',+ sourceBranch: 'main',+ localRepoName: '',+ syncDirection: 'pull',+ autoSync: true,+ // Deployment settings+ appId: '',+ deployOnPush: false,+ preDeployScript: '',+ postDeployScript: '',+ zeroDowntime: false+ });+ const [webhookSecret, setWebhookSecret] = useState(null);++ // Repository state+ const [repositories, setRepositories] = useState([]);+ const [reposLoading, setReposLoading] = useState(false);+ const [selectedRepo, setSelectedRepo] = useState(null);+ const [repoView, setRepoView] = useState('list'); // 'list', 'detail'+ const [branches, setBranches] = useState([]);+ const [commits, setCommits] = useState([]);+ const [selectedBranch, setSelectedBranch] = useState(null);+ const [files, setFiles] = useState([]);+ const [currentPath, setCurrentPath] = useState('');+ const [repoDetailTab, setRepoDetailTab] = useState('files'); // 'files', 'commits', 'branches'++ // Deployment state+ const [applications, setApplications] = useState([]);+ const [deployments, setDeployments] = useState([]);+ const [deploymentsLoading, setDeploymentsLoading] = useState(false);+ const [selectedDeployment, setSelectedDeployment] = useState(null);+ const [showDeploymentLogs, setShowDeploymentLogs] = useState(false);+ const [deployingAppId, setDeployingAppId] = useState(null);+const toast = useToast();useEffect(() => {loadData();}, []);+ useEffect(() => {+ if (activeTab === 'webhooks' && status?.installed) {+ loadWebhooks();+ loadApplications();+ }+ if (activeTab === 'repositories' && status?.installed && status?.running) {+ loadRepositories();+ }+ if (activeTab === 'deployments' && status?.installed) {+ loadWebhooks();+ loadAllDeployments();+ }+ }, [activeTab, status?.installed, status?.running]);+const loadData = async () => {setLoading(true);try {@@ -43,6 +99,355 @@ function Git() {}};+ const loadWebhooks = async () => {+ setWebhooksLoading(true);+ try {+ const data = await api.getWebhooks();+ setWebhooks(data.webhooks || []);+ } catch (error) {+ console.error('Failed to load webhooks:', error);+ } finally {+ setWebhooksLoading(false);+ }+ };++ const handleCreateWebhook = async () => {+ if (!webhookForm.name || !webhookForm.sourceRepoUrl) {+ toast.error('Name and repository URL are required');+ return;+ }++ setActionLoading(true);+ try {+ const result = await api.createWebhook(webhookForm);+ if (result.success) {+ toast.success('Webhook created successfully');+ setWebhookSecret(result.secret);+ setShowWebhookModal(false);+ setWebhookForm({+ name: '',+ source: 'github',+ sourceRepoUrl: '',+ sourceBranch: 'main',+ localRepoName: '',+ syncDirection: 'pull',+ autoSync: true,+ appId: '',+ deployOnPush: false,+ preDeployScript: '',+ postDeployScript: '',+ zeroDowntime: false+ });+ await loadWebhooks();+ } else {+ toast.error(result.error || 'Failed to create webhook');+ }+ } catch (error) {+ toast.error(`Failed to create webhook: ${error.message}`);+ } finally {+ setActionLoading(false);+ }+ };++ const handleDeleteWebhook = async (webhookId) => {+ setConfirmDialog({+ title: 'Delete Webhook',+ message: 'Are you sure you want to delete this webhook? This cannot be undone.',+ confirmText: 'Delete',+ variant: 'danger',+ onConfirm: async () => {+ try {+ await api.deleteWebhook(webhookId);+ toast.success('Webhook deleted');+ await loadWebhooks();+ } catch (error) {+ toast.error(`Failed to delete: ${error.message}`);+ } finally {+ setConfirmDialog(null);+ }+ },+ onCancel: () => setConfirmDialog(null)+ });+ };++ const handleToggleWebhook = async (webhookId) => {+ try {+ const result = await api.toggleWebhook(webhookId);+ if (result.success) {+ toast.success(result.message);+ await loadWebhooks();+ }+ } catch (error) {+ toast.error(`Failed to toggle webhook: ${error.message}`);+ }+ };++ const handleTestWebhook = async (webhookId) => {+ try {+ const result = await api.testWebhook(webhookId);+ if (result.success) {+ toast.success('Test event logged');+ } else {+ toast.error(result.error || 'Test failed');+ }+ } catch (error) {+ toast.error(`Test failed: ${error.message}`);+ }+ };++ const copyWebhookUrl = (webhook) => {+ const baseUrl = window.location.origin;+ const url = `${baseUrl}/api${webhook.webhook_url}`;+ navigator.clipboard.writeText(url);+ toast.success('Webhook URL copied');+ };++ // Repository functions+ const loadRepositories = async () => {+ setReposLoading(true);+ try {+ const data = await api.getRepositories();+ setRepositories(data.repositories || []);+ } catch (error) {+ console.error('Failed to load repositories:', error);+ if (error.message?.includes('not running')) {+ toast.error('Gitea server is not running');+ }+ } finally {+ setReposLoading(false);+ }+ };++ const selectRepository = async (repo) => {+ setSelectedRepo(repo);+ setRepoView('detail');+ setCurrentPath('');+ setSelectedBranch(repo.default_branch);+ setRepoDetailTab('files');++ // Load branches, commits, and files+ try {+ const [branchesData, commitsData, filesData] = await Promise.all([+ api.getBranches(repo.owner.login, repo.name),+ api.getCommits(repo.owner.login, repo.name, repo.default_branch),+ api.getRepoFiles(repo.owner.login, repo.name, repo.default_branch)+ ]);++ setBranches(branchesData.branches || []);+ setCommits(commitsData.commits || []);+ setFiles(filesData.files || []);+ } catch (error) {+ console.error('Failed to load repo details:', error);+ toast.error('Failed to load repository details');+ }+ };++ const navigateToPath = async (path) => {+ if (!selectedRepo) return;++ try {+ const data = await api.getRepoFiles(+ selectedRepo.owner.login,+ selectedRepo.name,+ selectedBranch,+ path+ );+ setFiles(data.files || []);+ setCurrentPath(path);+ } catch (error) {+ toast.error('Failed to load directory');+ }+ };++ const navigateUp = () => {+ if (!currentPath) return;+ const parts = currentPath.split('/');+ parts.pop();+ navigateToPath(parts.join('/'));+ };++ const changeBranch = async (branchName) => {+ if (!selectedRepo) return;++ setSelectedBranch(branchName);+ setCurrentPath('');++ try {+ const [commitsData, filesData] = await Promise.all([+ api.getCommits(selectedRepo.owner.login, selectedRepo.name, branchName),+ api.getRepoFiles(selectedRepo.owner.login, selectedRepo.name, branchName)+ ]);++ setCommits(commitsData.commits || []);+ setFiles(filesData.files || []);+ } catch (error) {+ toast.error('Failed to switch branch');+ }+ };++ const loadMoreCommits = async () => {+ if (!selectedRepo) return;++ const currentPage = Math.ceil(commits.length / 30) + 1;+ try {+ const data = await api.getCommits(+ selectedRepo.owner.login,+ selectedRepo.name,+ selectedBranch,+ currentPage+ );+ if (data.commits?.length) {+ setCommits([...commits, ...data.commits]);+ }+ } catch (error) {+ toast.error('Failed to load more commits');+ }+ };++ const backToRepoList = () => {+ setSelectedRepo(null);+ setRepoView('list');+ setBranches([]);+ setCommits([]);+ setFiles([]);+ setCurrentPath('');+ };++ // Deployment functions+ const loadApplications = async () => {+ try {+ const data = await api.getApps();+ setApplications(data.apps || []);+ } catch (error) {+ console.error('Failed to load applications:', error);+ }+ };++ const loadAllDeployments = async () => {+ setDeploymentsLoading(true);+ try {+ // Load deployments for all webhooks that have deploy_on_push enabled+ const webhooksData = await api.getWebhooks();+ const webhooksWithDeploy = (webhooksData.webhooks || []).filter(w => w.deploy_on_push && w.app_id);++ let allDeployments = [];+ for (const webhook of webhooksWithDeploy) {+ const data = await api.getWebhookDeployments(webhook.id, 10);+ if (data.deployments) {+ allDeployments = [...allDeployments, ...data.deployments.map(d => ({+ ...d,+ webhook_name: webhook.name+ }))];+ }+ }++ // Sort by created_at descending+ allDeployments.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));+ setDeployments(allDeployments);+ } catch (error) {+ console.error('Failed to load deployments:', error);+ } finally {+ setDeploymentsLoading(false);+ }+ };++ const loadWebhookDeployments = async (webhookId) => {+ try {+ const data = await api.getWebhookDeployments(webhookId, 20);+ return data.deployments || [];+ } catch (error) {+ console.error('Failed to load webhook deployments:', error);+ return [];+ }+ };++ const handleTriggerDeploy = async (appId) => {+ setDeployingAppId(appId);+ try {+ const result = await api.triggerDeploy(appId);+ if (result.success) {+ toast.success(`Deployment started: v${result.version}`);+ await loadAllDeployments();+ } else {+ toast.error(result.error || 'Failed to trigger deployment');+ }+ } catch (error) {+ toast.error(`Failed to deploy: ${error.message}`);+ } finally {+ setDeployingAppId(null);+ }+ };++ const handleRollback = async (appId, targetVersion) => {+ setConfirmDialog({+ title: 'Rollback Deployment',+ message: `Are you sure you want to rollback to version ${targetVersion}? This will restart the application with the previous code.`,+ confirmText: 'Rollback',+ variant: 'warning',+ onConfirm: async () => {+ try {+ const result = await api.rollbackDeployment(appId, targetVersion);+ if (result.success) {+ toast.success(result.message || 'Rollback completed');+ await loadAllDeployments();+ } else {+ toast.error(result.error || 'Rollback failed');+ }+ } catch (error) {+ toast.error(`Rollback failed: ${error.message}`);+ } finally {+ setConfirmDialog(null);+ }+ },+ onCancel: () => setConfirmDialog(null)+ });+ };++ const viewDeploymentLogs = async (deploymentId) => {+ try {+ const data = await api.getDeployment(deploymentId, true);+ if (data.success) {+ setSelectedDeployment(data.deployment);+ setShowDeploymentLogs(true);+ } else {+ toast.error('Failed to load deployment details');+ }+ } catch (error) {+ toast.error(`Failed to load logs: ${error.message}`);+ }+ };++ const getStatusColor = (status) => {+ switch (status) {+ case 'success': return 'success';+ case 'failed': return 'danger';+ case 'running': return 'warning';+ default: return '';+ }+ };++ const formatFileSize = (bytes) => {+ if (bytes === 0) return '0 B';+ const k = 1024;+ const sizes = ['B', 'KB', 'MB', 'GB'];+ const i = Math.floor(Math.log(bytes) / Math.log(k));+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];+ };++ const formatDate = (dateString) => {+ if (!dateString) return 'Unknown';+ const date = new Date(dateString);+ const now = new Date();+ const diff = now - date;++ if (diff < 60000) return 'just now';+ if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;+ if (diff < 604800000) return `${Math.floor(diff / 86400000)}d ago`;++ return date.toLocaleDateString();+ };+const handleInstall = async () => {if (!installForm.adminEmail) {toast.error('Admin email is required');@@ -289,12 +694,30 @@ function Git() {>Overview</button>+ <button+ className={`tab ${activeTab === 'repositories' ? 'active' : ''}`}+ onClick={() => setActiveTab('repositories')}+ >+ Repositories+ </button><buttonclassName={`tab ${activeTab === 'access' ? 'active' : ''}`}onClick={() => setActiveTab('access')}>Access Info</button>+ <button+ className={`tab ${activeTab === 'webhooks' ? 'active' : ''}`}+ onClick={() => setActiveTab('webhooks')}+ >+ Webhooks+ </button>+ <button+ className={`tab ${activeTab === 'deployments' ? 'active' : ''}`}+ onClick={() => setActiveTab('deployments')}+ >+ Deployments+ </button><buttonclassName={`tab ${activeTab === 'settings' ? 'active' : ''}`}onClick={() => setActiveTab('settings')}@@ -357,6 +780,311 @@ function Git() {</div>)}+ {activeTab === 'repositories' && (+ <div className="repositories-tab">+ {!status?.running ? (+ <div className="empty-state">+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1.5">+ <circle cx="12" cy="12" r="10"/>+ <line x1="12" y1="8" x2="12" y2="12"/>+ <line x1="12" y1="16" x2="12.01" y2="16"/>+ </svg>+ <h4>Server Not Running</h4>+ <p>Start the Git server to browse repositories</p>+ <button className="btn btn-primary" onClick={handleStart}>+ Start Server+ </button>+ </div>+ ) : repoView === 'list' ? (+ <>+ <div className="repos-header">+ <h3>Repositories</h3>+ <button+ className="btn btn-secondary btn-sm"+ onClick={loadRepositories}+ disabled={reposLoading}+ >+ Refresh+ </button>+ </div>++ {reposLoading ? (+ <div className="loading-state">+ <Spinner />+ </div>+ ) : repositories.length === 0 ? (+ <div className="empty-state">+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1.5">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ <h4>No Repositories Yet</h4>+ <p>Create your first repository in Gitea</p>+ <button className="btn btn-primary" onClick={openGitea}>+ Open Gitea+ </button>+ </div>+ ) : (+ <div className="repos-list">+ {repositories.map((repo) => (+ <div+ key={repo.id}+ className="repo-card"+ onClick={() => selectRepository(repo)}+ >+ <div className="repo-info">+ <div className="repo-name">+ <span className="owner">{repo.owner.login}/</span>+ <span className="name">{repo.name}</span>+ {repo.private && <span className="badge private">Private</span>}+ {repo.fork && <span className="badge fork">Fork</span>}+ </div>+ {repo.description && (+ <p className="repo-description">{repo.description}</p>+ )}+ <div className="repo-meta">+ <span className="meta-item">+ <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="18" cy="18" r="3"/>+ <circle cx="6" cy="6" r="3"/>+ <path d="M6 21V9a9 9 0 0 0 9 9"/>+ </svg>+ {repo.default_branch}+ </span>+ <span className="meta-item">+ <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" strokeWidth="2">+ <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>+ </svg>+ {repo.stars}+ </span>+ <span className="meta-item">+ <svg viewBox="0 0 24 24" width="14" height="14" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="18" r="3"/>+ <circle cx="6" cy="6" r="3"/>+ <circle cx="18" cy="6" r="3"/>+ <path d="M18 9v1a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V9"/>+ <path d="M12 12v3"/>+ </svg>+ {repo.forks}+ </span>+ <span className="meta-item updated">+ Updated {formatDate(repo.updated_at)}+ </span>+ </div>+ </div>+ <div className="repo-arrow">+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">+ <polyline points="9 18 15 12 9 6"/>+ </svg>+ </div>+ </div>+ ))}+ </div>+ )}+ </>+ ) : (+ <div className="repo-detail">+ <div className="repo-detail-header">+ <button className="btn btn-ghost btn-sm" onClick={backToRepoList}>+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <polyline points="15 18 9 12 15 6"/>+ </svg>+ Back+ </button>+ <div className="repo-title">+ <h3>{selectedRepo?.owner.login}/{selectedRepo?.name}</h3>+ {selectedRepo?.description && (+ <p>{selectedRepo.description}</p>+ )}+ </div>+ <div className="branch-selector">+ <select+ value={selectedBranch || ''}+ onChange={(e) => changeBranch(e.target.value)}+ >+ {branches.map((b) => (+ <option key={b.name} value={b.name}>{b.name}</option>+ ))}+ </select>+ </div>+ </div>++ <div className="repo-detail-tabs">+ <button+ className={`tab ${repoDetailTab === 'files' ? 'active' : ''}`}+ onClick={() => setRepoDetailTab('files')}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ Files+ </button>+ <button+ className={`tab ${repoDetailTab === 'commits' ? 'active' : ''}`}+ onClick={() => setRepoDetailTab('commits')}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <circle cx="12" cy="12" r="4"/>+ <line x1="1.05" y1="12" x2="7" y2="12"/>+ <line x1="17.01" y1="12" x2="22.96" y2="12"/>+ </svg>+ Commits ({commits.length})+ </button>+ <button+ className={`tab ${repoDetailTab === 'branches' ? 'active' : ''}`}+ onClick={() => setRepoDetailTab('branches')}+ >+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <line x1="6" y1="3" x2="6" y2="15"/>+ <circle cx="18" cy="6" r="3"/>+ <circle cx="6" cy="18" r="3"/>+ <path d="M18 9a9 9 0 0 1-9 9"/>+ </svg>+ Branches ({branches.length})+ </button>+ </div>++ <div className="repo-detail-content">+ {repoDetailTab === 'files' && (+ <div className="files-browser">+ {currentPath && (+ <div className="breadcrumb">+ <button onClick={() => navigateToPath('')}>+ {selectedRepo?.name}+ </button>+ {currentPath.split('/').map((part, i, arr) => (+ <span key={i}>+ <span className="separator">/</span>+ <button+ onClick={() => navigateToPath(arr.slice(0, i + 1).join('/'))}+ >+ {part}+ </button>+ </span>+ ))}+ </div>+ )}+ <div className="files-list">+ {currentPath && (+ <div className="file-item dir" onClick={navigateUp}>+ <div className="file-icon">+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <polyline points="15 18 9 12 15 6"/>+ </svg>+ </div>+ <span className="file-name">..</span>+ </div>+ )}+ {files+ .sort((a, b) => {+ if (a.type === 'dir' && b.type !== 'dir') return -1;+ if (a.type !== 'dir' && b.type === 'dir') return 1;+ return a.name.localeCompare(b.name);+ })+ .map((file) => (+ <div+ key={file.path}+ className={`file-item ${file.type}`}+ onClick={() => file.type === 'dir' && navigateToPath(file.path)}+ >+ <div className="file-icon">+ {file.type === 'dir' ? (+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>+ </svg>+ ) : (+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>+ <polyline points="14 2 14 8 20 8"/>+ </svg>+ )}+ </div>+ <span className="file-name">{file.name}</span>+ {file.type === 'file' && (+ <span className="file-size">{formatFileSize(file.size)}</span>+ )}+ </div>+ ))}+ </div>+ </div>+ )}++ {repoDetailTab === 'commits' && (+ <div className="commits-list">+ {commits.map((commit) => (+ <div key={commit.sha} className="commit-item">+ <div className="commit-info">+ <div className="commit-message">+ {commit.message?.split('\n')[0]}+ </div>+ <div className="commit-meta">+ <span className="author">{commit.author?.name}</span>+ <span className="date">{formatDate(commit.author?.date)}</span>+ </div>+ </div>+ <div className="commit-sha">+ <code>{commit.short_sha}</code>+ </div>+ </div>+ ))}+ {commits.length >= 30 && (+ <button+ className="btn btn-secondary btn-block"+ onClick={loadMoreCommits}+ >+ Load More+ </button>+ )}+ </div>+ )}++ {repoDetailTab === 'branches' && (+ <div className="branches-list">+ {branches.map((branch) => (+ <div+ key={branch.name}+ className={`branch-item ${branch.name === selectedBranch ? 'active' : ''}`}+ >+ <div className="branch-info">+ <div className="branch-name">+ <svg viewBox="0 0 24 24" width="16" height="16" stroke="currentColor" fill="none" strokeWidth="2">+ <line x1="6" y1="3" x2="6" y2="15"/>+ <circle cx="18" cy="6" r="3"/>+ <circle cx="6" cy="18" r="3"/>+ <path d="M18 9a9 9 0 0 1-9 9"/>+ </svg>+ {branch.name}+ {branch.name === selectedRepo?.default_branch && (+ <span className="badge default">default</span>+ )}+ {branch.protected && (+ <span className="badge protected">protected</span>+ )}+ </div>+ {branch.commit && (+ <div className="branch-commit">+ <code>{branch.commit.sha?.slice(0, 7)}</code>+ <span className="commit-date">+ {formatDate(branch.commit.date)}+ </span>+ </div>+ )}+ </div>+ <button+ className="btn btn-sm btn-ghost"+ onClick={() => changeBranch(branch.name)}+ >+ Switch+ </button>+ </div>+ ))}+ </div>+ )}+ </div>+ </div>+ )}+ </div>+ )}+{activeTab === 'access' && (<div className="access-tab"><div className="info-card">@@ -397,6 +1125,242 @@ function Git() {</div>)}+ {activeTab === 'webhooks' && (+ <div className="webhooks-tab">+ <div className="webhooks-header">+ <div>+ <h3>External Repository Webhooks</h3>+ <p className="text-muted">Sync repositories from GitHub, GitLab, or Bitbucket</p>+ </div>+ <button+ className="btn btn-primary"+ onClick={() => setShowWebhookModal(true)}+ >+ Add Webhook+ </button>+ </div>++ {webhooksLoading ? (+ <div className="loading-state">+ <Spinner />+ </div>+ ) : webhooks.length === 0 ? (+ <div className="empty-state">+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1.5">+ <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/>+ <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/>+ </svg>+ <h4>No Webhooks Configured</h4>+ <p>Add a webhook to sync repositories from external sources</p>+ <button+ className="btn btn-primary"+ onClick={() => setShowWebhookModal(true)}+ >+ Add Your First Webhook+ </button>+ </div>+ ) : (+ <div className="webhooks-list">+ {webhooks.map((webhook) => (+ <div key={webhook.id} className={`webhook-card ${!webhook.is_active ? 'inactive' : ''}`}>+ <div className="webhook-header">+ <div className="webhook-info">+ <span className={`source-badge ${webhook.source}`}>+ {webhook.source}+ </span>+ <h4>{webhook.name}</h4>+ </div>+ <div className="webhook-status">+ <span className={`status-dot ${webhook.is_active ? 'active' : 'inactive'}`}></span>+ {webhook.is_active ? 'Active' : 'Inactive'}+ </div>+ </div>++ <div className="webhook-details">+ <div className="detail-item">+ <span className="label">Repository:</span>+ <span className="value">{webhook.source_repo_url}</span>+ </div>+ <div className="detail-item">+ <span className="label">Branch:</span>+ <span className="value">{webhook.source_branch}</span>+ </div>+ <div className="detail-item">+ <span className="label">Last Sync:</span>+ <span className="value">+ {webhook.last_sync_at+ ? new Date(webhook.last_sync_at).toLocaleString()+ : 'Never'}+ </span>+ </div>+ <div className="detail-item">+ <span className="label">Sync Count:</span>+ <span className="value">{webhook.sync_count}</span>+ </div>+ </div>++ <div className="webhook-actions">+ <button+ className="btn btn-sm btn-secondary"+ onClick={() => copyWebhookUrl(webhook)}+ title="Copy webhook URL"+ >+ Copy URL+ </button>+ <button+ className="btn btn-sm btn-secondary"+ onClick={() => handleTestWebhook(webhook.id)}+ title="Test webhook"+ >+ Test+ </button>+ <button+ className={`btn btn-sm ${webhook.is_active ? 'btn-warning' : 'btn-primary'}`}+ onClick={() => handleToggleWebhook(webhook.id)}+ >+ {webhook.is_active ? 'Disable' : 'Enable'}+ </button>+ <button+ className="btn btn-sm btn-danger"+ onClick={() => handleDeleteWebhook(webhook.id)}+ >+ Delete+ </button>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}++ {activeTab === 'deployments' && (+ <div className="deployments-tab">+ <div className="deployments-header">+ <div>+ <h3>Deployment History</h3>+ <p className="text-muted">Track automatic and manual deployments</p>+ </div>+ <button+ className="btn btn-secondary"+ onClick={loadAllDeployments}+ disabled={deploymentsLoading}+ >+ Refresh+ </button>+ </div>++ {deploymentsLoading ? (+ <div className="loading-state">+ <Spinner />+ </div>+ ) : deployments.length === 0 ? (+ <div className="empty-state">+ <svg viewBox="0 0 24 24" width="48" height="48" stroke="currentColor" fill="none" strokeWidth="1.5">+ <path d="M12 2L2 7l10 5 10-5-10-5z"/>+ <path d="M2 17l10 5 10-5"/>+ <path d="M2 12l10 5 10-5"/>+ </svg>+ <h4>No Deployments Yet</h4>+ <p>Configure a webhook with "Deploy on Push" enabled to see deployments here</p>+ <button+ className="btn btn-primary"+ onClick={() => setActiveTab('webhooks')}+ >+ Configure Webhooks+ </button>+ </div>+ ) : (+ <div className="deployments-list">+ {deployments.map((deployment) => (+ <div key={deployment.id} className={`deployment-card ${deployment.status}`}>+ <div className="deployment-header">+ <div className="deployment-version">+ <span className="version">v{deployment.version}</span>+ {deployment.is_rollback && (+ <span className="badge rollback">Rollback</span>+ )}+ <span className={`status-badge ${deployment.status}`}>+ {deployment.status}+ </span>+ </div>+ <div className="deployment-time">+ {formatDate(deployment.created_at)}+ </div>+ </div>++ <div className="deployment-details">+ {deployment.commit_sha && (+ <div className="detail-item">+ <span className="label">Commit:</span>+ <code>{deployment.commit_sha.slice(0, 7)}</code>+ </div>+ )}+ {deployment.commit_message && (+ <div className="detail-item commit-message">+ <span className="message">{deployment.commit_message.split('\n')[0]}</span>+ </div>+ )}+ <div className="detail-item">+ <span className="label">Branch:</span>+ <span className="value">{deployment.branch}</span>+ </div>+ <div className="detail-item">+ <span className="label">Triggered by:</span>+ <span className="value">{deployment.triggered_by}</span>+ </div>+ {deployment.webhook_name && (+ <div className="detail-item">+ <span className="label">Webhook:</span>+ <span className="value">{deployment.webhook_name}</span>+ </div>+ )}+ {deployment.duration_seconds != null && (+ <div className="detail-item">+ <span className="label">Duration:</span>+ <span className="value">{deployment.duration_seconds}s</span>+ </div>+ )}+ {deployment.error_message && (+ <div className="detail-item error">+ <span className="label">Error:</span>+ <span className="value">{deployment.error_message}</span>+ </div>+ )}+ </div>++ <div className="deployment-actions">+ <button+ className="btn btn-sm btn-secondary"+ onClick={() => viewDeploymentLogs(deployment.id)}+ >+ View Logs+ </button>+ {deployment.status === 'success' && !deployment.is_rollback && (+ <button+ className="btn btn-sm btn-warning"+ onClick={() => handleRollback(deployment.app_id, deployment.version)}+ >+ Rollback to This+ </button>+ )}+ {deployment.status === 'success' && (+ <button+ className="btn btn-sm btn-primary"+ onClick={() => handleTriggerDeploy(deployment.app_id)}+ disabled={deployingAppId === deployment.app_id}+ >+ {deployingAppId === deployment.app_id ? 'Deploying...' : 'Redeploy'}+ </button>+ )}+ </div>+ </div>+ ))}+ </div>+ )}+ </div>+ )}+{activeTab === 'settings' && (<div className="settings-tab"><div className="info-card">@@ -510,6 +1474,310 @@ function Git() {</div>)}+ {/* Webhook Modal */}+ {showWebhookModal && (+ <div className="modal-overlay" onClick={() => setShowWebhookModal(false)}>+ <div className="modal modal-lg" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Add Webhook</h2>+ <button className="btn btn-icon" onClick={() => setShowWebhookModal(false)}>+ <span className="icon">close</span>+ </button>+ </div>+ <div className="modal-body">+ <div className="form-group">+ <label>Name <span className="required">*</span></label>+ <input+ type="text"+ value={webhookForm.name}+ onChange={(e) => setWebhookForm({ ...webhookForm, name: e.target.value })}+ placeholder="My GitHub Repo"+ />+ </div>++ <div className="form-group">+ <label>Source</label>+ <select+ value={webhookForm.source}+ onChange={(e) => setWebhookForm({ ...webhookForm, source: e.target.value })}+ >+ <option value="github">GitHub</option>+ <option value="gitlab">GitLab</option>+ <option value="bitbucket">Bitbucket</option>+ </select>+ </div>++ <div className="form-group">+ <label>Repository URL <span className="required">*</span></label>+ <input+ type="text"+ value={webhookForm.sourceRepoUrl}+ onChange={(e) => setWebhookForm({ ...webhookForm, sourceRepoUrl: e.target.value })}+ placeholder="https://github.com/user/repo.git"+ />+ </div>++ <div className="form-row">+ <div className="form-group">+ <label>Branch</label>+ <input+ type="text"+ value={webhookForm.sourceBranch}+ onChange={(e) => setWebhookForm({ ...webhookForm, sourceBranch: e.target.value })}+ placeholder="main"+ />+ </div>++ <div className="form-group">+ <label>Sync Direction</label>+ <select+ value={webhookForm.syncDirection}+ onChange={(e) => setWebhookForm({ ...webhookForm, syncDirection: e.target.value })}+ >+ <option value="pull">Pull (External → Local)</option>+ <option value="push">Push (Local → External)</option>+ <option value="bidirectional">Bidirectional</option>+ </select>+ </div>+ </div>++ <div className="form-group">+ <label>Local Repository Name (optional)</label>+ <input+ type="text"+ value={webhookForm.localRepoName}+ onChange={(e) => setWebhookForm({ ...webhookForm, localRepoName: e.target.value })}+ placeholder="Leave empty to use same name"+ />+ </div>++ <div className="form-group checkbox">+ <label>+ <input+ type="checkbox"+ checked={webhookForm.autoSync}+ onChange={(e) => setWebhookForm({ ...webhookForm, autoSync: e.target.checked })}+ />+ Auto-sync on push events+ </label>+ </div>++ <div className="form-section">+ <h4>Deployment Settings</h4>+ <p className="text-muted">Optionally deploy an application when code is pushed</p>++ <div className="form-group">+ <label>Deploy to Application</label>+ <select+ value={webhookForm.appId}+ onChange={(e) => setWebhookForm({+ ...webhookForm,+ appId: e.target.value,+ deployOnPush: e.target.value ? webhookForm.deployOnPush : false+ })}+ >+ <option value="">None (sync only)</option>+ {applications.map((app) => (+ <option key={app.id} value={app.id}>+ {app.name} ({app.status})+ </option>+ ))}+ </select>+ </div>++ {webhookForm.appId && (+ <>+ <div className="form-group checkbox">+ <label>+ <input+ type="checkbox"+ checked={webhookForm.deployOnPush}+ onChange={(e) => setWebhookForm({ ...webhookForm, deployOnPush: e.target.checked })}+ />+ Deploy on push+ </label>+ <span className="form-hint">Automatically deploy when code is pushed to the branch</span>+ </div>++ <div className="form-group checkbox">+ <label>+ <input+ type="checkbox"+ checked={webhookForm.zeroDowntime}+ onChange={(e) => setWebhookForm({ ...webhookForm, zeroDowntime: e.target.checked })}+ />+ Zero-downtime deployment+ </label>+ <span className="form-hint">Use rolling update to minimize downtime</span>+ </div>++ <div className="form-group">+ <label>Pre-deploy Script (optional)</label>+ <textarea+ value={webhookForm.preDeployScript}+ onChange={(e) => setWebhookForm({ ...webhookForm, preDeployScript: e.target.value })}+ placeholder="#!/bin/bash npm install"+ rows={3}+ />+ <span className="form-hint">Runs before pulling code (e.g., npm install, migrations)</span>+ </div>++ <div className="form-group">+ <label>Post-deploy Script (optional)</label>+ <textarea+ value={webhookForm.postDeployScript}+ onChange={(e) => setWebhookForm({ ...webhookForm, postDeployScript: e.target.value })}+ placeholder="#!/bin/bash npm run cache:clear"+ rows={3}+ />+ <span className="form-hint">Runs after deployment completes (e.g., cache clear)</span>+ </div>+ </>+ )}+ </div>+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => setShowWebhookModal(false)}>+ Cancel+ </button>+ <button+ className="btn btn-primary"+ onClick={handleCreateWebhook}+ disabled={actionLoading || !webhookForm.name || !webhookForm.sourceRepoUrl}+ >+ {actionLoading ? 'Creating...' : 'Create Webhook'}+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Webhook Secret Modal */}+ {webhookSecret && (+ <div className="modal-overlay" onClick={() => setWebhookSecret(null)}>+ <div className="modal" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Webhook Secret</h2>+ <button className="btn btn-icon" onClick={() => setWebhookSecret(null)}>+ <span className="icon">close</span>+ </button>+ </div>+ <div className="modal-body">+ <div className="secret-warning">+ <svg viewBox="0 0 24 24" width="20" height="20" stroke="currentColor" fill="none" strokeWidth="2">+ <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>+ <line x1="12" y1="9" x2="12" y2="13"/>+ <line x1="12" y1="17" x2="12.01" y2="17"/>+ </svg>+ <span>Save this secret! It will not be shown again.</span>+ </div>+ <div className="secret-display">+ <code>{webhookSecret}</code>+ <button+ className="btn btn-sm btn-secondary"+ onClick={() => {+ navigator.clipboard.writeText(webhookSecret);+ toast.success('Secret copied to clipboard');+ }}+ >+ Copy+ </button>+ </div>+ <p className="text-muted">+ Use this secret when configuring the webhook in your repository settings.+ </p>+ </div>+ <div className="modal-footer">+ <button className="btn btn-primary" onClick={() => setWebhookSecret(null)}>+ I've Saved It+ </button>+ </div>+ </div>+ </div>+ )}++ {/* Deployment Logs Modal */}+ {showDeploymentLogs && selectedDeployment && (+ <div className="modal-overlay" onClick={() => setShowDeploymentLogs(false)}>+ <div className="modal modal-xl" onClick={(e) => e.stopPropagation()}>+ <div className="modal-header">+ <h2>Deployment v{selectedDeployment.version} Logs</h2>+ <button className="btn btn-icon" onClick={() => setShowDeploymentLogs(false)}>+ <span className="icon">close</span>+ </button>+ </div>+ <div className="modal-body">+ <div className="deployment-summary">+ <div className="summary-item">+ <span className="label">Status:</span>+ <span className={`status-badge ${selectedDeployment.status}`}>+ {selectedDeployment.status}+ </span>+ </div>+ {selectedDeployment.commit_sha && (+ <div className="summary-item">+ <span className="label">Commit:</span>+ <code>{selectedDeployment.commit_sha.slice(0, 7)}</code>+ </div>+ )}+ <div className="summary-item">+ <span className="label">Branch:</span>+ <span>{selectedDeployment.branch}</span>+ </div>+ <div className="summary-item">+ <span className="label">Triggered by:</span>+ <span>{selectedDeployment.triggered_by}</span>+ </div>+ {selectedDeployment.duration_seconds != null && (+ <div className="summary-item">+ <span className="label">Duration:</span>+ <span>{selectedDeployment.duration_seconds}s</span>+ </div>+ )}+ </div>++ {selectedDeployment.error_message && (+ <div className="deployment-error">+ <strong>Error:</strong> {selectedDeployment.error_message}+ </div>+ )}++ {selectedDeployment.pre_script_output && (+ <div className="log-section">+ <h4>Pre-deployment Script Output</h4>+ <pre className="log-output">{selectedDeployment.pre_script_output}</pre>+ </div>+ )}++ {selectedDeployment.deploy_output && (+ <div className="log-section">+ <h4>Deployment Output</h4>+ <pre className="log-output">{selectedDeployment.deploy_output}</pre>+ </div>+ )}++ {selectedDeployment.post_script_output && (+ <div className="log-section">+ <h4>Post-deployment Script Output</h4>+ <pre className="log-output">{selectedDeployment.post_script_output}</pre>+ </div>+ )}++ {!selectedDeployment.pre_script_output && !selectedDeployment.deploy_output && !selectedDeployment.post_script_output && (+ <div className="no-logs">+ <p>No deployment logs available.</p>+ </div>+ )}+ </div>+ <div className="modal-footer">+ <button className="btn btn-secondary" onClick={() => setShowDeploymentLogs(false)}>+ Close+ </button>+ </div>+ </div>+ </div>+ )}+{/* Confirm Dialog */}{confirmDialog && (<ConfirmDialogdiff --git a/frontend/src/services/api.js b/frontend/src/services/api.jsindex fbfd97ab..705ffee7 100644--- a/frontend/src/services/api.js+++ b/frontend/src/services/api.js@@ -1905,6 +1905,123 @@ class ApiService {return this.request('/git/restart', { method: 'POST' });}+ // Git Webhooks+ async getWebhooks() {+ return this.request('/git/webhooks');+ }++ async getWebhook(webhookId) {+ return this.request(`/git/webhooks/${webhookId}`);+ }++ async createWebhook(data) {+ return this.request('/git/webhooks', {+ method: 'POST',+ body: data+ });+ }++ async updateWebhook(webhookId, data) {+ return this.request(`/git/webhooks/${webhookId}`, {+ method: 'PUT',+ body: data+ });+ }++ async deleteWebhook(webhookId) {+ return this.request(`/git/webhooks/${webhookId}`, { method: 'DELETE' });+ }++ async toggleWebhook(webhookId) {+ return this.request(`/git/webhooks/${webhookId}/toggle`, { method: 'POST' });+ }++ async getWebhookLogs(webhookId, limit = 50) {+ return this.request(`/git/webhooks/${webhookId}/logs?limit=${limit}`);+ }++ async testWebhook(webhookId) {+ return this.request(`/git/webhooks/${webhookId}/test`, { method: 'POST' });+ }++ // Git Repositories+ async getRepositories(limit = 50) {+ return this.request(`/git/repos?limit=${limit}`);+ }++ async getRepository(owner, repo) {+ return this.request(`/git/repos/${owner}/${repo}`);+ }++ async getRepoStats(owner, repo) {+ return this.request(`/git/repos/${owner}/${repo}/stats`);+ }++ async getBranches(owner, repo) {+ return this.request(`/git/repos/${owner}/${repo}/branches`);+ }++ async getBranch(owner, repo, branch) {+ return this.request(`/git/repos/${owner}/${repo}/branches/${branch}`);+ }++ async getCommits(owner, repo, branch = null, page = 1, limit = 30) {+ let url = `/git/repos/${owner}/${repo}/commits?page=${page}&limit=${limit}`;+ if (branch) url += `&branch=${branch}`;+ return this.request(url);+ }++ async getCommit(owner, repo, sha) {+ return this.request(`/git/repos/${owner}/${repo}/commits/${sha}`);+ }++ async getRepoFiles(owner, repo, ref = 'main', path = '') {+ let url = `/git/repos/${owner}/${repo}/contents?ref=${ref}`;+ if (path) url += `&path=${path}`;+ return this.request(url);+ }++ async getFileContent(owner, repo, filepath, ref = 'main') {+ return this.request(`/git/repos/${owner}/${repo}/contents/${filepath}?ref=${ref}`);+ }++ async getRepoReadme(owner, repo, ref = null) {+ let url = `/git/repos/${owner}/${repo}/readme`;+ if (ref) url += `?ref=${ref}`;+ return this.request(url);+ }++ async getGiteaVersion() {+ return this.request('/git/version');+ }++ // Git Deployments+ async getAppDeployments(appId, limit = 20) {+ return this.request(`/git/deployments/app/${appId}?limit=${limit}`);+ }++ async getDeployment(deploymentId, includeLogs = false) {+ return this.request(`/git/deployments/${deploymentId}?logs=${includeLogs}`);+ }++ async triggerDeploy(appId, branch = null) {+ return this.request(`/git/deployments/app/${appId}/deploy`, {+ method: 'POST',+ body: branch ? { branch } : {}+ });+ }++ async rollbackDeployment(appId, targetVersion = null) {+ return this.request(`/git/deployments/app/${appId}/rollback`, {+ method: 'POST',+ body: targetVersion ? { targetVersion } : {}+ });+ }++ async getWebhookDeployments(webhookId, limit = 20) {+ return this.request(`/git/deployments/webhook/${webhookId}?limit=${limit}`);+ }+// ========================================// Cron Job endpoints// ========================================diff --git a/frontend/src/styles/pages/_git.less b/frontend/src/styles/pages/_git.lessindex 5c6db17b..36563561 100644--- a/frontend/src/styles/pages/_git.less+++ b/frontend/src/styles/pages/_git.less@@ -434,4 +434,1036 @@.required {color: @danger;}++ // Webhooks Tab+ .webhooks-tab {+ .webhooks-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ margin-bottom: @space-5;++ h3 {+ margin: 0 0 @space-1 0;+ font-size: @font-size-md;+ font-weight: @font-weight-semibold;+ }++ .text-muted {+ color: @text-secondary;+ font-size: @font-size-sm;+ margin: 0;+ }+ }++ .loading-state {+ display: flex;+ justify-content: center;+ padding: @space-10;+ }++ .empty-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: @space-10;+ background: @bg-card;+ border-radius: @radius-xl;+ text-align: center;++ svg {+ color: @text-tertiary;+ margin-bottom: @space-4;+ }++ h4 {+ margin: 0 0 @space-2 0;+ font-size: @font-size-lg;+ font-weight: @font-weight-semibold;+ }++ p {+ margin: 0 0 @space-5 0;+ color: @text-secondary;+ }+ }++ .webhooks-list {+ display: flex;+ flex-direction: column;+ gap: @space-4;+ }++ .webhook-card {+ background: @bg-card;+ border-radius: @radius-lg;+ padding: @space-5;+ border: 1px solid @border-subtle;+ transition: border-color @transition-fast;++ &:hover {+ border-color: @border-default;+ }++ &.inactive {+ opacity: 0.7;+ background: @bg-hover;+ }++ .webhook-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @space-4;++ .webhook-info {+ display: flex;+ align-items: center;+ gap: @space-3;++ h4 {+ margin: 0;+ font-size: @font-size-md;+ font-weight: @font-weight-semibold;+ }+ }++ .webhook-status {+ display: flex;+ align-items: center;+ gap: @space-2;+ font-size: @font-size-sm;+ color: @text-secondary;++ .status-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: @text-tertiary;++ &.active {+ background: @success;+ }++ &.inactive {+ background: @text-tertiary;+ }+ }+ }+ }++ .webhook-details {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));+ gap: @space-3;+ margin-bottom: @space-4;+ padding: @space-4;+ background: @bg-hover;+ border-radius: @radius-md;++ .detail-item {+ display: flex;+ flex-direction: column;+ gap: @space-1;++ .label {+ font-size: @font-size-xs;+ color: @text-tertiary;+ text-transform: uppercase;+ letter-spacing: 0.5px;+ }++ .value {+ font-size: @font-size-sm;+ color: @text-primary;+ word-break: break-all;+ }+ }+ }++ .webhook-actions {+ display: flex;+ gap: @space-2;+ flex-wrap: wrap;+ }+ }++ .source-badge {+ display: inline-flex;+ align-items: center;+ padding: @space-1 @space-2;+ border-radius: @radius-md;+ font-size: @font-size-xs;+ font-weight: @font-weight-medium;+ text-transform: uppercase;++ &.github {+ background: fade(#333, 15%);+ color: #333;++ @media (prefers-color-scheme: dark) {+ background: fade(#f0f0f0, 15%);+ color: #f0f0f0;+ }+ }++ &.gitlab {+ background: fade(#fc6d26, 15%);+ color: #fc6d26;+ }++ &.bitbucket {+ background: fade(#0052cc, 15%);+ color: #0052cc;+ }+ }+ }++ // Webhook Modal+ .form-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: @space-4;++ @media (max-width: @breakpoint-sm) {+ grid-template-columns: 1fr;+ }+ }++ .form-group.checkbox {+ label {+ display: flex;+ align-items: center;+ gap: @space-2;+ cursor: pointer;+ font-weight: @font-weight-normal;++ input[type="checkbox"] {+ width: 18px;+ height: 18px;+ cursor: pointer;+ }+ }+ }++ // Secret Display+ .secret-warning {+ display: flex;+ align-items: center;+ gap: @space-3;+ padding: @space-4;+ background: fade(@warning, 15%);+ border: 1px solid fade(@warning, 30%);+ border-radius: @radius-md;+ margin-bottom: @space-4;++ svg {+ color: @warning;+ flex-shrink: 0;+ }++ span {+ font-weight: @font-weight-medium;+ }+ }++ .secret-display {+ display: flex;+ align-items: center;+ gap: @space-3;+ padding: @space-4;+ background: @bg-hover;+ border-radius: @radius-md;+ margin-bottom: @space-4;++ code {+ flex: 1;+ font-family: @font-mono;+ font-size: @font-size-sm;+ word-break: break-all;+ }+ }++ // Repositories Tab+ .repositories-tab {+ .repos-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @space-5;++ h3 {+ margin: 0;+ font-size: @font-size-md;+ font-weight: @font-weight-semibold;+ }+ }++ .loading-state {+ display: flex;+ justify-content: center;+ padding: @space-10;+ }++ .empty-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: @space-10;+ background: @bg-card;+ border-radius: @radius-xl;+ text-align: center;++ svg {+ color: @text-tertiary;+ margin-bottom: @space-4;+ }++ h4 {+ margin: 0 0 @space-2 0;+ font-size: @font-size-lg;+ font-weight: @font-weight-semibold;+ }++ p {+ margin: 0 0 @space-5 0;+ color: @text-secondary;+ }+ }++ .repos-list {+ display: flex;+ flex-direction: column;+ gap: @space-3;+ }++ .repo-card {+ display: flex;+ align-items: center;+ padding: @space-4;+ background: @bg-card;+ border-radius: @radius-lg;+ border: 1px solid @border-subtle;+ cursor: pointer;+ transition: all @transition-fast;++ &:hover {+ border-color: @accent-primary;+ background: @bg-hover;++ .repo-arrow {+ color: @accent-primary;+ }+ }++ .repo-info {+ flex: 1;+ min-width: 0;++ .repo-name {+ display: flex;+ align-items: center;+ gap: @space-2;+ margin-bottom: @space-2;++ .owner {+ color: @text-secondary;+ }++ .name {+ font-weight: @font-weight-semibold;+ }++ .badge {+ padding: 2px @space-2;+ border-radius: @radius-sm;+ font-size: @font-size-xs;+ font-weight: @font-weight-medium;++ &.private {+ background: fade(@warning, 20%);+ color: @warning;+ }++ &.fork {+ background: fade(@info, 20%);+ color: @info;+ }+ }+ }++ .repo-description {+ margin: 0 0 @space-2 0;+ font-size: @font-size-sm;+ color: @text-secondary;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .repo-meta {+ display: flex;+ align-items: center;+ gap: @space-4;+ font-size: @font-size-xs;+ color: @text-tertiary;++ .meta-item {+ display: flex;+ align-items: center;+ gap: @space-1;++ svg {+ opacity: 0.6;+ }++ &.updated {+ margin-left: auto;+ }+ }+ }+ }++ .repo-arrow {+ color: @text-tertiary;+ transition: color @transition-fast;+ }+ }++ // Repository Detail View+ .repo-detail {+ .repo-detail-header {+ display: flex;+ align-items: flex-start;+ gap: @space-4;+ margin-bottom: @space-5;+ padding-bottom: @space-4;+ border-bottom: 1px solid @border-subtle;++ .btn-ghost {+ padding: @space-2;+ }++ .repo-title {+ flex: 1;++ h3 {+ margin: 0 0 @space-1 0;+ font-size: @font-size-lg;+ font-weight: @font-weight-semibold;+ }++ p {+ margin: 0;+ font-size: @font-size-sm;+ color: @text-secondary;+ }+ }++ .branch-selector {+ select {+ padding: @space-2 @space-4;+ background: @bg-card;+ border: 1px solid @border-default;+ border-radius: @radius-md;+ font-size: @font-size-sm;+ color: @text-primary;+ cursor: pointer;++ &:focus {+ outline: none;+ border-color: @accent-primary;+ }+ }+ }+ }++ .repo-detail-tabs {+ display: flex;+ gap: @space-1;+ margin-bottom: @space-4;+ border-bottom: 1px solid @border-subtle;++ .tab {+ display: flex;+ align-items: center;+ gap: @space-2;+ padding: @space-3 @space-4;+ background: none;+ border: none;+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ color: @text-secondary;+ cursor: pointer;+ position: relative;+ transition: color @transition-fast;++ &:hover {+ color: @text-primary;+ }++ &.active {+ color: @accent-primary;++ &::after {+ content: '';+ position: absolute;+ bottom: -1px;+ left: 0;+ right: 0;+ height: 2px;+ background: @accent-primary;+ }+ }+ }+ }++ .repo-detail-content {+ background: @bg-card;+ border-radius: @radius-lg;+ border: 1px solid @border-subtle;+ }+ }++ // Files Browser+ .files-browser {+ .breadcrumb {+ display: flex;+ align-items: center;+ padding: @space-3 @space-4;+ background: @bg-hover;+ border-bottom: 1px solid @border-subtle;+ font-size: @font-size-sm;++ button {+ background: none;+ border: none;+ color: @accent-primary;+ cursor: pointer;+ padding: 0;++ &:hover {+ text-decoration: underline;+ }+ }++ .separator {+ margin: 0 @space-2;+ color: @text-tertiary;+ }+ }++ .files-list {+ .file-item {+ display: flex;+ align-items: center;+ gap: @space-3;+ padding: @space-3 @space-4;+ border-bottom: 1px solid @border-subtle;+ transition: background @transition-fast;++ &:last-child {+ border-bottom: none;+ }++ &.dir {+ cursor: pointer;++ &:hover {+ background: @bg-hover;+ }+ }++ .file-icon {+ color: @text-tertiary;+ }++ &.dir .file-icon svg {+ color: @info;+ }++ .file-name {+ flex: 1;+ font-size: @font-size-sm;+ }++ .file-size {+ font-size: @font-size-xs;+ color: @text-tertiary;+ font-family: @font-mono;+ }+ }+ }+ }++ // Commits List+ .commits-list {+ .commit-item {+ display: flex;+ align-items: flex-start;+ gap: @space-4;+ padding: @space-4;+ border-bottom: 1px solid @border-subtle;++ &:last-child {+ border-bottom: none;+ }++ .commit-info {+ flex: 1;+ min-width: 0;++ .commit-message {+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ margin-bottom: @space-1;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .commit-meta {+ font-size: @font-size-xs;+ color: @text-tertiary;++ .author {+ color: @text-secondary;+ margin-right: @space-2;+ }+ }+ }++ .commit-sha {+ code {+ padding: @space-1 @space-2;+ background: @bg-hover;+ border-radius: @radius-sm;+ font-size: @font-size-xs;+ font-family: @font-mono;+ color: @accent-primary;+ }+ }+ }++ .btn-block {+ width: 100%;+ margin: @space-4;+ width: calc(100% - @space-8);+ }+ }++ // Branches List+ .branches-list {+ .branch-item {+ display: flex;+ align-items: center;+ gap: @space-4;+ padding: @space-4;+ border-bottom: 1px solid @border-subtle;++ &:last-child {+ border-bottom: none;+ }++ &.active {+ background: fade(@accent-primary, 5%);+ }++ .branch-info {+ flex: 1;++ .branch-name {+ display: flex;+ align-items: center;+ gap: @space-2;+ font-size: @font-size-sm;+ font-weight: @font-weight-medium;+ margin-bottom: @space-1;++ svg {+ color: @text-tertiary;+ }++ .badge {+ padding: 2px @space-2;+ border-radius: @radius-sm;+ font-size: @font-size-xs;+ font-weight: @font-weight-medium;++ &.default {+ background: fade(@success, 20%);+ color: @success;+ }++ &.protected {+ background: fade(@warning, 20%);+ color: @warning;+ }+ }+ }++ .branch-commit {+ font-size: @font-size-xs;+ color: @text-tertiary;++ code {+ color: @accent-primary;+ margin-right: @space-2;+ }+ }+ }+ }+ }+ }++ // Deployments Tab+ .deployments-tab {+ .deployments-header {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ margin-bottom: @space-5;++ h3 {+ margin: 0 0 @space-1 0;+ font-size: @font-size-md;+ font-weight: @font-weight-semibold;+ }++ .text-muted {+ color: @text-secondary;+ font-size: @font-size-sm;+ margin: 0;+ }+ }++ .loading-state {+ display: flex;+ justify-content: center;+ padding: @space-10;+ }++ .empty-state {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ padding: @space-10;+ background: @bg-card;+ border-radius: @radius-xl;+ text-align: center;++ svg {+ color: @text-tertiary;+ margin-bottom: @space-4;+ }++ h4 {+ margin: 0 0 @space-2 0;+ font-size: @font-size-lg;+ font-weight: @font-weight-semibold;+ }++ p {+ margin: 0 0 @space-5 0;+ color: @text-secondary;+ }+ }++ .deployments-list {+ display: flex;+ flex-direction: column;+ gap: @space-4;+ }++ .deployment-card {+ background: @bg-card;+ border-radius: @radius-lg;+ padding: @space-5;+ border: 1px solid @border-subtle;+ border-left: 4px solid @border-subtle;++ &.success {+ border-left-color: @success;+ }++ &.failed {+ border-left-color: @danger;+ }++ &.running {+ border-left-color: @warning;+ }++ .deployment-header {+ display: flex;+ justify-content: space-between;+ align-items: center;+ margin-bottom: @space-4;++ .deployment-version {+ display: flex;+ align-items: center;+ gap: @space-3;++ .version {+ font-size: @font-size-lg;+ font-weight: @font-weight-semibold;+ }++ .badge {+ padding: 2px @space-2;+ border-radius: @radius-sm;+ font-size: @font-size-xs;+ font-weight: @font-weight-medium;++ &.rollback {+ background: fade(@info, 20%);+ color: @info;+ }+ }++ .status-badge {+ padding: @space-1 @space-2;+ border-radius: @radius-md;+ font-size: @font-size-xs;+ font-weight: @font-weight-medium;+ text-transform: uppercase;++ &.success {+ background: fade(@success, 15%);+ color: @success;+ }++ &.failed {+ background: fade(@danger, 15%);+ color: @danger;+ }++ &.running {+ background: fade(@warning, 15%);+ color: @warning;+ }+ }+ }++ .deployment-time {+ font-size: @font-size-sm;+ color: @text-tertiary;+ }+ }++ .deployment-details {+ display: grid;+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));+ gap: @space-3;+ margin-bottom: @space-4;+ padding: @space-4;+ background: @bg-hover;+ border-radius: @radius-md;++ .detail-item {+ display: flex;+ align-items: center;+ gap: @space-2;+ font-size: @font-size-sm;++ .label {+ color: @text-tertiary;+ }++ .value {+ color: @text-primary;+ }++ code {+ padding: 2px @space-2;+ background: @bg-card;+ border-radius: @radius-sm;+ font-size: @font-size-xs;+ font-family: @font-mono;+ color: @accent-primary;+ }++ &.commit-message {+ grid-column: 1 / -1;++ .message {+ color: @text-secondary;+ font-style: italic;+ }+ }++ &.error {+ grid-column: 1 / -1;+ color: @danger;++ .value {+ color: @danger;+ }+ }+ }+ }++ .deployment-actions {+ display: flex;+ gap: @space-2;+ flex-wrap: wrap;+ }+ }+ }++ // Form section for webhook modal+ .form-section {+ margin-top: @space-5;+ padding-top: @space-5;+ border-top: 1px solid @border-subtle;++ h4 {+ margin: 0 0 @space-1 0;+ font-size: @font-size-base;+ font-weight: @font-weight-semibold;+ }++ .text-muted {+ color: @text-secondary;+ font-size: @font-size-sm;+ margin: 0 0 @space-4 0;+ }+ }++ .form-hint {+ display: block;+ font-size: @font-size-xs;+ color: @text-tertiary;+ margin-top: @space-1;+ }++ .form-group textarea {+ width: 100%;+ min-height: 80px;+ padding: @space-3;+ font-family: @font-mono;+ font-size: @font-size-sm;+ background: @bg-elevated;+ border: 1px solid @border-default;+ border-radius: @radius-md;+ color: @text-primary;+ resize: vertical;++ &:focus {+ outline: none;+ border-color: @accent-primary;+ }++ &::placeholder {+ color: @text-tertiary;+ }+ }++ // Modal XL size+ .modal-xl {+ max-width: 800px;+ }++ // Deployment Logs Modal+ .deployment-summary {+ display: flex;+ flex-wrap: wrap;+ gap: @space-4;+ padding: @space-4;+ background: @bg-hover;+ border-radius: @radius-md;+ margin-bottom: @space-4;++ .summary-item {+ display: flex;+ align-items: center;+ gap: @space-2;+ font-size: @font-size-sm;++ .label {+ color: @text-tertiary;+ }++ .status-badge {+ padding: @space-1 @space-2;+ border-radius: @radius-md;+ font-size: @font-size-xs;+ font-weight: @font-weight-medium;+ text-transform: uppercase;++ &.success {+ background: fade(@success, 15%);+ color: @success;+ }++ &.failed {+ background: fade(@danger, 15%);+ color: @danger;+ }++ &.running {+ background: fade(@warning, 15%);+ color: @warning;+ }+ }++ code {+ padding: 2px @space-2;+ background: @bg-card;+ border-radius: @radius-sm;+ font-size: @font-size-xs;+ font-family: @font-mono;+ color: @accent-primary;+ }+ }+ }++ .deployment-error {+ padding: @space-4;+ background: fade(@danger, 10%);+ border: 1px solid fade(@danger, 30%);+ border-radius: @radius-md;+ margin-bottom: @space-4;+ color: @danger;+ font-size: @font-size-sm;++ strong {+ margin-right: @space-2;+ }+ }++ .log-section {+ margin-bottom: @space-4;++ h4 {+ margin: 0 0 @space-2 0;+ font-size: @font-size-sm;+ font-weight: @font-weight-semibold;+ color: @text-secondary;+ }++ .log-output {+ padding: @space-4;+ background: @bg-hover;+ border-radius: @radius-md;+ font-family: @font-mono;+ font-size: @font-size-xs;+ color: @text-primary;+ white-space: pre-wrap;+ word-break: break-all;+ max-height: 300px;+ overflow-y: auto;+ margin: 0;+ }+ }++ .no-logs {+ padding: @space-6;+ text-align: center;+ color: @text-tertiary;+ }}