实用脚本能自动生成变更日志吗?

wen 实用脚本 3

本文目录导读:

实用脚本能自动生成变更日志吗?

  1. 基于 Git 提交的常用工具
  2. Python 脚本示例
  3. Node.js 脚本
  4. 集成到开发流程中
  5. 最佳实践建议

是的,有多种实用脚本可以自动生成变更日志,以下是一些主流解决方案:

基于 Git 提交的常用工具

Standard Version (推荐)

# 安装
npm install -g standard-version
# 自动生成变更日志
standard-version
# 只生成 changelog,不创建 tag
standard-version --dry-run

conventional-changelog-cli

# 安装
npm install -g conventional-changelog-cli
# 生成 changelog
conventional-changelog -p angular -i CHANGELOG.md -s -r 0
# 增量生成
conventional-changelog -p angular -i CHANGELOG.md -s

Git 自动化脚本示例

#!/bin/bash
# auto-changelog.sh
# 基于提交信息生成 changelog
git log --pretty=format:"- %s (%h)" --since="1 month ago" > CHANGELOG.md
# 分类提交
git log --pretty=format:"%s" | while read line; do
    if [[ $line =~ ^feat ]]; then
        echo "## 新功能" >> CHANGELOG.md
        echo "- $line" >> CHANGELOG.md
    elif [[ $line =~ ^fix ]]; then
        echo "## Bug 修复" >> CHANGELOG.md
        echo "- $line" >> CHANGELOG.md
    fi
done

Python 脚本示例

# auto_changelog.py
import subprocess
import re
from datetime import datetime
def generate_changelog():
    # 获取 git 提交记录
    result = subprocess.run(
        ['git', 'log', '--oneline', '--since=1 month ago'],
        capture_output=True, text=True
    )
    commits = result.stdout.split('\n')
    changelog = f"# Changelog\n\n## {datetime.now().strftime('%Y-%m-%d')}\n\n"
    categories = {
        'feat': '🚀 新功能',
        'fix': '🐛 Bug 修复',
        'docs': '📝 文档更新',
        'refactor': '🔧 代码重构',
        'test': '✅ 测试'
    }
    for category, title in categories.items():
        items = [c for c in commits if c.startswith(category)]
        if items:
            changelog += f"### {title}\n\n"
            for item in items:
                changelog += f"- {item[item.find(':')+1:].strip()}\n"
            changelog += "\n"
    # 写入文件
    with open('CHANGELOG.md', 'w') as f:
        f.write(changelog)
if __name__ == '__main__':
    generate_changelog()

Node.js 脚本

// changelog-generator.mjs
import { execSync } from 'child_process';
import { writeFileSync } from 'fs';
function generateChangelog() {
  const commits = execSync('git log --oneline --since="1 month ago"')
    .toString()
    .trim()
    .split('\n');
  const changelog = {
    'feat': '✨ 新功能',
    'fix': '🐛 修复',
    'docs': '📖 文档',
    'refactor': '♻️ 重构',
    'chore': '🔧 杂项'
  };
  let content = `# 更新日志\n\n## ${new Date().toISOString().split('T')[0]}\n\n`;
  Object.entries(changelog).forEach(([prefix, title]) => {
    const items = commits
      .filter(c => c.startsWith(prefix))
      .map(c => `- ${c.substring(c.indexOf(':') + 1).trim()}`);
    if (items.length > 0) {
      content += `### ${title}\n\n${items.join('\n')}\n\n`;
    }
  });
  writeFileSync('CHANGELOG.md', content);
  console.log('✅ 更新日志已生成!');
}
generateChangelog();

集成到开发流程中

Git hooks (pre-commit)

# .git/hooks/pre-commit
#!/bin/bash
# 在提交时自动更新 changelog
node changelog-generator.mjs
git add CHANGELOG.md

CI/CD 配置 (GitHub Actions)

# .github/workflows/changelog.yml
name: Generate Changelog
on:
  push:
    tags:
      - 'v*'
jobs:
  changelog:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Generate changelog
        run: npx conventional-changelog-cli -p angular -i CHANGELOG.md -s
      - name: Commit changelog
        run: |
          git config user.name github-actions
          git config user.email github-actions@github.com
          git add CHANGELOG.md
          git commit -m "docs: update changelog"
          git push

最佳实践建议

提交信息规范

确保使用标准化的 commit 格式:

<type>(<scope>): <subject>
feat: 添加新功能
fix: 修复 bug
docs: 更新文档
refactor: 重构代码
test: 添加测试
chore: 维护工作

推荐工具选择

  • 小型项目:直接使用 git log 脚本
  • 中大型项目:standard-version 或 conventional-changelog
  • 全自动化:集成到 CI/CD 流程

选择哪种方式取决于你的项目规模、团队的 commit 规范程度以及自动化需求。

抱歉,评论功能暂时关闭!