ホームページ  >  記事  >  バックエンド開発  >  GitHub Actions と Commitizen を使用した Python ライブラリのリリースの自動化

GitHub Actions と Commitizen を使用した Python ライブラリのリリースの自動化

WBOY
WBOYオリジナル
2024-08-28 18:31:19779ブラウズ

Automating Python Library Releases Using GitHub Actions and Commitizen

導入

Python ライブラリの保守は、特に新しいバージョンをリリースする場合に困難になることがあります。このプロセスを手動で行うと、時間がかかり、エラーが発生しやすくなります。この投稿では、GitHub Actions と Commitizen を使用してリリース プロセスを自動化する手順を説明します。このアプローチにより、リリースの一貫性が確保され、セマンティック バージョニング (semver) が遵守され、変更ログが最新に保たれると同時に、手動による介入が減ります。

セマンティック バージョニングとは何ですか?

セマンティック バージョニング (semver) は、MAJOR.MINOR.PATCH 形式の 3 つの数値を使用するバージョン管理スキームです。このスキームは、各リリースでの変更点を伝える明確かつ予測可能な方法を提供します。

  • メジャー: 破壊的変更 - 下位互換性のないもの。
  • マイナー: 新機能ですが下位互換性があります。
  • パッチ: バグ修正 - 完全な下位互換性。

セマンティック バージョニングは、開発者が依存関係を効果的に管理するのに役立つため、非常に重要です。ライブラリの新しいバージョンに重大な変更 (マイナー アップデートやパッチ アップデートなど) が導入されないことがわかっている場合は、アプリケーションの破損を心配することなく、自信を持って依存関係を更新できます。

semver の詳細については、semver.org をご覧ください。

コミッティンの紹介

Commitizen は、コミットメッセージを標準化し、バージョン管理と変更ログの作成を自動化するツールです。特定のコミット メッセージ形式を強制することにより、Commitizen は必要なバージョン バンプの種類 (メジャー、マイナー、またはパッチ) を判断し、変更ログを自動的に生成できます。

コミットメッセージの形式は次の構造に従います:

<commit-type>(<topic>): the commit message
  • コミットタイプ:
    • feat: 新しい機能を示します。これにより、マイナーなバージョンの変更が発生する可能性があります。コミットに重大な変更に関するメモが含まれている場合、メジャー バージョンのバンプが発生します。
    • 修正: バグ修正を示し、パッチ バージョンのバンプにつながります。
    • choreci、その他: これらはバージョンバンプを引き起こしません。

例:

feat(parser): add support for parsing new file formats
fix(api): handle null values in the response
feat(api): change response of me endpoint

BREAKING CHANGE: 

changes the API signature of the parser function

この例では、feat コミット内の BREAKING CHANGE ノートがメジャー バージョン バンプをトリガーします。この一貫性により、バージョン番号が適切なレベルの変更を確実に伝えることができます。これは、ライブラリを利用するユーザーにとって重要です。

コミティゼンの構成

Commitizen を Python プロジェクトと統合するには、pyproject.toml ファイルで構成する必要があります。追加する必要がある構成は次のとおりです:

[tool.commitizen]
name = "cz_conventional_commits"
version = "0.1.0"
tag_format = "v$version"
version_files = [
    "pyproject.toml:version",
]
update_changelog_on_bump = true

説明:

  • name: 使用するコミットメッセージ規約を指定します。従来のコミット形式を使用しています。
  • version: プロジェクトの現在のバージョン。 「0.1.0」または初期バージョンから始める必要があります。
  • tag_format: タグのフォーマット方法を定義します。v$version が一般的なフォーマット (v1.0.0、v1.1.0 など) です。
  • version_files: バージョン番号が追跡されるファイルのリストを表示します。この設定により、pyproject.toml のバージョン番号が自動的に更新されます。
  • update_changelog_on_bump: バージョンアップが発生するたびに、CHANGELOG.md ファイルを自動的に更新します。

リリースプロセスを自動化する理由

リリースを手動で管理するのは面倒で、特にプロジェクトが成長するにつれてエラーが発生しやすくなります。自動化はいくつかの重要な利点をもたらします:

  • 一貫性: バージョン バンプと変更ログが毎回同じ方法で処理されるようにします。
  • 効率: 新しいバージョンのリリースに必要な手動手順を減らし、時間を節約します。
  • 精度: 変更ログの更新を忘れたり、バージョンを誤って変更したりするなどの人的エラーを最小限に抑えます。

概要: 自動リリースプロセス

自動化がどのように機能するかを明確に理解できるように、概要を次に示します。

  1. メインへのマージ時: プル リクエスト (PR) がメイン ブランチにマージされると、ワークフローはコミット メッセージをチェックし、バージョン バンプが必要かどうかを判断し、変更ログを更新し、必要に応じてリリースにタグを付けます。 .
  2. タグ作成時: タグがプッシュされると (新しいリリースを示す)、ワークフローは新しいバージョンを PyPI に公開し、対応する変更ログを含む GitHub リリースを作成します。

ワークフローの分割: イベントのマージとタグ付け

簡単かつ明確にするために、自動化を 2 つのワークフローに分割します。

  1. Merge to Main Workflow
  2. On Tag Creation Workflow

Workflow 1: On Merge to Main

This workflow handles the logic of detecting changes and bumping the version:

name: Merge to Main

on:
  push:
    branches:
      - "main"

concurrency:
  group: main
  cancel-in-progress: true

jobs:
  bump:
    if: "!startsWith(github.event.head_commit.message, 'bump:')"
    runs-on: ubuntu-latest
    steps:
      - name: Setup Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"
      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
          fetch-depth: 0
      - name: Create bump and changelog
        uses: commitizen-tools/commitizen-action@0.21.0
        with:
          github_token: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
          branch: main

Explanation:

  • Trigger: This workflow is triggered when a new commit is pushed to the main branch.
  • Concurrency: The concurrency setting ensures that only one instance of the workflow runs at a time for the main branch, preventing race conditions and duplicate version bumps.
  • bump job: It checks whether the commit message starts with ‘bump:’, which indicates an automated commit from the previous release. If not, Commitizen determines the necessary version bump based on the commit messages, updates the CHANGELOG.md, and creates a new tag.

Workflow 2: On Tag Creation

This workflow is triggered when a tag is pushed, and it handles the release process:

name: On Tag Creation

on:
  push:
    tags:
      - 'v*'

concurrency:
  group: tag-release-${{ github.ref }}
  cancel-in-progress: true

jobs:
  detect-release-parameters:
    runs-on: ubuntu-latest
    outputs:
      notes: ${{ steps.generate_notes.outputs.notes }}
    steps:
      - name: Setup Python
        uses: actions/setup-python@v5
      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - name: Get release notes
        id: generate_notes
        uses: anmarkoulis/commitizen-changelog-reader@v1.2.0
        with:
          tag_name: ${{ github.ref }}
          changelog: CHANGELOG.md

  release:
    runs-on: ubuntu-20.04
    needs: detect-release-parameters
    steps:
      - name: Checkout repo
        uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.10"
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install poetry
      - name: Configure pypi token
        run: |
          poetry config pypi-token.pypi ${{ secrets.PYPI_TOKEN }}
      - name: Build and publish package
        run: |
          poetry publish --build

  release-github:
    runs-on: ubuntu-latest
    needs: [release, detect-release-parameters]
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4
      - name: Create Release Notes File
        run: |
          echo "${{ join(fromJson(needs.detect-release-parameters.outputs.notes).notes, '') }}" > release_notes.txt
      - name: Create GitHub Release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          VERSION: ${{ github.ref_name }}
        run: |
          gh release create ${{ github.ref }} \
          --title "Release $VERSION" \
          --notes-file "release_notes.txt"

Explanation:

  • Trigger: This workflow is triggered by a tag push (e.g., v1.2.0).
  • Concurrency: The concurrency setting ensures that only one instance of the workflow runs for each tag, preventing issues like multiple release attempts for the same version.
  • detect-release-parameters job: Extracts the changelog notes for the release.
  • release job: Builds the package and publishes it to PyPI using Poetry.
  • release-github job: Creates a new GitHub release with the generated release notes.

Setting Up the Personal Access Token

To ensure the workflows can perform actions like creating commits and tagging releases, you’ll need to set up a Personal Access Token (PAT) in your GitHub repository:

  1. Go to your repository on GitHub.
  2. Navigate to Settings > Secrets and variables > Actions.
  3. Click on New repository secret.
  4. Add a secret with the name PERSONAL_ACCESS_TOKEN and paste your PAT in the value field.

This token is crucial because it allows the workflow to push changes (like the updated changelog and version bump) back to the repository.

Generated CHANGELOG.md Example

After running the workflows, a CHANGELOG.md file will be generated and updated automatically. Here’s an example of what it might look like:

## v2.0.0 (2021-03-31)

### Feat

- **api**: change response of me endpoint

## v1.0.1 (2021-03-30)

### Fix

- **api**: handle null values in the response

## v1.0.0 (2021-03-30)

### Feat

- **parser**: add support for parsing new file formats

This CHANGELOG.md is automatically updated by Commitizen each time a new version is released. It categorizes changes into different sections (e.g., Feat, Fix), making it easy for users and developers to see what's new in each version.

Common Issues and Troubleshooting

Finally, here’s what a GitHub release looks like after being created by the workflow:

  • Incorrect Token Permissions: If the workflow fails due to permission errors, ensure that the PAT has the necessary scopes (e.g., repo, workflow).

  • Commitizen Parsing Issues: If Commitizen fails to parse commit messages, double-check the commit format and ensure it's consistent with the expected format.

  • Bump Commit Conflicts: If conflicts arise when the bump commit tries to merge into the main branch, you might need to manually resolve the conflicts or adjust your workflow to handle them.

  • Concurrent Executions: Without proper concurrency control, multiple commits or tags being processed simultaneously can lead to issues like duplicate version bumps or race conditions. This can result in multiple commits with the same version or incomplete releases. To avoid this, we’ve added concurrency settings to both workflows to ensure only one instance runs at a time for each branch or tag.

Conclusion and Next Steps

Automating the release process of your Python library with GitHub Actions and Commitizen not only saves time but also ensures consistency and reduces human errors. With this setup, you can focus more on developing new features and less on the repetitive tasks of managing releases.

As a next step, consider extending your CI/CD pipeline to include automated testing, code quality checks, or even security scans. This would further enhance the robustness of your release process.

Call to Action

If you found this post helpful, please feel free to share it with others who might benefit. I’d love to hear your thoughts or any questions you might have in the comments below. Have you implemented similar workflows in your projects? Share your experiences!

参考文献と詳細情報

  • セマンティック バージョニング 公式サイト
  • コミッティンドキュメント
  • GitHub アクションのドキュメント

以上がGitHub Actions と Commitizen を使用した Python ライブラリのリリースの自動化の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
前の記事:変数 その04次の記事:変数 その04