백엔드 개발 파이썬 튜토리얼 GitHub Actions 및 Commitizen을 사용하여 Python 라이브러리 릴리스 자동화

GitHub Actions 및 Commitizen을 사용하여 Python 라이브러리 릴리스 자동화

Aug 28, 2024 pm 06:31 PM

Automating Python Library Releases Using GitHub Actions and Commitizen

소개

Python 라이브러리를 유지 관리하는 것은 어려울 수 있으며, 특히 새 버전을 출시하는 경우에는 더욱 그렇습니다. 이 프로세스를 수동으로 수행하면 시간이 많이 걸리고 오류가 발생하기 쉽습니다. 이 게시물에서는 GitHub Actions 및 Commitizen을 사용하여 릴리스 프로세스를 자동화하는 방법을 안내하겠습니다. 이 접근 방식을 사용하면 릴리스의 일관성, 의미론적 버전 관리(semver) 준수, 변경 로그를 최신 상태로 유지하는 동시에 수동 개입을 줄일 수 있습니다.

의미적 버전 관리란 무엇입니까?

Semantic Versioning(semver)은 MAJOR.MINOR.PATCH 형식의 세 숫자를 사용하는 버전 관리 체계입니다. 이 체계는 각 릴리스의 변경 사항을 전달하는 명확하고 예측 가능한 방법을 제공합니다.

  • 주요: 획기적인 변경 사항 - 이전 버전과 호환되지 않는 모든 것
  • 사소: 새로운 기능이지만 이전 버전과 호환됩니다.
  • 패치: 버그 수정 - 이전 버전과 완전히 호환됩니다.

의미적 버전 관리는 개발자가 종속성을 효과적으로 관리하는 데 도움이 되기 때문에 매우 중요합니다. 새 버전의 라이브러리에 주요 변경 사항(예: 마이너 또는 패치 업데이트)이 적용되지 않는다는 사실을 알게 되면 애플리케이션 중단에 대한 걱정 없이 자신있게 종속성을 업데이트할 수 있습니다.

semver에 대한 자세한 내용은 semver.org를 확인하세요.

커미티즌 소개

Commitizen은 커밋 메시지를 표준화하고 버전 관리 및 변경 로그 생성을 자동화하는 도구입니다. 특정 커밋 메시지 형식을 적용함으로써 Commitizen은 필요한 버전 변경 유형(주, 부 또는 패치)을 결정하고 변경 로그를 자동으로 생성할 수 있습니다.

커밋 메시지 형식은 다음 구조를 따릅니다.

<commit-type>(<topic>): the commit message
로그인 후 복사
  • 커밋 유형:
    • feat: 새로운 기능을 나타냅니다. 이로 인해 마이너 버전 충돌이 발생할 수 있습니다. 커밋에 주요 변경 사항 메모가 포함되어 있으면 주요 버전이 변경됩니다.
    • 수정: 버그 수정을 나타내며 패치 버전이 올라갑니다.
    • chore, ci 및 기타: 버전 충돌을 유발하지 않습니다.

예:

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 커밋 내의 주요 변경 사항 메모는 주요 버전 범프를 유발합니다. 이러한 일관성을 통해 버전 번호가 올바른 변경 수준을 전달할 수 있으며 이는 라이브러리를 사용하는 사용자에게 매우 중요합니다.

커밋 구성

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: 사용할 커밋 메시지 규칙을 지정합니다. 우리는 일반적인 커밋 형식을 사용하고 있습니다.
  • 버전: 프로젝트의 현재 버전입니다. "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 릴리스를 생성합니다.

워크플로 분할: 이벤트 병합과 태그 이벤트

단순성과 명확성을 위해 자동화를 두 가지 워크플로로 나누겠습니다.

  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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

<gum> : Bubble Gum Simulator Infinity- 로얄 키를 얻고 사용하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Nordhold : Fusion System, 설명
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora : 마녀 트리의 속삭임 - Grappling Hook 잠금 해제 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python vs. C : 학습 곡선 및 사용 편의성 Python vs. C : 학습 곡선 및 사용 편의성 Apr 19, 2025 am 12:20 AM

Python은 배우고 사용하기 쉽고 C는 더 강력하지만 복잡합니다. 1. Python Syntax는 간결하며 초보자에게 적합합니다. 동적 타이핑 및 자동 메모리 관리를 사용하면 사용하기 쉽지만 런타임 오류가 발생할 수 있습니다. 2.C는 고성능 응용 프로그램에 적합한 저수준 제어 및 고급 기능을 제공하지만 학습 임계 값이 높고 수동 메모리 및 유형 안전 관리가 필요합니다.

파이썬과 시간 : 공부 시간을 최대한 활용 파이썬과 시간 : 공부 시간을 최대한 활용 Apr 14, 2025 am 12:02 AM

제한된 시간에 Python 학습 효율을 극대화하려면 Python의 DateTime, Time 및 Schedule 모듈을 사용할 수 있습니다. 1. DateTime 모듈은 학습 시간을 기록하고 계획하는 데 사용됩니다. 2. 시간 모듈은 학습과 휴식 시간을 설정하는 데 도움이됩니다. 3. 일정 모듈은 주간 학습 작업을 자동으로 배열합니다.

Python vs. C : 성능과 효율성 탐색 Python vs. C : 성능과 효율성 탐색 Apr 18, 2025 am 12:20 AM

Python은 개발 효율에서 C보다 낫지 만 C는 실행 성능이 높습니다. 1. Python의 간결한 구문 및 풍부한 라이브러리는 개발 효율성을 향상시킵니다. 2.C의 컴파일 유형 특성 및 하드웨어 제어는 실행 성능을 향상시킵니다. 선택할 때는 프로젝트 요구에 따라 개발 속도 및 실행 효율성을 평가해야합니다.

Python 학습 : 2 시간의 일일 연구가 충분합니까? Python 학습 : 2 시간의 일일 연구가 충분합니까? Apr 18, 2025 am 12:22 AM

하루에 2 시간 동안 파이썬을 배우는 것으로 충분합니까? 목표와 학습 방법에 따라 다릅니다. 1) 명확한 학습 계획을 개발, 2) 적절한 학습 자원 및 방법을 선택하고 3) 실습 연습 및 검토 및 통합 연습 및 검토 및 통합,이 기간 동안 Python의 기본 지식과 고급 기능을 점차적으로 마스터 할 수 있습니다.

Python vs. C : 주요 차이점 이해 Python vs. C : 주요 차이점 이해 Apr 21, 2025 am 12:18 AM

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까? Python Standard Library의 일부는 무엇입니까? 목록 또는 배열은 무엇입니까? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

파이썬 : 자동화, 스크립팅 및 작업 관리 파이썬 : 자동화, 스크립팅 및 작업 관리 Apr 16, 2025 am 12:14 AM

파이썬은 자동화, 스크립팅 및 작업 관리가 탁월합니다. 1) 자동화 : 파일 백업은 OS 및 Shutil과 같은 표준 라이브러리를 통해 실현됩니다. 2) 스크립트 쓰기 : PSUTIL 라이브러리를 사용하여 시스템 리소스를 모니터링합니다. 3) 작업 관리 : 일정 라이브러리를 사용하여 작업을 예약하십시오. Python의 사용 편의성과 풍부한 라이브러리 지원으로 인해 이러한 영역에서 선호하는 도구가됩니다.

과학 컴퓨팅을위한 파이썬 : 상세한 모양 과학 컴퓨팅을위한 파이썬 : 상세한 모양 Apr 19, 2025 am 12:15 AM

과학 컴퓨팅에서 Python의 응용 프로그램에는 데이터 분석, 머신 러닝, 수치 시뮬레이션 및 시각화가 포함됩니다. 1.numpy는 효율적인 다차원 배열 및 수학적 함수를 제공합니다. 2. Scipy는 Numpy 기능을 확장하고 최적화 및 선형 대수 도구를 제공합니다. 3. 팬더는 데이터 처리 및 분석에 사용됩니다. 4. matplotlib는 다양한 그래프와 시각적 결과를 생성하는 데 사용됩니다.

See all articles