Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Mengautomasikan Keluaran Pustaka Python Menggunakan Tindakan GitHub dan Commitizen

Mengautomasikan Keluaran Pustaka Python Menggunakan Tindakan GitHub dan Commitizen

WBOY
WBOYasal
2024-08-28 18:31:19778semak imbas

Automating Python Library Releases Using GitHub Actions and Commitizen

pengenalan

Mengekalkan perpustakaan Python boleh menjadi mencabar, terutamanya apabila ia datang untuk mengeluarkan versi baharu. Proses ini boleh memakan masa dan terdedah kepada ralat jika dilakukan secara manual. Dalam siaran ini, saya akan memandu anda mengautomasikan proses keluaran menggunakan GitHub Actions and Commitizen. Pendekatan ini memastikan keluaran anda konsisten, mematuhi versi semantik (semver) dan memastikan log perubahan anda dikemas kini—semuanya sambil mengurangkan campur tangan manual.

Apakah Versi Semantik?

Versi Semantik (semver) ialah skema versi yang menggunakan tiga nombor dalam format MAJOR.MINOR.PATCH. Skim ini menyediakan cara yang jelas dan boleh diramal untuk menyampaikan perkara yang telah berubah dalam setiap keluaran:

  • UTAMA: Memecahkan perubahan—apa-apa sahaja yang tidak serasi ke belakang.
  • MINOR: Ciri baharu, tetapi serasi ke belakang.
  • PATCH: Pembetulan pepijat—serasi ke belakang sepenuhnya.

Versi Semantik adalah penting kerana ia membantu pembangun mengurus kebergantungan dengan berkesan. Apabila anda mengetahui bahawa versi baharu pustaka tidak memperkenalkan perubahan pecah (cth., kemas kini kecil atau tampalan), anda boleh mengemas kini kebergantungan anda dengan yakin tanpa rasa takut aplikasi anda rosak.

Untuk butiran lanjut tentang semver, anda boleh menyemak semver.org.

Pengenalan kepada comitizen

Commitizen ialah alat yang menyeragamkan mesej komit dan mengautomasikan pembuatan versi dan log perubahan. Dengan menguatkuasakan format mesej komitmen tertentu, Commitizen boleh menentukan jenis bonjolan versi yang diperlukan (utama, kecil atau tampalan) dan menjana log perubahan secara automatik.

Format mesej komit mengikut struktur ini:

<commit-type>(<topic>): the commit message
  • Jenis Komit:
    • feat: Menunjukkan ciri baharu. Ini boleh menyebabkan bonjolan versi kecil. Jika komit menyertakan nota PERUBAHAN PECAH, ia menghasilkan bonjolan versi utama.
    • pembetulan: Menunjukkan pembetulan pepijat dan membawa kepada bonggol versi tampalan.
    • tugas, ci dan lain-lain: Ini tidak mencetuskan bonjolan versi.

Contohnya:

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

Dalam contoh ini, nota BREAKING CHANGE dalam komit prestasi akan mencetuskan bonggol versi utama. Ketekalan ini memastikan nombor versi anda menyampaikan tahap perubahan yang betul, yang penting untuk pengguna yang bergantung pada pustaka anda.

Mengkonfigurasi Jawatankuasa

Untuk menyepadukan Commitizen dengan projek Python anda, anda perlu mengkonfigurasinya dalam fail pyproject.toml anda. Di bawah ialah konfigurasi yang perlu anda tambahkan:

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

Penjelasan:

  • nama: Menentukan konvensyen mesej komit untuk digunakan. Kami menggunakan format komitmen konvensional.
  • versi: Versi semasa projek anda. Anda harus bermula dengan "0.1.0" atau apa sahaja versi awal anda.
  • format_tag: Mentakrifkan cara teg diformatkan, dengan v$version ialah format biasa (v1.0.0, v1.1.0, dll.).
  • version_files: Menyenaraikan fail tempat nombor versi dijejaki. Persediaan ini memastikan nombor versi dalam pyproject.toml dikemas kini secara automatik.
  • update_changelog_on_bump: Mengemas kini fail CHANGELOG.md secara automatik apabila bonggol versi berlaku.

Mengapa Automatikkan Proses Keluaran?

Mengurus keluaran secara manual boleh membosankan dan terdedah kepada ralat, terutamanya apabila projek anda berkembang. Automasi membawa beberapa faedah utama:

  • Ketekalan: Memastikan bonjolan versi dan log perubahan dikendalikan dengan cara yang sama setiap kali.
  • Kecekapan: Menjimatkan masa dengan mengurangkan langkah manual yang terlibat dalam mengeluarkan versi baharu.
  • Ketepatan: Meminimumkan ralat manusia, seperti terlupa untuk mengemas kini log perubahan atau tersalah pukul versi.

Gambaran Keseluruhan: Proses Keluaran Automatik

Untuk memberi anda gambaran yang jelas tentang cara automasi berfungsi, berikut ialah gambaran keseluruhan peringkat tinggi:

  1. Pada Gabung ke Utama: Apabila permintaan tarik (PR) digabungkan ke dalam cawangan utama, aliran kerja menyemak mesej komit, memutuskan sama ada bonjolan versi diperlukan, mengemas kini log perubahan dan menandakan keluaran jika perlu .
  2. Pada Penciptaan Teg: Apabila teg ditolak (menunjukkan keluaran baharu), aliran kerja menerbitkan versi baharu kepada PyPI dan mencipta keluaran GitHub dengan log perubahan yang sepadan.

Memisahkan Aliran Kerja: Gabung lwn Acara Teg

Untuk kesederhanaan dan kejelasan, kami akan membahagikan automasi kepada dua aliran kerja:

  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!

Rujukan dan Bacaan Lanjut

  • Tapak Rasmi Versi Semantik
  • Dokumentasi Jawatankuasa
  • Dokumentasi Tindakan GitHub

Atas ialah kandungan terperinci Mengautomasikan Keluaran Pustaka Python Menggunakan Tindakan GitHub dan Commitizen. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel sebelumnya:Pembolehubah Bahagian-04Artikel seterusnya:Pembolehubah Bahagian-04