markdown格式脚本
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
本周工作总结生成器
读取Git提交记录并生成工作总结报告
"""
import subprocess
import json
from datetime import datetime, timedelta
import re
import sys
from collections import defaultdict
class WeeklyWorkSummary:
def __init__(self):
self.commits = []
self.file_changes = defaultdict(int)
self.modules_changed = set()
def get_week_range(self):
"""获取本周的开始和结束日期"""
today = datetime.now()
# 获取本周一的日期
monday = today - timedelta(days=today.weekday())
# 本周日
sunday = monday + timedelta(days=6)
return monday.strftime('%Y-%m-%d'), sunday.strftime('%Y-%m-%d')
def get_git_commits(self, start_date, end_date, author='xuhang'):
"""获取指定时间范围内的Git提交"""
try:
# 获取提交信息,只显示指定作者的提交
cmd = [
'git', 'log',
f'--since={start_date}',
f'--until={end_date} 23:59:59',
f'--author={author}',
'--pretty=format:%H|%an|%ae|%ad|%s',
'--date=iso',
'--no-merges'
]
result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
if result.returncode != 0:
print(f"Git命令执行失败: {result.stderr}")
return []
commits = []
for line in result.stdout.strip().split('\n'):
if line:
parts = line.split('|', 4)
if len(parts) == 5:
commits.append({
'hash': parts[0],
'author': parts[1],
'email': parts[2],
'date': parts[3],
'message': parts[4]
})
return commits
except Exception as e:
print(f"获取Git提交失败: {e}")
return []
def get_commit_files(self, commit_hash):
"""获取提交中修改的文件"""
try:
cmd = ['git', 'show', '--name-status', '--pretty=format:', commit_hash]
result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
if result.returncode != 0:
return []
files = []
for line in result.stdout.strip().split('\n'):
if line and '\t' in line:
status, filename = line.split('\t', 1)
files.append({
'status': status,
'filename': filename
})
return files
except Exception as e:
print(f"获取提交文件失败: {e}")
return []
def analyze_modules(self, filename):
"""分析文件所属的模块"""
if filename.startswith('source/modules/'):
module = filename.split('/')[2] if len(filename.split('/')) > 2 else 'unknown'
return f"modules/{module}"
elif filename.startswith('source/plugins/'):
plugin = filename.split('/')[2] if len(filename.split('/')) > 2 else 'unknown'
return f"plugins/{plugin}"
elif filename.startswith('source/app/'):
return "app"
elif filename.startswith('3rdparty/'):
return "3rdparty"
elif filename.startswith('cmake/'):
return "cmake"
elif filename.startswith('config/'):
return "config"
else:
return "other"
def categorize_commit(self, message):
"""根据提交信息分类提交类型"""
message_lower = message.lower()
if any(word in message_lower for word in ['fix', 'bug', '修复', '修正', 'hotfix']):
return "🐛 Bug修复"
elif any(word in message_lower for word in ['feat', 'feature', '新增', '添加', '功能']):
return "✨ 新功能"
elif any(word in message_lower for word in ['refactor', '重构', 'refact']):
return "♻️ 重构"
elif any(word in message_lower for word in ['doc', 'docs', '文档', 'readme']):
return "📝 文档"
elif any(word in message_lower for word in ['test', '测试']):
return "🧪 测试"
elif any(word in message_lower for word in ['style', '样式', 'format', '格式']):
return "💄 样式"
elif any(word in message_lower for word in ['perf', '性能', '优化', 'optimize']):
return "⚡ 性能优化"
elif any(word in message_lower for word in ['config', '配置', 'setup']):
return "🔧 配置"
else:
return "🔨 其他"
def generate_markdown_report(self, start_date, end_date, author, commits,
commit_categories, total_files_changed, sorted_files):
"""生成Markdown格式的工作总结报告"""
# 计算工作日数量
from datetime import datetime, timedelta
start = datetime.strptime(start_date, '%Y-%m-%d')
end = datetime.strptime(end_date, '%Y-%m-%d')
work_days = 0
current = start
while current <= end:
if current.weekday() < 5: # 周一到周五
work_days += 1
current += timedelta(days=1)
# 计算平均每日提交数
avg_commits_per_day = len(commits) / work_days if work_days > 0 else 0
markdown = f"""# 📊 {author} 的本周工作总结
## 📅 基本信息
- **统计周期**: {start_date} ~ {end_date}
- **工作日数**: {work_days} 天
- **总提交数**: {len(commits)} 个
- **日均提交**: {avg_commits_per_day:.1f} 个/天
- **修改文件**: {total_files_changed} 个
- **涉及模块**: {len(self.modules_changed)} 个
## 📈 工作量统计
| 指标 | 数量 | 备注 |
|------|------|------|
| 总提交数 | {len(commits)} | 本周所有提交 |
| 修改文件数 | {total_files_changed} | 累计修改的文件 |
| 涉及模块数 | {len(self.modules_changed)} | 跨模块开发 |
| 工作日数 | {work_days} | 周一至周五 |
| 日均提交 | {avg_commits_per_day:.1f} | 提交频率 |
## 🎯 工作内容分类
"""
# 添加提交分类统计
for category, category_commits in sorted(commit_categories.items()):
category_name = category.split(' ', 1)[1] if ' ' in category else category
markdown += f"### {category} ({len(category_commits)}个)\n\n"
for commit in category_commits:
date_str = commit['date'][:16].replace('T', ' ')
commit_hash = commit['hash'][:8]
message = commit['message'].replace('\n', ' ').strip()
markdown += f"- **{date_str}** - {message} `[{commit_hash}]`\n"
markdown += "\n"
# 添加模块统计
markdown += "## 🏗️ 涉及模块\n\n"
for module in sorted(self.modules_changed):
markdown += f"- {module}\n"
# 添加文件修改统计
markdown += f"\n## 📁 文件修改统计 (Top 10)\n\n"
markdown += "| 文件路径 | 修改次数 |\n"
markdown += "|----------|----------|\n"
for filename, count in sorted_files[:10]:
markdown += f"| `{filename}` | {count} |\n"
# 添加工作亮点总结
markdown += f"\n## ✨ 本周工作亮点\n\n"
# 统计各类型提交数量
feature_count = len(commit_categories.get("✨ 新功能", []))
bug_count = len(commit_categories.get("🐛 Bug修复", []))
refactor_count = len(commit_categories.get("♻️ 重构", []))
if feature_count > 0:
markdown += f"- 🚀 **新功能开发**: 完成 {feature_count} 个新功能的开发\n"
if bug_count > 0:
markdown += f"- 🔧 **问题修复**: 解决了 {bug_count} 个Bug和问题\n"
if refactor_count > 0:
markdown += f"- ♻️ **代码优化**: 进行了 {refactor_count} 次代码重构和优化\n"
if len(self.modules_changed) > 5:
markdown += f"- 🏗️ **跨模块协作**: 涉及 {len(self.modules_changed)} 个不同模块的开发\n"
if avg_commits_per_day > 2:
markdown += f"- 📈 **高效产出**: 日均 {avg_commits_per_day:.1f} 次提交,保持高效的开发节奏\n"
# 添加总结
markdown += f"\n## 📝 总结\n\n"
markdown += f"本周共完成 **{len(commits)}** 次代码提交,"
if feature_count >= bug_count:
markdown += "主要专注于新功能开发,"
else:
markdown += "主要专注于问题修复和优化,"
markdown += f"涉及 **{len(self.modules_changed)}** 个模块的 **{total_files_changed}** 个文件修改。"
if avg_commits_per_day > 2:
markdown += "保持了较高的开发效率和代码质量。"
else:
markdown += "注重代码质量,每次提交都经过仔细考虑。"
markdown += f"\n\n---\n*报告生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*"
return markdown
def generate_summary(self, author='xuhang'):
"""生成工作总结"""
start_date, end_date = self.get_week_range()
print(f"📊 生成 {start_date} 至 {end_date} 的工作总结")
print(f"👤 作者筛选: {author}\n")
commits = self.get_git_commits(start_date, end_date, author)
if not commits:
print(f"❌ 本周没有找到 {author} 的提交记录")
return
# 按类型分组提交
commit_categories = defaultdict(list)
total_files_changed = 0
for commit in commits:
category = self.categorize_commit(commit['message'])
commit_categories[category].append(commit)
# 获取文件变更信息
files = self.get_commit_files(commit['hash'])
total_files_changed += len(files)
for file_info in files:
filename = file_info['filename']
self.file_changes[filename] += 1
module = self.analyze_modules(filename)
self.modules_changed.add(module)
# 生成报告
print("=" * 60)
print("📈 本周工作总结报告")
print("=" * 60)
print(f"\n📅 时间范围: {start_date} ~ {end_date}")
print(f"📝 总提交数: {len(commits)}")
print(f"📁 修改文件数: {total_files_changed}")
print(f"🏗️ 涉及模块数: {len(self.modules_changed)}")
# 按类型显示提交
print(f"\n{'='*40}")
print("📋 提交分类统计")
print(f"{'='*40}")
for category, category_commits in sorted(commit_categories.items()):
print(f"\n{category} ({len(category_commits)}个)")
print("-" * 50)
for commit in category_commits:
date_str = commit['date'][:16] # 只显示日期和时间
print(f" • {date_str} - {commit['message']}")
print(f" [{commit['hash'][:8]}]")
# 显示主要修改的模块
print(f"\n{'='*40}")
print("🏗️ 主要修改模块")
print(f"{'='*40}")
for module in sorted(self.modules_changed):
print(f" • {module}")
# 显示修改最频繁的文件
print(f"\n{'='*40}")
print("📁 修改最频繁的文件 (Top 10)")
print(f"{'='*40}")
sorted_files = sorted(self.file_changes.items(), key=lambda x: x[1], reverse=True)
for filename, count in sorted_files[:10]:
print(f" • {filename} ({count}次)")
# 生成Markdown格式的工作总结
markdown_content = self.generate_markdown_report(
start_date, end_date, author, commits,
commit_categories, total_files_changed, sorted_files
)
# 保存Markdown报告到文件
markdown_filename = f"weekly_summary_{author}_{start_date}_to_{end_date}.md"
try:
with open(markdown_filename, 'w', encoding='utf-8') as f:
f.write(markdown_content)
print(f"\n📄 Markdown报告已保存到: {markdown_filename}")
except Exception as e:
print(f"\n❌ 保存Markdown文件失败: {e}")
print(f"\n{'='*60}")
print("✅ 工作总结生成完成!")
print(f"{'='*60}")
def main():
"""主函数"""
try:
# 检查是否在Git仓库中
result = subprocess.run(['git', 'rev-parse', '--git-dir'],
capture_output=True, text=True)
if result.returncode != 0:
print("❌ 当前目录不是Git仓库")
sys.exit(1)
# 获取命令行参数中的作者名称,默认为 xuhang
author = 'xuhang'
if len(sys.argv) > 1:
author = sys.argv[1]
# 生成工作总结
summary_generator = WeeklyWorkSummary()
summary_generator.generate_summary(author)
except KeyboardInterrupt:
print("\n\n⚠️ 用户中断操作")
sys.exit(1)
except Exception as e:
print(f"❌ 程序执行出错: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
普通表格形式
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
本周工作总结生成器
读取Git提交记录并生成工作总结报告
"""
import subprocess
import json
from datetime import datetime, timedelta
import re
import sys
from collections import defaultdict
class WeeklyWorkSummary:
def __init__(self):
self.commits = []
self.file_changes = defaultdict(int)
self.modules_changed = set()
def get_week_range(self):
"""获取本周的开始和结束日期"""
today = datetime.now()
# 获取本周一的日期
monday = today - timedelta(days=today.weekday())
# 本周日
sunday = monday + timedelta(days=6)
return monday.strftime('%Y-%m-%d'), sunday.strftime('%Y-%m-%d')
def get_git_commits(self, start_date, end_date, author='xuhang'):
"""获取指定时间范围内的Git提交"""
try:
# 获取提交信息,只显示指定作者的提交
cmd = [
'git', 'log',
f'--since={start_date}',
f'--until={end_date} 23:59:59',
f'--author={author}',
'--pretty=format:%H|%an|%ae|%ad|%s',
'--date=iso',
'--no-merges'
]
result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
if result.returncode != 0:
print(f"Git命令执行失败: {result.stderr}")
return []
commits = []
for line in result.stdout.strip().split('\n'):
if line:
parts = line.split('|', 4)
if len(parts) == 5:
commits.append({
'hash': parts[0],
'author': parts[1],
'email': parts[2],
'date': parts[3],
'message': parts[4]
})
return commits
except Exception as e:
print(f"获取Git提交失败: {e}")
return []
def get_commit_files(self, commit_hash):
"""获取提交中修改的文件"""
try:
cmd = ['git', 'show', '--name-status', '--pretty=format:', commit_hash]
result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8')
if result.returncode != 0:
return []
files = []
for line in result.stdout.strip().split('\n'):
if line and '\t' in line:
status, filename = line.split('\t', 1)
files.append({
'status': status,
'filename': filename
})
return files
except Exception as e:
print(f"获取提交文件失败: {e}")
return []
def analyze_modules(self, filename):
"""分析文件所属的模块"""
if filename.startswith('source/modules/'):
module = filename.split('/')[2] if len(filename.split('/')) > 2 else 'unknown'
return f"modules/{module}"
elif filename.startswith('source/plugins/'):
plugin = filename.split('/')[2] if len(filename.split('/')) > 2 else 'unknown'
return f"plugins/{plugin}"
elif filename.startswith('source/app/'):
return "app"
elif filename.startswith('3rdparty/'):
return "3rdparty"
elif filename.startswith('cmake/'):
return "cmake"
elif filename.startswith('config/'):
return "config"
else:
return "other"
def split_commit_message(self, message):
"""拆分包含多个功能点的提交信息"""
import re
# 尝试按换行分割
lines = message.split('\n')
if len(lines) > 1:
split_messages = []
for line in lines:
line = line.strip()
if line and any(prefix in line.lower() for prefix in ['fix:', 'feat:', 'refactor:', 'fix:', 'feat:', 'refactor:']):
split_messages.append(line)
if len(split_messages) > 1:
return split_messages
# 使用正则表达式查找所有可能的功能点分割位置
# 匹配模式:前缀关键词 + 冒号 + 内容
pattern = r'((?:fix|feat|refactor)[::])'
# 找到所有匹配的位置
matches = list(re.finditer(pattern, message, flags=re.IGNORECASE))
if len(matches) >= 1:
split_messages = []
# 如果第一个匹配不是从开头开始,说明前面有内容
if matches[0].start() > 0:
first_part = message[:matches[0].start()].strip()
if first_part:
# 为第一部分添加适当的前缀(根据后续内容判断)
next_match = matches[0].group().lower()
if 'fix' in next_match:
prefix = 'fix:'
elif 'feat' in next_match:
prefix = 'feat:'
else:
prefix = 'fix:' # 默认为fix
split_messages.append(f"{prefix}{first_part}")
# 处理所有匹配的部分
for i, match in enumerate(matches):
start_pos = match.start()
if i < len(matches) - 1:
end_pos = matches[i + 1].start()
segment = message[start_pos:end_pos].strip()
else:
segment = message[start_pos:].strip()
if segment:
split_messages.append(segment)
if len(split_messages) > 1:
return split_messages
# 备用方案:基于标点符号和关键词的分割
separators = [
r'([,。;])\s*(fix[::])', # 标点符号后跟fix:
r'([,。;])\s*(feat[::])', # 标点符号后跟feat:
r'([,。;])\s*(refactor[::])', # 标点符号后跟refactor:
r'(\s+)(fix[::])', # 空格后跟fix: (处理你的示例情况)
r'(\s+)(feat[::])', # 空格后跟feat:
r'(\s+)(refactor[::])', # 空格后跟refactor:
]
for separator_pattern in separators:
if re.search(separator_pattern, message, flags=re.IGNORECASE):
# 使用lookahead来保持分隔符
split_pattern = f'(?={separator_pattern.replace("(", "").replace(")", "")})'
parts = re.split(split_pattern, message, flags=re.IGNORECASE)
if len(parts) > 1:
split_messages = []
for part in parts:
part = part.strip()
if part and any(prefix in part.lower() for prefix in ['fix:', 'feat:', 'refactor:', 'fix:', 'feat:', 'refactor:']):
split_messages.append(part)
if len(split_messages) > 1:
return split_messages
# 如果没有找到分割点,返回原始消息
return [message]
def categorize_commit(self, message):
"""根据提交信息分类提交类型"""
message_lower = message.lower()
if any(word in message_lower for word in ['fix', 'bug', '修复', '修正', 'hotfix']):
return "🐛 Bug修复"
elif any(word in message_lower for word in ['feat', 'feature', '新增', '添加', '功能']):
return "✨ 新功能"
elif any(word in message_lower for word in ['refactor', '重构', 'refact']):
return "♻️ 重构"
elif any(word in message_lower for word in ['doc', 'docs', '文档', 'readme']):
return "📝 文档"
elif any(word in message_lower for word in ['test', '测试']):
return "🧪 测试"
elif any(word in message_lower for word in ['style', '样式', 'format', '格式']):
return "💄 样式"
elif any(word in message_lower for word in ['perf', '性能', '优化', 'optimize']):
return "⚡ 性能优化"
elif any(word in message_lower for word in ['config', '配置', 'setup']):
return "🔧 配置"
else:
return "🔨 其他"
def generate_table_format(self, start_date, end_date, author, commits, split_commit_items,
commit_categories, total_files_changed, sorted_files):
"""生成适合复制粘贴到表格的格式"""
# 计算工作日数量
start = datetime.strptime(start_date, '%Y-%m-%d')
end = datetime.strptime(end_date, '%Y-%m-%d')
work_days = 0
current = start
while current <= end:
if current.weekday() < 5: # 周一到周五
work_days += 1
current += timedelta(days=1)
avg_commits_per_day = len(commits) / work_days if work_days > 0 else 0
# 统计各类型提交数量
feature_count = len(commit_categories.get("✨ 新功能", []))
bug_count = len(commit_categories.get("🐛 Bug修复", []))
refactor_count = len(commit_categories.get("♻️ 重构", []))
other_count = len(commits) - feature_count - bug_count - refactor_count
# 主要模块列表
main_modules = [module.replace('modules/', '').replace('plugins/', '')
for module in sorted(self.modules_changed)
if not module.startswith('other')][:5] # 只取前5个主要模块
# 计算拆分后的工作项统计
total_work_items = len(split_commit_items)
avg_items_per_day = total_work_items / work_days if work_days > 0 else 0
# 生成表格友好的内容
table_content = f"""工作周期: {start_date} ~ {end_date}
开发者: {author}
工作日数: {work_days}天
总提交数: {len(commits)}个
工作项数: {total_work_items}个 (拆分后)
日均提交: {avg_commits_per_day:.1f}个/天
日均工作项: {avg_items_per_day:.1f}个/天
修改文件: {total_files_changed}个
涉及模块: {len(self.modules_changed)}个
工作分类统计:
新功能开发: {feature_count}个
Bug修复: {bug_count}个
代码重构: {refactor_count}个
其他工作: {other_count}个
主要涉及模块:
{' | '.join(main_modules)}
核心工作内容:"""
# 添加主要工作内容(使用拆分后的信息)
important_items = []
for category, category_commits in sorted(commit_categories.items()):
if category in ["✨ 新功能", "🐛 Bug修复", "♻️ 重构"]:
for commit in category_commits[:8]: # 增加显示数量,因为现在每个都是拆分后的单独项
message = commit['message'].replace('\n', ' ').strip()
# 由于提交信息已经在拆分时处理过,这里只需要简单清理
if any(prefix in message for prefix in ['feat:', 'fix:', 'refactor:', 'feat:', 'fix:', 'refactor:']):
message = message.split(':', 1)[-1].split(':', 1)[-1].strip()
# 保留完整的提交信息,不进行长度截断
category_name = category.split(' ', 1)[1] if ' ' in category else category
important_items.append(f"• {category_name}: {message}")
table_content += '\n' + '\n'.join(important_items[:15]) # 增加显示数量以容纳拆分后的项目
if len(important_items) > 15:
table_content += f"\n• 其他工作: 还完成了{len(important_items)-15}项其他开发任务"
# 添加工作亮点总结
table_content += f"\n\n工作亮点:"
highlights = []
if feature_count > 0:
highlights.append(f"新功能开发{feature_count}个")
if bug_count > 0:
highlights.append(f"问题修复{bug_count}个")
if refactor_count > 0:
highlights.append(f"代码优化{refactor_count}次")
if len(self.modules_changed) > 5:
highlights.append(f"跨{len(self.modules_changed)}个模块协作")
if avg_commits_per_day > 2:
highlights.append(f"高效开发(日均{avg_commits_per_day:.1f}次提交)")
table_content += ' | '.join(highlights)
# 添加简洁总结
table_content += f"\n\n工作总结:"
if feature_count >= bug_count:
focus = "主要专注新功能开发"
else:
focus = "主要专注问题修复优化"
table_content += f"本周完成{len(commits)}次提交({total_work_items}个工作项),{focus},涉及{len(self.modules_changed)}个模块{total_files_changed}个文件,"
if avg_commits_per_day > 2:
table_content += "保持高效开发节奏。"
else:
table_content += "注重代码质量。"
return table_content
def generate_summary(self, author='xuhang'):
"""生成工作总结"""
start_date, end_date = self.get_week_range()
print(f"📊 生成 {start_date} 至 {end_date} 的工作总结")
print(f"👤 作者筛选: {author}\n")
commits = self.get_git_commits(start_date, end_date, author)
if not commits:
print(f"❌ 本周没有找到 {author} 的提交记录")
return
# 按类型分组提交
commit_categories = defaultdict(list)
total_files_changed = 0
split_commit_items = [] # 存储拆分后的提交项
for commit in commits:
# 拆分提交信息
split_messages = self.split_commit_message(commit['message'])
# 获取文件变更信息
files = self.get_commit_files(commit['hash'])
total_files_changed += len(files)
for file_info in files:
filename = file_info['filename']
self.file_changes[filename] += 1
module = self.analyze_modules(filename)
self.modules_changed.add(module)
# 为每个拆分的消息创建单独的项目
for split_message in split_messages:
category = self.categorize_commit(split_message)
# 创建新的提交项,包含拆分后的消息
split_commit_item = commit.copy()
split_commit_item['message'] = split_message
split_commit_item['is_split'] = len(split_messages) > 1
commit_categories[category].append(split_commit_item)
split_commit_items.append(split_commit_item)
# 生成报告
print("=" * 60)
print("📈 本周工作总结报告")
print("=" * 60)
print(f"\n📅 时间范围: {start_date} ~ {end_date}")
print(f"📝 总提交数: {len(commits)}")
print(f"📋 工作项数: {len(split_commit_items)} (拆分后)")
print(f"📁 修改文件数: {total_files_changed}")
print(f"🏗️ 涉及模块数: {len(self.modules_changed)}")
# 按类型显示提交
print(f"\n{'='*40}")
print("📋 提交分类统计")
print(f"{'='*40}")
for category, category_commits in sorted(commit_categories.items()):
print(f"\n{category} ({len(category_commits)}个)")
print("-" * 50)
for commit in category_commits:
date_str = commit['date'][:16] # 只显示日期和时间
split_indicator = " [拆分]" if commit.get('is_split', False) else ""
print(f" • {date_str} - {commit['message']}{split_indicator}")
print(f" [{commit['hash'][:8]}]")
# 显示主要修改的模块
print(f"\n{'='*40}")
print("🏗️ 主要修改模块")
print(f"{'='*40}")
for module in sorted(self.modules_changed):
print(f" • {module}")
# 显示修改最频繁的文件
print(f"\n{'='*40}")
print("📁 修改最频繁的文件 (Top 10)")
print(f"{'='*40}")
sorted_files = sorted(self.file_changes.items(), key=lambda x: x[1], reverse=True)
for filename, count in sorted_files[:10]:
print(f" • {filename} ({count}次)")
# 生成表格友好格式
table_content = self.generate_table_format(
start_date, end_date, author, commits, split_commit_items,
commit_categories, total_files_changed, sorted_files
)
# 保存表格友好格式到文件
table_filename = f"weekly_summary_{author}_{start_date}_to_{end_date}_表格版.xuhang"
try:
with open(table_filename, 'w', encoding='utf-8') as f:
f.write(table_content)
print(f"\n📋 表格友好格式已保存到: {table_filename}")
except Exception as e:
print(f"\n❌ 保存表格文件失败: {e}")
# 在控制台显示表格友好格式
print(f"\n{'='*60}")
print("📋 表格友好格式 (可直接复制粘贴)")
print(f"{'='*60}")
print(table_content)
print(f"\n{'='*60}")
print("✅ 工作总结生成完成!")
print(f"{'='*60}")
def main():
"""主函数"""
try:
# 检查是否在Git仓库中
result = subprocess.run(['git', 'rev-parse', '--git-dir'],
capture_output=True, text=True)
if result.returncode != 0:
print("❌ 当前目录不是Git仓库")
sys.exit(1)
# 获取命令行参数中的作者名称,默认为 xuhang
author = 'xuhang'
if len(sys.argv) > 1:
author = sys.argv[1]
# 生成工作总结
summary_generator = WeeklyWorkSummary()
summary_generator.generate_summary(author)
except KeyboardInterrupt:
print("\n\n⚠️ 用户中断操作")
sys.exit(1)
except Exception as e:
print(f"❌ 程序执行出错: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
作者:admin 创建时间:2025-08-28 09:41
最后编辑:admin 更新时间:2025-08-28 09:44
最后编辑:admin 更新时间:2025-08-28 09:44