feat.动画优化与更新界面

This commit is contained in:
lincube
2026-05-17 19:36:07 +08:00
parent a5abda62dc
commit 9404a0b347
29 changed files with 1607 additions and 71 deletions

144
scripts/analyze_commits.ps1 Normal file
View File

@@ -0,0 +1,144 @@
# Analyze Git commits from today and generate Markdown reports
param(
[string]$RepoPath = (Split-Path -Parent $PSScriptRoot)
)
Write-Host "Analyzing repository: $RepoPath"
# Create output directory
$outputDir = Join-Path (Join-Path $RepoPath "docs") "auto_commit_md"
if (-not (Test-Path $outputDir)) {
New-Item -ItemType Directory -Path $outputDir -Force | Out-Null
Write-Host "Created directory: $outputDir"
} else {
Write-Host "Output directory: $outputDir"
}
Write-Host ""
# Get today's date range
$today = Get-Date
$todayStart = $today.Date.ToString("yyyy-MM-ddTHH:mm:ss")
$todayEnd = $today.Date.AddDays(1).AddSeconds(-1).ToString("yyyy-MM-ddTHH:mm:ss")
# Get commits from today
$commitsOutput = & git -C $RepoPath log --since="$todayStart" --until="$todayEnd" --pretty=format:"%H|%an|%ae|%ad|%s" --date=iso
if (-not $commitsOutput) {
Write-Host "No new commits today."
exit 0
}
$commits = @()
foreach ($line in $commitsOutput -split "`n") {
if (-not $line) { continue }
$parts = $line -split '\|', 5
if ($parts.Count -eq 5) {
$commits += @{
Hash = $parts[0]
AuthorName = $parts[1]
AuthorEmail = $parts[2]
Date = $parts[3]
Message = $parts[4]
}
}
}
Write-Host "Found $($commits.Count) commits today."
Write-Host ""
foreach ($commit in $commits) {
$shortHash = $commit.Hash.Substring(0, 7)
Write-Host "Processing commit: $shortHash - $($commit.Message)"
# Get commit details
$diffStat = & git -C $RepoPath show --stat $commit.Hash
$diffDetails = & git -C $RepoPath show $commit.Hash
# Parse statistics
$filesChanged = @()
$totalInsertions = 0
$totalDeletions = 0
foreach ($line in $diffStat -split "`n") {
if ($line -match '(\d+) insertion') {
$totalInsertions += [int]$matches[1]
}
if ($line -match '(\d+) deletion') {
$totalDeletions += [int]$matches[1]
}
if ($line -match '^\s*(.*?)\s*\|\s*(\d+)') {
$filesChanged += @{
File = $matches[1]
Lines = [int]$matches[2]
}
}
}
# Generate filename
$dateStr = $commit.Date.Split(' ')[0].Replace('-', '')
$filename = "$dateStr`_$shortHash.md"
$outputPath = Join-Path $outputDir $filename
# Generate Markdown content
$report = @"
# Commit Analysis Report - $shortHash
## Basic Information
| Item | Content |
|------|---------|
| Commit Hash | `` $($commit.Hash) `` |
| Author | $($commit.AuthorName) ($($commit.AuthorEmail)) |
| Commit Time | $($commit.Date) |
## Commit Message
$($commit.Message)
## Change Statistics
| Metric | Value |
|--------|-------|
| Files Changed | $($filesChanged.Count) |
| Lines Added | +$totalInsertions |
| Lines Removed | -$totalDeletions |
## Modified Files
"@
foreach ($file in $filesChanged) {
$report += "- $($file.File) ($($file.Lines) lines)`n"
}
$report += @"
## Detailed Changes
```diff
$diffDetails
```
## Code Review Checklist
> This section is auto-generated, manual review recommended
- [ ] Check for potential bugs
- [ ] Verify code follows project standards
- [ ] Test new functionality if applicable
- [ ] Check for security issues
---
*Report generated: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")*
"@
# Save file
[System.IO.File]::WriteAllText($outputPath, $report, [System.Text.Encoding]::UTF8)
Write-Host " Report saved: $outputPath"
}
Write-Host ""
Write-Host "Done!"

206
scripts/analyze_commits.py Normal file
View File

@@ -0,0 +1,206 @@
#!/usr/bin/env python3
"""
分析当天 Git 提交并生成 Markdown 报告的脚本
"""
import os
import subprocess
import sys
from datetime import datetime
import re
def run_command(cmd, cwd=None):
"""运行命令并返回输出"""
try:
result = subprocess.run(
cmd,
shell=True,
capture_output=True,
text=True,
cwd=cwd,
encoding='utf-8',
errors='replace'
)
return result.stdout, result.stderr, result.returncode
except Exception as e:
return "", str(e), 1
def get_today_commits(repo_path):
"""获取当天的所有提交"""
today_start = datetime.now().strftime('%Y-%m-%dT00:00:00')
today_end = datetime.now().strftime('%Y-%m-%dT23:59:59')
cmd = f'git log --since="{today_start}" --until="{today_end}" --pretty=format:"%H|%an|%ae|%ad|%s" --date=iso'
stdout, stderr, code = run_command(cmd, cwd=repo_path)
if code != 0:
print(f"Error getting commits: {stderr}")
return []
commits = []
for line in stdout.strip().split('\n'):
if not line:
continue
parts = line.split('|', 4)
if len(parts) == 5:
commits.append({
'hash': parts[0],
'author_name': parts[1],
'author_email': parts[2],
'date': parts[3],
'message': parts[4]
})
return commits
def get_commit_diff(repo_path, commit_hash):
"""获取提交的详细 diff"""
cmd = f'git show --stat {commit_hash}'
stdout, _, _ = run_command(cmd, cwd=repo_path)
return stdout
def get_commit_details(repo_path, commit_hash):
"""获取提交的详细信息"""
cmd = f'git show {commit_hash}'
stdout, _, _ = run_command(cmd, cwd=repo_path)
return stdout
def parse_diff_stats(diff_stat):
"""解析 diff --stat 的输出"""
files_changed = []
total_insertions = 0
total_deletions = 0
lines = diff_stat.strip().split('\n')
for line in lines:
match = re.search(r'(\d+) insertion', line)
if match:
total_insertions += int(match.group(1))
match = re.search(r'(\d+) deletion', line)
if match:
total_deletions += int(match.group(1))
file_match = re.match(r'^\s*(.*?)\s*\|\s*(\d+)', line)
if file_match:
files_changed.append({
'file': file_match.group(1),
'lines': int(file_match.group(2))
})
return {
'files': files_changed,
'insertions': total_insertions,
'deletions': total_deletions
}
def generate_markdown_report(commit, diff_stat, diff_details):
"""生成 Markdown 报告"""
short_hash = commit['hash'][:7]
date_str = commit['date'].split(' ')[0].replace('-', '')
report = f"""# 提交分析报告 - {short_hash}
## 基本信息
| 项目 | 内容 |
|------|------|
| 提交哈希 | `{commit['hash']}` |
| 作者 | {commit['author_name']} ({commit['author_email']}) |
| 提交时间 | {commit['date']} |
## 提交信息
{commit['message']}
## 变更统计
| 指标 | 数值 |
|------|------|
| 修改文件数 | {len(diff_stat['files'])} |
| 新增行数 | +{diff_stat['insertions']} |
| 删除行数 | -{diff_stat['deletions']} |
## 修改文件列表
"""
for file_info in diff_stat['files']:
report += f"- {file_info['file']} ({file_info['lines']} 行)\n"
report += f"""
## 详细变更
```diff
{diff_details}
```
## 代码审查要点
> 此部分为自动生成,建议人工审查确认
- [ ] 检查是否有潜在的 bug
- [ ] 确认代码符合项目规范
- [ ] 验证是否有需要测试的新功能
- [ ] 检查是否有安全问题
---
*报告生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
"""
return report, f"{date_str}_{short_hash}.md"
def main():
repo_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
output_dir = os.path.join(repo_path, 'docs', 'auto_commit_md')
# 创建输出目录
os.makedirs(output_dir, exist_ok=True)
print(f"分析仓库: {repo_path}")
print(f"输出目录: {output_dir}")
print()
# 获取当天的提交
commits = get_today_commits(repo_path)
if not commits:
print("今天没有新提交。")
return 0
print(f"找到 {len(commits)} 个今天的提交。")
print()
for commit in commits:
print(f"处理提交: {commit['hash'][:7]} - {commit['message']}")
# 获取提交详情
diff_stat = get_commit_diff(repo_path, commit['hash'])
diff_details = get_commit_details(repo_path, commit['hash'])
# 解析统计信息
stats = parse_diff_stats(diff_stat)
# 生成报告
report_content, filename = generate_markdown_report(commit, stats, diff_details)
# 保存文件
output_path = os.path.join(output_dir, filename)
with open(output_path, 'w', encoding='utf-8') as f:
f.write(report_content)
print(f" 报告已保存: {output_path}")
print()
print("完成!")
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@@ -0,0 +1,177 @@
#!/usr/bin/env python3
import subprocess
import os
import re
from datetime import datetime
from pathlib import Path
def run_git_command(cmd, cwd=None):
result = subprocess.run(cmd, shell=True, capture_output=True, text=True, cwd=cwd)
if result.returncode != 0:
print(f"Git command failed: {cmd}")
print(f"Error: {result.stderr}")
return None
return result.stdout
def get_commits_since(since_date, until_date, cwd=None):
cmd = f'git log --since="{since_date}" --until="{until_date}" --pretty=format:"%H|%an|%ae|%ad|%s" --date=iso'
output = run_git_command(cmd, cwd)
if not output:
return []
commits = []
for line in output.strip().split('\n'):
if line:
parts = line.split('|', 4)
commits.append({
'hash': parts[0],
'author': parts[1],
'email': parts[2],
'date': parts[3],
'message': parts[4]
})
return commits
def get_commit_diff(commit_hash, cwd=None):
cmd = f'git show {commit_hash}'
return run_git_command(cmd, cwd)
def get_commit_stat(commit_hash, cwd=None):
cmd = f'git show --stat {commit_hash}'
return run_git_command(cmd, cwd)
def analyze_diff(diff_text):
file_changes = []
current_file = None
changes = {'insertions': 0, 'deletions': 0, 'files': 0}
lines = diff_text.split('\n')
for line in lines:
if line.startswith('diff --git'):
if current_file:
file_changes.append(current_file)
filename = line.split(' ')[2][2:]
current_file = {'name': filename, 'insertions': 0, 'deletions': 0, 'hunks': []}
changes['files'] += 1
elif line.startswith('+') and not line.startswith('+++'):
if current_file:
current_file['insertions'] += 1
changes['insertions'] += 1
elif line.startswith('-') and not line.startswith('---'):
if current_file:
current_file['deletions'] += 1
changes['deletions'] += 1
if current_file:
file_changes.append(current_file)
return file_changes, changes
def generate_markdown_report(commit, diff_text, stat_text, output_dir):
file_changes, summary = analyze_diff(diff_text)
short_hash = commit['hash'][:7]
date_obj = datetime.fromisoformat(commit['date'].replace(' +0800', ''))
date_str = date_obj.strftime('%Y%m%d')
filename = f"{date_str}_{short_hash}.md"
filepath = Path(output_dir) / filename
markdown = f"""# Git 提交分析报告
## 基本信息
| 项目 | 内容 |
|------|------|
| 提交哈希 | `{commit['hash']}` |
| 短哈希 | `{short_hash}` |
| 作者 | {commit['author']} <{commit['email']}> |
| 提交时间 | {commit['date']} |
## 提交信息
{commit['message']}
## 变更统计
- **变更文件数**: {summary['files']}
- **新增行数**: +{summary['insertions']}
- **删除行数**: -{summary['deletions']}
## 详细变更
"""
if file_changes:
for fc in sorted(file_changes, key=lambda x: x['name']):
markdown += f"\n### `{fc['name']}`\n"
markdown += f"- 新增: +{fc['insertions']}\n"
markdown += f"- 删除: -{fc['deletions']}\n"
else:
markdown += "\n*无文件变更统计*\n"
markdown += "\n## 完整 Diff\n\n```diff\n"
markdown += diff_text
markdown += "\n```\n"
with open(filepath, 'w', encoding='utf-8') as f:
f.write(markdown)
print(f"Generated: {filepath}")
return filepath
def main():
repo_dir = Path(__file__).parent.parent
output_dir = repo_dir / 'docs' / 'auto_commit_md'
output_dir.mkdir(parents=True, exist_ok=True)
today = datetime.now()
since_date = today.strftime('%Y-%m-%d 00:00:00')
until_date = today.strftime('%Y-%m-%d 23:59:59')
print(f"Fetching commits from {since_date} to {until_date}...")
commits = get_commits_since(since_date, until_date, str(repo_dir))
if not commits:
print("No commits found for today.")
print("\nLet's check the latest commits instead...")
cmd = 'git log -3 --pretty=format:"%H|%an|%ae|%ad|%s" --date=iso'
output = run_git_command(cmd, str(repo_dir))
if output:
commits = []
for line in output.strip().split('\n'):
if line:
parts = line.split('|', 4)
commits.append({
'hash': parts[0],
'author': parts[1],
'email': parts[2],
'date': parts[3],
'message': parts[4]
})
if commits:
print(f"\nFound {len(commits)} commit(s) to analyze:\n")
for commit in commits:
print(f" - {commit['hash'][:7]}: {commit['message']}")
print("\nGenerating reports...\n")
for commit in commits:
diff = get_commit_diff(commit['hash'], str(repo_dir))
stat = get_commit_stat(commit['hash'], str(repo_dir))
if diff:
generate_markdown_report(commit, diff, stat, str(output_dir))
print(f"\nDone! Reports saved to {output_dir}")
else:
print("No commits found.")
if __name__ == '__main__':
main()