#!/usr/bin/env python3 """Read live release evidence and preview a plan without publishing or dispatching.""" import argparse import json from pathlib import Path import re import sys from urllib.error import HTTPError import candidate_coordinator as coordinator import candidate_release as candidate import candidate_worker as worker import production_cd as cd SOURCE = Path.home() / '.local/share/kg-candidate-source.git' SITE = 'http://100.85.111.121:8088/' def task_record(value): cd.require(cd.matches(cd.UUID, value) or re.fullmatch(r'CYWL-[1-9][0-9]{0,8}', value), 'provide a task UUID or CYWL task number') record = coordinator.hfx.hifox(coordinator.CLI, 'task', 'view', value) cd.require(isinstance(record, dict) and record.get('spaceId') == cd.SPACE, 'task is outside the release space') cd.require(cd.matches(cd.UUID, record.get('id')) and value in (record['id'], record.get('identifier')), 'task identity did not match') return record def ci_state(sha): status = candidate.read_forge(f'{candidate.API}/commits/{sha}/status') contexts = {line.split('#', 1)[0].strip() for line in candidate.CONTEXTS.read_text().splitlines()} - {''} latest = {name: next((row for row in status.get('statuses') or [] if row.get('context') == name), None) for name in sorted(contexts)} result = {} for name, row in latest.items(): row = row or {} url = (row.get('target_url') or '').replace('http://192.168.50.223:3000/', cd.FORGE + '/', 1) if url.startswith('/' + cd.REPO + '/'): url = cd.FORGE + url result[name] = {'status': row.get('status', 'not_reported'), 'url': url if url.startswith(cd.FORGE + '/') else ''} return result def snapshot(): branch = candidate.read_forge(f'{candidate.API}/branches/main') sha = branch['commit']['id'] cd.require(cd.matches(cd.SHA, sha), 'Gitea did not return a full main SHA') active = worker.main_site_sha() block = None try: coordinator.runtime.qa_database(Path.home() / '.config/knowledge-governance/qa.json') except (cd.CDError, coordinator.runtime.qa_env.QAError, OSError): block = '候选执行机未就绪。缺少可用的专用 QA 数据库连接配置。' return {'main_sha': sha, 'main_ci': ci_state(sha), 'site': SITE, 'site_api_sha': active, 'candidate_configuration_block': block} def pr_record(number): cd.require(type(number) is int and number > 0, 'invalid PR number') result = candidate.read_forge(f'{candidate.API}/pulls/{number}') return {**result, 'public_url': f'{cd.FORGE}/{cd.REPO}/pulls/{number}'} def describe_task(value): task = task_record(value) acceptance = cd.metadata(task, 'cd_acceptance') release = cd.metadata(task, 'cd_release') result = {'task': task['identifier'], 'uuid': task['id'], 'url': task['url'], 'status': (task.get('status') or {}).get('name'), 'acceptance': acceptance, 'release': release} try: plan = coordinator.owner_plan(task['id']) except cd.CDError as exc: result['candidate'] = {'state': 'unavailable', 'reason': str(exc)} return result key = cd.acceptance_digest(plan) receipt = coordinator.STATE / key / 'ready.json' dispatch = coordinator.STATE / (key + '.dispatch.json') if receipt.is_file(): data = cd.read_json(cd.immutable_file(receipt)) result['candidate'] = {field: data.get(field) for field in ('sha', 'bundle', 'url', 'mode', 'ready_at')} elif dispatch.is_file(): data = cd.read_json(cd.immutable_file(dispatch)) result['candidate'] = {field: data.get(field) for field in ('state', 'run', 'url')} if data.get('run') and cd.matches(coordinator.hfx.RUN_ID, data['run']): run = candidate.read_forge(candidate.API + '/actions/runs/' + data['run']) result['candidate'].update(workflow_status=run.get('status'), conclusion=run.get('conclusion')) else: result['candidate'] = {'state': 'unprepared', 'sha': plan['sha']} return result def preview(release_task, items, candidate_sha=None): state = snapshot() sha, base = candidate_sha or state['main_sha'], state['site_api_sha'] cd.require(cd.matches(cd.SHA, sha), 'invalid candidate SHA') launch = task_record(release_task) cd.require((launch.get('status') or {}).get('id') not in (cd.READY, cd.PUBLISHED), 'choose a separate pre-approval release task') content = [] landed = set() for pair in items: task_key, separator, number = pair.partition(':') if separator and cd.matches(cd.SHA, number): requirement = task_record(task_key) landed.add(number) content.append({'task': requirement['id'], 'commit': number}) continue cd.require(bool(separator) and bool(re.fullmatch(r'[1-9][0-9]{0,8}', number)), 'expected task:PR') requirement = task_record(task_key) pr = pr_record(int(number)) change = pr.get('merge_commit_sha') cd.require(pr.get('merged') and (pr.get('base') or {}).get('ref') == 'main' and cd.matches(cd.SHA, change), f'PR #{number} has not landed on main') fields = [pr.get('title'), pr.get('body'), (pr.get('head') or {}).get('ref')] cd.require(bool(re.search(rf"(?