FossilRepo

fossilrepo / fossil / tasks.py
Source Blame History 591 lines
4ce269c… ragelink 1 """Celery tasks for Fossil repository management."""
4ce269c… ragelink 2
4ce269c… ragelink 3 import hashlib
4ce269c… ragelink 4 import logging
4ce269c… ragelink 5
4ce269c… ragelink 6 from celery import shared_task
4ce269c… ragelink 7 from django.core.files.base import ContentFile
4ce269c… ragelink 8
4ce269c… ragelink 9 logger = logging.getLogger(__name__)
4ce269c… ragelink 10
4ce269c… ragelink 11
4ce269c… ragelink 12 @shared_task(name="fossil.sync_metadata")
4ce269c… ragelink 13 def sync_repository_metadata():
4ce269c… ragelink 14 """Update metadata for all FossilRepository records from disk."""
4ce269c… ragelink 15 from fossil.models import FossilRepository
4ce269c… ragelink 16 from fossil.reader import FossilReader
4ce269c… ragelink 17
4ce269c… ragelink 18 for repo in FossilRepository.objects.all():
4ce269c… ragelink 19 if not repo.exists_on_disk:
4ce269c… ragelink 20 continue
4ce269c… ragelink 21 try:
4ce269c… ragelink 22 repo.file_size_bytes = repo.full_path.stat().st_size
4ce269c… ragelink 23 with FossilReader(repo.full_path) as reader:
4ce269c… ragelink 24 repo.checkin_count = reader.get_checkin_count()
4ce269c… ragelink 25 timeline = reader.get_timeline(limit=1)
4ce269c… ragelink 26 if timeline:
4ce269c… ragelink 27 repo.last_checkin_at = timeline[0].timestamp
4ce269c… ragelink 28 repo.fossil_project_code = reader.get_project_code()
4ce269c… ragelink 29 repo.save(update_fields=["file_size_bytes", "checkin_count", "last_checkin_at", "fossil_project_code", "updated_at", "version"])
4ce269c… ragelink 30 except Exception:
4ce269c… ragelink 31 logger.exception("Failed to sync metadata for %s", repo.filename)
4ce269c… ragelink 32
4ce269c… ragelink 33
4ce269c… ragelink 34 @shared_task(name="fossil.create_snapshot")
4ce269c… ragelink 35 def create_snapshot(repository_id: int, note: str = ""):
4ce269c… ragelink 36 """Create a FossilSnapshot if FOSSIL_STORE_IN_DB is enabled."""
4ce269c… ragelink 37 from constance import config
4ce269c… ragelink 38
4ce269c… ragelink 39 if not config.FOSSIL_STORE_IN_DB:
4ce269c… ragelink 40 return
4ce269c… ragelink 41
4ce269c… ragelink 42 from fossil.models import FossilRepository, FossilSnapshot
4ce269c… ragelink 43
4ce269c… ragelink 44 try:
4ce269c… ragelink 45 repo = FossilRepository.objects.get(pk=repository_id)
4ce269c… ragelink 46 except FossilRepository.DoesNotExist:
4ce269c… ragelink 47 return
4ce269c… ragelink 48
4ce269c… ragelink 49 if not repo.exists_on_disk:
4ce269c… ragelink 50 return
4ce269c… ragelink 51
4ce269c… ragelink 52 data = repo.full_path.read_bytes()
4ce269c… ragelink 53 sha = hashlib.sha256(data).hexdigest()
4ce269c… ragelink 54
4ce269c… ragelink 55 # Skip if latest snapshot has same hash
4ce269c… ragelink 56 latest = repo.snapshots.first()
4ce269c… ragelink 57 if latest and latest.fossil_hash == sha:
4ce269c… ragelink 58 return
4ce269c… ragelink 59
4ce269c… ragelink 60 snapshot = FossilSnapshot(
4ce269c… ragelink 61 repository=repo,
4ce269c… ragelink 62 file_size_bytes=len(data),
4ce269c… ragelink 63 fossil_hash=sha,
4ce269c… ragelink 64 note=note,
4ce269c… ragelink 65 created_by=repo.created_by,
4ce269c… ragelink 66 )
4ce269c… ragelink 67 snapshot.file.save(f"{repo.filename}_{sha[:8]}.fossil", ContentFile(data), save=True)
4ce269c… ragelink 68 logger.info("Created snapshot for %s (hash: %s)", repo.filename, sha[:8])
4ce269c… ragelink 69
4ce269c… ragelink 70
4ce269c… ragelink 71 @shared_task(name="fossil.check_upstream")
4ce269c… ragelink 72 def check_upstream_updates():
4ce269c… ragelink 73 """Check all repos with remote URLs for available updates."""
4ce269c… ragelink 74 from fossil.cli import FossilCLI
4ce269c… ragelink 75 from fossil.models import FossilRepository
4ce269c… ragelink 76
4ce269c… ragelink 77 cli = FossilCLI()
4ce269c… ragelink 78 if not cli.is_available():
4ce269c… ragelink 79 return
4ce269c… ragelink 80
4ce269c… ragelink 81 from django.utils import timezone
4ce269c… ragelink 82
4ce269c… ragelink 83 for repo in FossilRepository.objects.exclude(remote_url=""):
4ce269c… ragelink 84 if not repo.exists_on_disk:
4ce269c… ragelink 85 continue
4ce269c… ragelink 86 try:
4ce269c… ragelink 87 result = cli.pull(repo.full_path)
4ce269c… ragelink 88 if result["success"] and result["artifacts_received"] > 0:
4ce269c… ragelink 89 repo.upstream_artifacts_available = result["artifacts_received"]
4ce269c… ragelink 90 repo.last_sync_at = timezone.now()
4ce269c… ragelink 91 # Update metadata after pull
4ce269c… ragelink 92 from fossil.reader import FossilReader
4ce269c… ragelink 93
4ce269c… ragelink 94 with FossilReader(repo.full_path) as reader:
4ce269c… ragelink 95 repo.checkin_count = reader.get_checkin_count()
4ce269c… ragelink 96 timeline = reader.get_timeline(limit=1, event_type="ci")
4ce269c… ragelink 97 if timeline:
4ce269c… ragelink 98 repo.last_checkin_at = timeline[0].timestamp
4ce269c… ragelink 99 repo.file_size_bytes = repo.full_path.stat().st_size
4ce269c… ragelink 100 repo.save(
4ce269c… ragelink 101 update_fields=[
4ce269c… ragelink 102 "upstream_artifacts_available",
4ce269c… ragelink 103 "last_sync_at",
4ce269c… ragelink 104 "checkin_count",
4ce269c… ragelink 105 "last_checkin_at",
4ce269c… ragelink 106 "file_size_bytes",
4ce269c… ragelink 107 "updated_at",
4ce269c… ragelink 108 "version",
4ce269c… ragelink 109 ]
4ce269c… ragelink 110 )
4ce269c… ragelink 111 logger.info("Pulled %d artifacts for %s (new count: %d)", result["artifacts_received"], repo.filename, repo.checkin_count)
4ce269c… ragelink 112 else:
4ce269c… ragelink 113 repo.upstream_artifacts_available = 0
4ce269c… ragelink 114 repo.last_sync_at = timezone.now()
4ce269c… ragelink 115 repo.save(update_fields=["upstream_artifacts_available", "last_sync_at", "updated_at", "version"])
4ce269c… ragelink 116 except Exception:
4ce269c… ragelink 117 logger.exception("Failed to check upstream for %s", repo.filename)
2eca4eb… ragelink 118
2eca4eb… ragelink 119
2eca4eb… ragelink 120 @shared_task(name="fossil.git_sync")
2eca4eb… ragelink 121 def run_git_sync(mirror_id: int | None = None):
2eca4eb… ragelink 122 """Run Git export/push for configured mirrors."""
2eca4eb… ragelink 123 from pathlib import Path
2eca4eb… ragelink 124
2eca4eb… ragelink 125 from constance import config
2eca4eb… ragelink 126 from django.utils import timezone
2eca4eb… ragelink 127
2eca4eb… ragelink 128 from fossil.cli import FossilCLI
2eca4eb… ragelink 129 from fossil.sync_models import GitMirror, SyncLog
2eca4eb… ragelink 130
2eca4eb… ragelink 131 cli = FossilCLI()
2eca4eb… ragelink 132 if not cli.is_available():
2eca4eb… ragelink 133 return
2eca4eb… ragelink 134
2eca4eb… ragelink 135 mirrors = GitMirror.objects.filter(deleted_at__isnull=True).exclude(sync_mode="disabled")
2eca4eb… ragelink 136 if mirror_id:
2eca4eb… ragelink 137 mirrors = mirrors.filter(pk=mirror_id)
2eca4eb… ragelink 138
2eca4eb… ragelink 139 mirror_dir = Path(config.GIT_MIRROR_DIR)
2eca4eb… ragelink 140
2eca4eb… ragelink 141 for mirror in mirrors:
2eca4eb… ragelink 142 repo = mirror.repository
2eca4eb… ragelink 143 if not repo.exists_on_disk:
2eca4eb… ragelink 144 continue
2eca4eb… ragelink 145
2eca4eb… ragelink 146 log = SyncLog.objects.create(mirror=mirror, triggered_by="schedule" if not mirror_id else "manual")
2eca4eb… ragelink 147
2eca4eb… ragelink 148 try:
2eca4eb… ragelink 149 # Ensure default user
2eca4eb… ragelink 150 cli.ensure_default_user(repo.full_path)
2eca4eb… ragelink 151
2eca4eb… ragelink 152 # Git export directory for this mirror
2eca4eb… ragelink 153 export_dir = mirror_dir / f"{repo.filename.replace('.fossil', '')}-git"
2eca4eb… ragelink 154
c588255… ragelink 155 # Pass clean URL and token separately -- never embed credentials in URLs
2eca4eb… ragelink 156 push_url = mirror.git_remote_url
c588255… ragelink 157 auth_token = ""
2eca4eb… ragelink 158 if mirror.auth_method == "token" and mirror.auth_credential and push_url.startswith("https://"):
c588255… ragelink 159 auth_token = mirror.auth_credential
2eca4eb… ragelink 160
c588255… ragelink 161 result = cli.git_export(repo.full_path, export_dir, autopush_url=push_url, auth_token=auth_token)
c588255… ragelink 162
c588255… ragelink 163 # Scrub any credential from output before persisting
c588255… ragelink 164 message = result.get("message", "")
c588255… ragelink 165 if mirror.auth_credential:
c588255… ragelink 166 message = message.replace(mirror.auth_credential, "[REDACTED]")
2eca4eb… ragelink 167
2eca4eb… ragelink 168 log.status = "success" if result["success"] else "failed"
c588255… ragelink 169 log.message = message
2eca4eb… ragelink 170 log.completed_at = timezone.now()
2eca4eb… ragelink 171 log.save()
2eca4eb… ragelink 172
2eca4eb… ragelink 173 mirror.last_sync_at = timezone.now()
2eca4eb… ragelink 174 mirror.last_sync_status = log.status
c588255… ragelink 175 mirror.last_sync_message = message[:500]
2eca4eb… ragelink 176 mirror.total_syncs += 1
2eca4eb… ragelink 177 mirror.save(
2eca4eb… ragelink 178 update_fields=[
2eca4eb… ragelink 179 "last_sync_at",
2eca4eb… ragelink 180 "last_sync_status",
2eca4eb… ragelink 181 "last_sync_message",
2eca4eb… ragelink 182 "total_syncs",
2eca4eb… ragelink 183 "updated_at",
2eca4eb… ragelink 184 "version",
2eca4eb… ragelink 185 ]
2eca4eb… ragelink 186 )
2eca4eb… ragelink 187
2eca4eb… ragelink 188 if result["success"]:
2eca4eb… ragelink 189 logger.info("Git sync success for %s → %s", repo.filename, mirror.git_remote_url)
0e40dc2… ragelink 190
0e40dc2… ragelink 191 # Chain ticket and wiki sync if enabled
0e40dc2… ragelink 192 if mirror.sync_tickets:
0e40dc2… ragelink 193 sync_tickets_to_github.delay(mirror.id)
0e40dc2… ragelink 194 if mirror.sync_wiki:
0e40dc2… ragelink 195 sync_wiki_to_github.delay(mirror.id)
2eca4eb… ragelink 196 else:
2eca4eb… ragelink 197 logger.warning("Git sync failed for %s: %s", repo.filename, result["message"][:200])
2eca4eb… ragelink 198
2eca4eb… ragelink 199 except Exception:
2eca4eb… ragelink 200 logger.exception("Git sync error for %s", repo.filename)
2eca4eb… ragelink 201 log.status = "failed"
2eca4eb… ragelink 202 log.message = "Unexpected error"
2eca4eb… ragelink 203 log.completed_at = timezone.now()
2eca4eb… ragelink 204 log.save()
c588255… ragelink 205
c588255… ragelink 206
c588255… ragelink 207 @shared_task(name="fossil.send_digest")
c588255… ragelink 208 def send_digest(mode="daily"):
c588255… ragelink 209 """Send digest emails to users who prefer batch delivery.
c588255… ragelink 210
c588255… ragelink 211 Collects unread notifications for users with the given delivery mode
c588255… ragelink 212 and sends a single summary email with HTML template. Marks those
c588255… ragelink 213 notifications as read after sending.
c588255… ragelink 214 """
c588255… ragelink 215 from django.conf import settings
c588255… ragelink 216 from django.core.mail import send_mail
c588255… ragelink 217 from django.template.loader import render_to_string
c588255… ragelink 218
c588255… ragelink 219 from fossil.notifications import Notification, NotificationPreference
c588255… ragelink 220
c588255… ragelink 221 prefs = NotificationPreference.objects.filter(delivery_mode=mode).select_related("user")
c588255… ragelink 222 for pref in prefs:
c588255… ragelink 223 unread = Notification.objects.filter(user=pref.user, read=False).select_related("project")
c588255… ragelink 224 if not unread.exists():
c588255… ragelink 225 continue
c588255… ragelink 226
c588255… ragelink 227 count = unread.count()
c588255… ragelink 228 notifications_list = list(unread[:50])
c588255… ragelink 229 overflow_count = count - 50 if count > 50 else 0
c588255… ragelink 230
c588255… ragelink 231 # Plain text fallback
c588255… ragelink 232 lines = [f"You have {count} new notification{'s' if count != 1 else ''}:\n"]
c588255… ragelink 233 for notif in notifications_list:
c588255… ragelink 234 lines.append(f"- [{notif.event_type}] {notif.project.name}: {notif.title}")
c588255… ragelink 235 if overflow_count:
c588255… ragelink 236 lines.append(f"\n... and {overflow_count} more.")
c588255… ragelink 237
c588255… ragelink 238 # HTML version
c588255… ragelink 239 html_body = render_to_string(
c588255… ragelink 240 "email/digest.html",
c588255… ragelink 241 {
c588255… ragelink 242 "digest_type": mode,
c588255… ragelink 243 "count": count,
c588255… ragelink 244 "notifications": notifications_list,
c588255… ragelink 245 "overflow_count": overflow_count,
c588255… ragelink 246 "dashboard_url": "/",
c588255… ragelink 247 "preferences_url": "/auth/notifications/",
c588255… ragelink 248 },
c588255… ragelink 249 )
c588255… ragelink 250
c588255… ragelink 251 try:
c588255… ragelink 252 send_mail(
c588255… ragelink 253 subject=f"Fossilrepo {mode.title()} Digest - {count} update{'s' if count != 1 else ''}",
c588255… ragelink 254 message="\n".join(lines),
c588255… ragelink 255 from_email=settings.DEFAULT_FROM_EMAIL,
c588255… ragelink 256 recipient_list=[pref.user.email],
c588255… ragelink 257 html_message=html_body,
c588255… ragelink 258 fail_silently=True,
c588255… ragelink 259 )
c588255… ragelink 260 except Exception:
c588255… ragelink 261 logger.exception("Failed to send %s digest to %s", mode, pref.user.email)
c588255… ragelink 262 continue
c588255… ragelink 263
c588255… ragelink 264 unread.update(read=True)
c588255… ragelink 265
c588255… ragelink 266
c588255… ragelink 267 @shared_task(name="fossil.dispatch_webhook", bind=True, max_retries=3)
c588255… ragelink 268 def dispatch_webhook(self, webhook_id, event_type, payload):
c588255… ragelink 269 """Deliver a webhook with retry and logging."""
c588255… ragelink 270 import hashlib
c588255… ragelink 271 import hmac
c588255… ragelink 272 import json
c588255… ragelink 273 import time
c588255… ragelink 274
c588255… ragelink 275 import requests
c588255… ragelink 276
c588255… ragelink 277 from fossil.webhooks import Webhook, WebhookDelivery
c588255… ragelink 278
c588255… ragelink 279 try:
c588255… ragelink 280 webhook = Webhook.objects.get(id=webhook_id)
c588255… ragelink 281 except Webhook.DoesNotExist:
c588255… ragelink 282 logger.warning("Webhook %s not found, skipping delivery", webhook_id)
c588255… ragelink 283 return
c588255… ragelink 284
7e1aaf6… ragelink 285 # Re-validate URL at dispatch time (hostname could resolve differently than at save time)
7e1aaf6… ragelink 286 from core.url_validation import is_safe_outbound_url
7e1aaf6… ragelink 287
7e1aaf6… ragelink 288 is_safe, url_error = is_safe_outbound_url(webhook.url)
7e1aaf6… ragelink 289 if not is_safe:
7e1aaf6… ragelink 290 logger.warning("Webhook %s URL failed safety check at dispatch: %s", webhook_id, url_error)
7e1aaf6… ragelink 291 WebhookDelivery.objects.create(
7e1aaf6… ragelink 292 webhook=webhook,
7e1aaf6… ragelink 293 event_type=event_type,
7e1aaf6… ragelink 294 payload=payload,
7e1aaf6… ragelink 295 response_status=0,
7e1aaf6… ragelink 296 response_body=f"Blocked: {url_error}",
7e1aaf6… ragelink 297 success=False,
7e1aaf6… ragelink 298 duration_ms=0,
7e1aaf6… ragelink 299 attempt=self.request.retries + 1,
7e1aaf6… ragelink 300 )
7e1aaf6… ragelink 301 return
7e1aaf6… ragelink 302
c588255… ragelink 303 headers = {"Content-Type": "application/json", "X-Fossilrepo-Event": event_type}
c588255… ragelink 304 body = json.dumps(payload)
c588255… ragelink 305
c588255… ragelink 306 if webhook.secret:
c588255… ragelink 307 sig = hmac.new(webhook.secret.encode(), body.encode(), hashlib.sha256).hexdigest()
c588255… ragelink 308 headers["X-Fossilrepo-Signature"] = f"sha256={sig}"
c588255… ragelink 309
c588255… ragelink 310 start = time.monotonic()
c588255… ragelink 311 try:
7e1aaf6… ragelink 312 resp = requests.post(webhook.url, data=body, headers=headers, timeout=30, allow_redirects=False)
c588255… ragelink 313 duration = int((time.monotonic() - start) * 1000)
c588255… ragelink 314
c588255… ragelink 315 WebhookDelivery.objects.create(
c588255… ragelink 316 webhook=webhook,
c588255… ragelink 317 event_type=event_type,
c588255… ragelink 318 payload=payload,
c588255… ragelink 319 response_status=resp.status_code,
c588255… ragelink 320 response_body=resp.text[:5000],
c588255… ragelink 321 success=200 <= resp.status_code < 300,
c588255… ragelink 322 duration_ms=duration,
c588255… ragelink 323 attempt=self.request.retries + 1,
c588255… ragelink 324 )
c588255… ragelink 325
c588255… ragelink 326 if not (200 <= resp.status_code < 300):
c588255… ragelink 327 raise self.retry(countdown=60 * (2**self.request.retries))
c588255… ragelink 328 except requests.RequestException as exc:
c588255… ragelink 329 duration = int((time.monotonic() - start) * 1000)
c588255… ragelink 330 WebhookDelivery.objects.create(
c588255… ragelink 331 webhook=webhook,
c588255… ragelink 332 event_type=event_type,
c588255… ragelink 333 payload=payload,
c588255… ragelink 334 response_status=0,
c588255… ragelink 335 response_body=str(exc)[:5000],
c588255… ragelink 336 success=False,
c588255… ragelink 337 duration_ms=duration,
c588255… ragelink 338 attempt=self.request.retries + 1,
c588255… ragelink 339 )
c588255… ragelink 340 raise self.retry(exc=exc, countdown=60 * (2**self.request.retries)) from exc
0da8377… ragelink 341
0da8377… ragelink 342
0da8377… ragelink 343 @shared_task(name="fossil.dispatch_notifications")
0da8377… ragelink 344 def dispatch_notifications():
0da8377… ragelink 345 """Check for new Fossil events and send notifications to watchers."""
0da8377… ragelink 346 import datetime
0da8377… ragelink 347
0da8377… ragelink 348 from django.utils import timezone
0da8377… ragelink 349
0da8377… ragelink 350 from fossil.models import FossilRepository
0da8377… ragelink 351 from fossil.notifications import ProjectWatch, notify_project_event
0da8377… ragelink 352 from fossil.reader import FossilReader
0da8377… ragelink 353
0da8377… ragelink 354 watched_project_ids = set(ProjectWatch.objects.filter(deleted_at__isnull=True).values_list("project_id", flat=True))
0da8377… ragelink 355 if not watched_project_ids:
0da8377… ragelink 356 return
0da8377… ragelink 357
0da8377… ragelink 358 cutoff = timezone.now() - datetime.timedelta(minutes=5)
0da8377… ragelink 359
0da8377… ragelink 360 for repo in FossilRepository.objects.filter(project_id__in=watched_project_ids, deleted_at__isnull=True):
0da8377… ragelink 361 if not repo.exists_on_disk:
0da8377… ragelink 362 continue
0da8377… ragelink 363 try:
0da8377… ragelink 364 with FossilReader(repo.full_path) as reader:
0da8377… ragelink 365 entries = reader.get_timeline(limit=10)
0da8377… ragelink 366 for entry in entries:
0da8377… ragelink 367 if entry.timestamp < cutoff:
0da8377… ragelink 368 break
0da8377… ragelink 369 event_type = {"ci": "checkin", "w": "wiki", "t": "ticket", "f": "forum"}.get(entry.event_type, "other")
0da8377… ragelink 370 url = f"/projects/{repo.project.slug}/fossil/"
0da8377… ragelink 371 if entry.event_type == "ci":
0da8377… ragelink 372 url += f"checkin/{entry.uuid}/"
0da8377… ragelink 373 notify_project_event(
0da8377… ragelink 374 project=repo.project,
0da8377… ragelink 375 event_type=event_type,
0da8377… ragelink 376 title=f"{entry.user}: {entry.comment[:100]}" if entry.comment else f"New {event_type}",
0da8377… ragelink 377 body=entry.comment or "",
0da8377… ragelink 378 url=url,
0da8377… ragelink 379 )
0da8377… ragelink 380 except Exception:
0da8377… ragelink 381 logger.exception("Notification dispatch error for %s", repo.filename)
0e40dc2… ragelink 382
0e40dc2… ragelink 383
0e40dc2… ragelink 384 @shared_task(name="fossil.sync_tickets_to_github")
0e40dc2… ragelink 385 def sync_tickets_to_github(mirror_id: int):
0e40dc2… ragelink 386 """Sync Fossil tickets to GitHub Issues for a given mirror.
0e40dc2… ragelink 387
0e40dc2… ragelink 388 Processes up to 20 tickets per run. Resumes from where it left off
0e40dc2… ragelink 389 by checking TicketSyncMapping for already-synced tickets.
0e40dc2… ragelink 390 """
0e40dc2… ragelink 391 from django.utils import timezone
0e40dc2… ragelink 392
0e40dc2… ragelink 393 from fossil.github_api import GitHubClient, format_ticket_body, fossil_status_to_github, parse_github_repo
0e40dc2… ragelink 394 from fossil.reader import FossilReader
0e40dc2… ragelink 395 from fossil.sync_models import GitMirror, SyncLog, TicketSyncMapping
0e40dc2… ragelink 396
0e40dc2… ragelink 397 try:
0e40dc2… ragelink 398 mirror = GitMirror.objects.get(pk=mirror_id, deleted_at__isnull=True)
0e40dc2… ragelink 399 except GitMirror.DoesNotExist:
0e40dc2… ragelink 400 return
0e40dc2… ragelink 401
0e40dc2… ragelink 402 repo = mirror.repository
0e40dc2… ragelink 403 if not repo.exists_on_disk:
0e40dc2… ragelink 404 return
0e40dc2… ragelink 405
0e40dc2… ragelink 406 parsed = parse_github_repo(mirror.git_remote_url)
0e40dc2… ragelink 407 if not parsed:
0e40dc2… ragelink 408 logger.warning("Cannot parse GitHub owner/repo from %s", mirror.git_remote_url)
0e40dc2… ragelink 409 return
0e40dc2… ragelink 410
0e40dc2… ragelink 411 owner, repo_name = parsed
0e40dc2… ragelink 412 token = mirror.auth_credential
0e40dc2… ragelink 413 if not token:
0e40dc2… ragelink 414 logger.warning("No auth token for mirror %s, skipping ticket sync", mirror_id)
0e40dc2… ragelink 415 return
0e40dc2… ragelink 416
0e40dc2… ragelink 417 log = SyncLog.objects.create(mirror=mirror, triggered_by="ticket_sync")
0e40dc2… ragelink 418 client = GitHubClient(token)
0e40dc2… ragelink 419 synced_count = 0
0e40dc2… ragelink 420 errors = []
0e40dc2… ragelink 421
0e40dc2… ragelink 422 try:
0e40dc2… ragelink 423 with FossilReader(repo.full_path) as reader:
0e40dc2… ragelink 424 tickets = reader.get_tickets(limit=500)
0e40dc2… ragelink 425
0e40dc2… ragelink 426 # Get existing mappings for this mirror
0e40dc2… ragelink 427 existing = {m.fossil_ticket_uuid: m for m in TicketSyncMapping.objects.filter(mirror=mirror)}
0e40dc2… ragelink 428
0e40dc2… ragelink 429 processed = 0
0e40dc2… ragelink 430 for ticket in tickets:
0e40dc2… ragelink 431 if processed >= 20:
0e40dc2… ragelink 432 break
0e40dc2… ragelink 433
0e40dc2… ragelink 434 mapping = existing.get(ticket.uuid)
0e40dc2… ragelink 435
0e40dc2… ragelink 436 # Skip if already synced and status hasn't changed
0e40dc2… ragelink 437 if mapping and mapping.fossil_status == ticket.status:
0e40dc2… ragelink 438 continue
0e40dc2… ragelink 439
0e40dc2… ragelink 440 processed += 1
0e40dc2… ragelink 441
0e40dc2… ragelink 442 # Get full ticket detail + comments
0e40dc2… ragelink 443 with FossilReader(repo.full_path) as reader:
0e40dc2… ragelink 444 detail = reader.get_ticket_detail(ticket.uuid)
0e40dc2… ragelink 445 comments = reader.get_ticket_comments(ticket.uuid)
0e40dc2… ragelink 446
0e40dc2… ragelink 447 if not detail:
0e40dc2… ragelink 448 continue
0e40dc2… ragelink 449
0e40dc2… ragelink 450 gh_state = fossil_status_to_github(detail.status)
0e40dc2… ragelink 451 body = format_ticket_body(detail, comments)
0e40dc2… ragelink 452
0e40dc2… ragelink 453 if mapping:
0e40dc2… ragelink 454 # Update existing issue
0e40dc2… ragelink 455 result = client.update_issue(owner, repo_name, mapping.github_issue_number, title=detail.title, body=body, state=gh_state)
0e40dc2… ragelink 456 if result["success"]:
0e40dc2… ragelink 457 mapping.fossil_status = detail.status
0e40dc2… ragelink 458 mapping.save()
0e40dc2… ragelink 459 synced_count += 1
0e40dc2… ragelink 460 logger.info("Updated GitHub issue #%d for ticket %s", mapping.github_issue_number, ticket.uuid[:10])
0e40dc2… ragelink 461 else:
0e40dc2… ragelink 462 errors.append(f"Update #{mapping.github_issue_number}: {result['error']}")
0e40dc2… ragelink 463 else:
0e40dc2… ragelink 464 # Create new issue
0e40dc2… ragelink 465 result = client.create_issue(owner, repo_name, detail.title, body, state=gh_state)
0e40dc2… ragelink 466 if result["number"]:
0e40dc2… ragelink 467 TicketSyncMapping.objects.create(
0e40dc2… ragelink 468 mirror=mirror,
0e40dc2… ragelink 469 fossil_ticket_uuid=ticket.uuid,
0e40dc2… ragelink 470 github_issue_number=result["number"],
0e40dc2… ragelink 471 fossil_status=detail.status,
0e40dc2… ragelink 472 )
0e40dc2… ragelink 473 synced_count += 1
0e40dc2… ragelink 474 logger.info("Created GitHub issue #%d for ticket %s", result["number"], ticket.uuid[:10])
0e40dc2… ragelink 475 else:
0e40dc2… ragelink 476 errors.append(f"Create '{detail.title[:30]}': {result['error']}")
0e40dc2… ragelink 477
0e40dc2… ragelink 478 log.status = "success" if not errors else "failed"
0e40dc2… ragelink 479 log.artifacts_synced = synced_count
0e40dc2… ragelink 480 log.message = f"Synced {synced_count} tickets." + (f" Errors: {'; '.join(errors[:5])}" if errors else "")
0e40dc2… ragelink 481 log.completed_at = timezone.now()
0e40dc2… ragelink 482 log.save()
0e40dc2… ragelink 483
0e40dc2… ragelink 484 except Exception:
0e40dc2… ragelink 485 logger.exception("Ticket sync error for mirror %s", mirror_id)
0e40dc2… ragelink 486 log.status = "failed"
0e40dc2… ragelink 487 log.message = "Unexpected error during ticket sync"
0e40dc2… ragelink 488 log.completed_at = timezone.now()
0e40dc2… ragelink 489 log.save()
0e40dc2… ragelink 490
0e40dc2… ragelink 491
0e40dc2… ragelink 492 @shared_task(name="fossil.sync_wiki_to_github")
0e40dc2… ragelink 493 def sync_wiki_to_github(mirror_id: int):
0e40dc2… ragelink 494 """Sync Fossil wiki pages to a wiki/ directory in the GitHub repo.
0e40dc2… ragelink 495
0e40dc2… ragelink 496 Uses the GitHub Contents API to create/update markdown files.
0e40dc2… ragelink 497 Only syncs pages whose content has changed (hash comparison).
0e40dc2… ragelink 498 """
0e40dc2… ragelink 499 from django.utils import timezone
0e40dc2… ragelink 500
0e40dc2… ragelink 501 from fossil.github_api import GitHubClient, content_hash, parse_github_repo
0e40dc2… ragelink 502 from fossil.reader import FossilReader
0e40dc2… ragelink 503 from fossil.sync_models import GitMirror, SyncLog, WikiSyncMapping
0e40dc2… ragelink 504
0e40dc2… ragelink 505 try:
0e40dc2… ragelink 506 mirror = GitMirror.objects.get(pk=mirror_id, deleted_at__isnull=True)
0e40dc2… ragelink 507 except GitMirror.DoesNotExist:
0e40dc2… ragelink 508 return
0e40dc2… ragelink 509
0e40dc2… ragelink 510 repo = mirror.repository
0e40dc2… ragelink 511 if not repo.exists_on_disk:
0e40dc2… ragelink 512 return
0e40dc2… ragelink 513
0e40dc2… ragelink 514 parsed = parse_github_repo(mirror.git_remote_url)
0e40dc2… ragelink 515 if not parsed:
0e40dc2… ragelink 516 logger.warning("Cannot parse GitHub owner/repo from %s", mirror.git_remote_url)
0e40dc2… ragelink 517 return
0e40dc2… ragelink 518
0e40dc2… ragelink 519 owner, repo_name = parsed
0e40dc2… ragelink 520 token = mirror.auth_credential
0e40dc2… ragelink 521 if not token:
0e40dc2… ragelink 522 logger.warning("No auth token for mirror %s, skipping wiki sync", mirror_id)
0e40dc2… ragelink 523 return
0e40dc2… ragelink 524
0e40dc2… ragelink 525 log = SyncLog.objects.create(mirror=mirror, triggered_by="wiki_sync")
0e40dc2… ragelink 526 client = GitHubClient(token)
0e40dc2… ragelink 527 synced_count = 0
0e40dc2… ragelink 528 errors = []
0e40dc2… ragelink 529
0e40dc2… ragelink 530 try:
0e40dc2… ragelink 531 with FossilReader(repo.full_path) as reader:
0e40dc2… ragelink 532 pages = reader.get_wiki_pages()
0e40dc2… ragelink 533
0e40dc2… ragelink 534 existing = {m.fossil_page_name: m for m in WikiSyncMapping.objects.filter(mirror=mirror)}
0e40dc2… ragelink 535
0e40dc2… ragelink 536 for page in pages:
0e40dc2… ragelink 537 # Read full page content
0e40dc2… ragelink 538 with FossilReader(repo.full_path) as reader:
0e40dc2… ragelink 539 full_page = reader.get_wiki_page(page.name)
0e40dc2… ragelink 540
0e40dc2… ragelink 541 if not full_page or not full_page.content.strip():
0e40dc2… ragelink 542 continue
0e40dc2… ragelink 543
0e40dc2… ragelink 544 current_hash = content_hash(full_page.content)
0e40dc2… ragelink 545 mapping = existing.get(page.name)
0e40dc2… ragelink 546
0e40dc2… ragelink 547 # Skip if content hasn't changed
0e40dc2… ragelink 548 if mapping and mapping.content_hash == current_hash:
0e40dc2… ragelink 549 continue
0e40dc2… ragelink 550
0e40dc2… ragelink 551 # Sanitize page name for file path
0e40dc2… ragelink 552 safe_name = page.name.replace(" ", "-").replace("/", "-")
0e40dc2… ragelink 553 file_path = f"wiki/{safe_name}.md"
0e40dc2… ragelink 554
0e40dc2… ragelink 555 result = client.create_or_update_file(
0e40dc2… ragelink 556 owner,
0e40dc2… ragelink 557 repo_name,
0e40dc2… ragelink 558 file_path,
0e40dc2… ragelink 559 full_page.content,
0e40dc2… ragelink 560 f"Sync wiki page: {page.name}",
0e40dc2… ragelink 561 )
0e40dc2… ragelink 562
0e40dc2… ragelink 563 if result["success"]:
0e40dc2… ragelink 564 if mapping:
0e40dc2… ragelink 565 mapping.content_hash = current_hash
0e40dc2… ragelink 566 mapping.github_path = file_path
0e40dc2… ragelink 567 mapping.save()
0e40dc2… ragelink 568 else:
0e40dc2… ragelink 569 WikiSyncMapping.objects.create(
0e40dc2… ragelink 570 mirror=mirror,
0e40dc2… ragelink 571 fossil_page_name=page.name,
0e40dc2… ragelink 572 content_hash=current_hash,
0e40dc2… ragelink 573 github_path=file_path,
0e40dc2… ragelink 574 )
0e40dc2… ragelink 575 synced_count += 1
0e40dc2… ragelink 576 logger.info("Synced wiki page '%s' to %s", page.name, file_path)
0e40dc2… ragelink 577 else:
0e40dc2… ragelink 578 errors.append(f"'{page.name}': {result['error']}")
0e40dc2… ragelink 579
0e40dc2… ragelink 580 log.status = "success" if not errors else "failed"
0e40dc2… ragelink 581 log.artifacts_synced = synced_count
0e40dc2… ragelink 582 log.message = f"Synced {synced_count} wiki pages." + (f" Errors: {'; '.join(errors[:5])}" if errors else "")
0e40dc2… ragelink 583 log.completed_at = timezone.now()
0e40dc2… ragelink 584 log.save()
0e40dc2… ragelink 585
0e40dc2… ragelink 586 except Exception:
0e40dc2… ragelink 587 logger.exception("Wiki sync error for mirror %s", mirror_id)
0e40dc2… ragelink 588 log.status = "failed"
0e40dc2… ragelink 589 log.message = "Unexpected error during wiki sync"
0e40dc2… ragelink 590 log.completed_at = timezone.now()
0e40dc2… ragelink 591 log.save()

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button