184 lines
5.9 KiB
Python
184 lines
5.9 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
历史周报整理工具
|
||
将旧的 .txt 格式周报转换为标准的 Markdown 归档格式
|
||
|
||
用法:
|
||
python3 migrate_legacy_reports.py --dry-run # 预览转换结果
|
||
python3 migrate_legacy_reports.py --migrate # 执行迁移
|
||
"""
|
||
|
||
import os
|
||
import re
|
||
from pathlib import Path
|
||
from datetime import datetime
|
||
import argparse
|
||
|
||
REPORTS_DIR = Path(__file__).parent
|
||
|
||
|
||
def parse_legacy_report(filepath):
|
||
"""解析旧的 .txt 格式周报"""
|
||
with open(filepath, 'r', encoding='utf-8') as f:
|
||
content = f.read()
|
||
|
||
# 从文件名提取日期
|
||
filename = filepath.name
|
||
match = re.match(r'(\d{4}-\d{2}-\d{2})_\d+_G5 周报\.txt', filename)
|
||
if not match:
|
||
return None
|
||
|
||
friday_date = datetime.strptime(match.group(1), '%Y-%m-%d')
|
||
monday_date = friday_date - timedelta(days=friday_date.weekday())
|
||
|
||
# 提取内容
|
||
lines = content.split('\n')
|
||
project = '维云智造 G5'
|
||
task = ''
|
||
daily_work = {}
|
||
problems = []
|
||
|
||
current_day = None
|
||
in_work_section = False
|
||
in_problem_section = False
|
||
|
||
for line in lines:
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
|
||
if line.startswith('主要任务:'):
|
||
task = line.replace('主要任务:', '').strip()
|
||
elif line.startswith('本周工作内容'):
|
||
in_work_section = True
|
||
in_problem_section = False
|
||
elif line.startswith('存在问题'):
|
||
in_work_section = False
|
||
in_problem_section = True
|
||
elif in_work_section and re.match(r'^周 [一二三四五六日]', line):
|
||
match = re.match(r'^(周 [一二三四五六日]).*?(\d{4}-\d{2}-\d{2})', line)
|
||
if match:
|
||
current_day = match.group(2)
|
||
daily_work[current_day] = []
|
||
elif in_work_section and line.startswith('- '):
|
||
if current_day:
|
||
daily_work[current_day].append(line)
|
||
elif in_problem_section and line and not line.startswith('存在问题'):
|
||
problems.append(line)
|
||
|
||
return {
|
||
'monday': monday_date,
|
||
'friday': friday_date,
|
||
'project': project,
|
||
'task': task,
|
||
'daily_work': daily_work,
|
||
'problems': problems,
|
||
'original_file': str(filepath)
|
||
}
|
||
|
||
|
||
def generate_markdown(report):
|
||
"""生成标准 Markdown 格式"""
|
||
from datetime import timedelta
|
||
|
||
week_number = report['monday'].isocalendar()[1]
|
||
year = report['monday'].year
|
||
|
||
content = []
|
||
content.append(f"# G5 开发周报 ({year}-W{week_number:02d})")
|
||
content.append("")
|
||
content.append(f"**日期范围:** {report['monday'].strftime('%Y-%m-%d')} ~ {report['friday'].strftime('%Y-%m-%d')}")
|
||
content.append("")
|
||
content.append("## 基本信息")
|
||
content.append(f"项目名称: {report['project']}")
|
||
content.append(f"主要任务: {report['task']}")
|
||
content.append("")
|
||
content.append("## 本周工作内容")
|
||
content.append("")
|
||
|
||
# 按日期排序输出每日工作
|
||
for day in sorted(report['daily_work'].keys()):
|
||
content.append(f"### {day}")
|
||
for item in report['daily_work'][day]:
|
||
content.append(item)
|
||
content.append("")
|
||
|
||
content.append("## 存在问题")
|
||
content.append("")
|
||
if report['problems']:
|
||
for problem in report['problems']:
|
||
content.append(f"- {problem}")
|
||
else:
|
||
content.append("无")
|
||
content.append("")
|
||
content.append("---")
|
||
content.append(f"*归档时间:{datetime.now().strftime('%Y-%m-%d %H:%M')}*")
|
||
content.append(f"*原始文件:{report['original_file']}*")
|
||
|
||
return '\n'.join(content)
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description='历史周报整理工具')
|
||
parser.add_argument('--dry-run', action='store_true', help='预览转换结果,不执行迁移')
|
||
parser.add_argument('--migrate', action='store_true', help='执行迁移')
|
||
args = parser.parse_args()
|
||
|
||
if not args.dry_run and not args.migrate:
|
||
print("请使用 --dry-run 预览或 --migrate 执行迁移")
|
||
return 1
|
||
|
||
# 查找所有 .txt 周报文件
|
||
txt_files = list(REPORTS_DIR.glob('2025-*/2025-*.txt')) + list(REPORTS_DIR.glob('2026-*/2026-*.txt'))
|
||
|
||
if not txt_files:
|
||
print("✅ 未找到需要迁移的旧格式周报")
|
||
return 0
|
||
|
||
print(f"📂 找到 {len(txt_files)} 个旧格式周报文件")
|
||
print("")
|
||
|
||
migrated_count = 0
|
||
for txt_file in sorted(txt_files):
|
||
report = parse_legacy_report(txt_file)
|
||
if not report:
|
||
print(f"⚠️ 跳过无法解析的文件:{txt_file.name}")
|
||
continue
|
||
|
||
# 生成目标文件名
|
||
week_number = report['monday'].isocalendar()[1]
|
||
year = report['monday'].year
|
||
target_dir = REPORTS_DIR / str(year)
|
||
target_file = target_dir / f"{year}-W{week_number:02d}-周报.md"
|
||
|
||
if args.dry_run:
|
||
print(f"📄 {txt_file.name} → {target_file.name}")
|
||
elif args.migrate:
|
||
# 检查是否已存在
|
||
if target_file.exists():
|
||
print(f"⏭️ 已存在,跳过:{target_file.name}")
|
||
continue
|
||
|
||
# 创建年份目录
|
||
target_dir.mkdir(parents=True, exist_ok=True)
|
||
|
||
# 生成并写入 Markdown
|
||
markdown_content = generate_markdown(report)
|
||
with open(target_file, 'w', encoding='utf-8') as f:
|
||
f.write(markdown_content)
|
||
|
||
print(f"✅ 迁移完成:{target_file.name}")
|
||
migrated_count += 1
|
||
|
||
print("")
|
||
if args.dry_run:
|
||
print(f"📊 预览:共 {len(txt_files)} 个文件待迁移")
|
||
print(" 使用 --migrate 执行实际迁移")
|
||
elif args.migrate:
|
||
print(f"🎉 迁移完成!共处理 {migrated_count} 个文件")
|
||
|
||
|
||
if __name__ == '__main__':
|
||
from datetime import timedelta
|
||
exit(main())
|