reposync/issue_sync/sync/pr_comment_sync_runner.py

111 lines
3.9 KiB
Python

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from service.pr_comment_sync_service import PRCommentSyncService
import pymysql
import time
from datetime import datetime
def load_env_file(path):
"""从 .env 或 .ini 文件加载环境变量, 支持 'export KEY=VALUE' 格式"""
env_vars = {}
try:
with open(path, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('export '):
line = line[len('export '):]
parts = line.split('=', 1)
if len(parts) == 2:
key, value = parts[0].strip(), parts[1].strip()
# 去除值可能存在的引号
if (value.startswith("'") and value.endswith("'")) or \
(value.startswith('"') and value.endswith('"')):
value = value[1:-1]
env_vars[key] = value
except FileNotFoundError:
print(f"配置文件未找到: {path}")
except Exception as e:
print(f"读取配置文件时出错: {e}")
return env_vars
# 加载配置
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', 'env.ini')
db_config = load_env_file(config_path)
def get_db():
return pymysql.connect(
host=db_config.get('CEROBOT_MYSQL_HOST', 'localhost'),
user=db_config.get('CEROBOT_MYSQL_USER', 'root'),
password=db_config.get('CEROBOT_MYSQL_PWD', '123456789LY@'),
database='issue_sync',
charset="utf8mb4"
)
def get_all_enabled_sync_configs():
"""
从数据库读取所有启用的 PR评论 同步配置
"""
db = get_db()
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute("""
SELECT * FROM sync_config
WHERE enabled=1 AND sync_type='pr_comment'
""")
configs = cursor.fetchall()
db.close()
return configs
def run_all_sync():
"""执行所有启用的PR评论同步配置"""
configs = get_all_enabled_sync_configs()
print(f"找到 {len(configs)} 个启用的PR评论同步配置")
for config in configs:
print(f"开始同步: {config['source_platform']}->{config['target_platform']} {config['source_repo']}->{config['target_repo']}")
service = PRCommentSyncService(config)
# 根据配置决定同步方向
if config.get('sync_direction') == 'bidirectional':
print("执行双向同步...")
service.bidirectional_sync()
else:
print("执行单向同步...")
service.sync()
print(f"完成同步: {config['source_platform']}->{config['target_platform']} {config['source_repo']}->{config['target_repo']}")
def run_auto_sync(interval=300):
"""
自动定期执行同步
:param interval: 同步间隔(秒)
"""
print(f"启动自动同步,间隔: {interval}")
while True:
print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 执行定时同步...")
try:
run_all_sync()
except Exception as e:
print(f"同步过程中发生错误: {e}")
print(f"同步完成,等待{interval}秒后再次执行...")
time.sleep(interval)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='PR评论同步工具')
parser.add_argument('--auto', action='store_true', help='启用自动同步模式')
parser.add_argument('--interval', type=int, default=300, help='自动同步间隔(秒)')
args = parser.parse_args()
if args.auto:
run_auto_sync(args.interval)
else:
run_all_sync()