Debian Codegraph @

docs/tutorials/github_actions.md

raw
1 ## Create a new release with GitHub Actions
2
3 This guide shows you how to automatically bump versions, create changelogs, and publish releases using Commitizen in GitHub Actions.
4
5 !!! tip
6 Check the new [setup-cz](https://github.com/marketplace/actions/setup-commitizen-cli) action, simple and with [examples](https://github.com/commitizen-tools/setup-cz/tree/main/examples)
7
8 ### Prerequisites
9
10 Before setting up the workflow, you'll need:
11
12 1. A personal access token with repository write permissions
13 2. Commitizen configured in your project (see [configuration documentation](../config/configuration_file.md))
14
15 ### Automatic version bumping
16
17 To automatically execute `cz bump` in your CI and push the new commit and tag back to your repository, follow these steps:
18
19 #### Step 1: Create a personal access token
20
21 1. Go to [GitHub Settings > Developer settings > Personal access tokens](https://github.com/settings/tokens)
22 2. Click "Generate new token (classic)"
23 3. Give it a descriptive name (e.g., "Commitizen CI")
24 4. Select the `repo` scope to grant full repository access
25 5. Click "Generate token" and **copy the token immediately** (you won't be able to see it again)
26
27 !!! warning "Important: Use Personal Access Token, not GITHUB_TOKEN"
28 If you use `GITHUB_TOKEN` instead of `PERSONAL_ACCESS_TOKEN`, the workflow won't trigger another workflow run. This is a GitHub security feature to prevent infinite loops. The `GITHUB_TOKEN` is treated like using `[skip ci]` in other CI systems.
29
30 #### Step 2: Add the token as a repository secret
31
32 1. Go to your repository on GitHub
33 2. Navigate to `Settings > Secrets and variables > Actions`
34 3. Click "New repository secret"
35 4. Name it `PERSONAL_ACCESS_TOKEN`
36 5. Paste the token you copied in Step 1
37 6. Click "Add secret"
38
39 #### Step 3: Create the workflow file
40
41 Create a new file `.github/workflows/bumpversion.yml` in your repository with the following content:
42
43 ```yaml title=".github/workflows/bumpversion.yml"
44 name: Bump version
45
46 on:
47 push:
48 branches:
49 - master # or 'main' if that's your default branch
50
51 jobs:
52 bump-version:
53 if: "!startsWith(github.event.head_commit.message, 'bump:')"
54 runs-on: ubuntu-latest
55 name: "Bump version and create changelog with commitizen"
56 steps:
57 - name: Check out
58 uses: actions/checkout@v6
59 with:
60 token: "${{ secrets.PERSONAL_ACCESS_TOKEN }}"
61 fetch-depth: 0
62 - name: Create bump and changelog
63 uses: commitizen-tools/commitizen-action@master
64 with:
65 github_token: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
66 ```
67
68 #### How it works
69
70 - **Trigger**: The workflow runs on every push to the `master` branch (or `main` if you change it)
71 - **Conditional check**: The `if` condition prevents infinite loops by skipping the job if the commit message starts with `bump:`
72 - **Checkout**: Uses your personal access token to check out the repository with full history (`fetch-depth: 0`)
73 - **Bump**: The `commitizen-action` automatically:
74 - Determines the version increment based on your commit messages
75 - Updates version files (as configured in your `pyproject.toml` or other config)
76 - Creates a new git tag
77 - Generates/updates the changelog
78 - Pushes the commit and tag back to the repository
79
80 Once you push this workflow file to your repository, it will automatically run on the next push to your default branch.
81
82 Check out [commitizen-action](https://github.com/commitizen-tools/commitizen-action) for more details.
83
84 ### Creating a GitHub release
85
86 To automatically create a GitHub release when a new version is bumped, you can extend the workflow above.
87
88 The `commitizen-action` creates an environment variable called `REVISION` containing the newly created version. You can use this to create a release with the changelog content.
89
90 ```yaml title=".github/workflows/bumpversion.yml"
91 name: Bump version
92
93 on:
94 push:
95 branches:
96 - master # or 'main' if that's your default branch
97
98 jobs:
99 bump-version:
100 if: "!startsWith(github.event.head_commit.message, 'bump:')"
101 runs-on: ubuntu-latest
102 name: "Bump version and create changelog with commitizen"
103 steps:
104 - name: Check out
105 uses: actions/checkout@v6
106 with:
107 token: "${{ secrets.PERSONAL_ACCESS_TOKEN }}"
108 fetch-depth: 0
109 - name: Create bump and changelog
110 uses: commitizen-tools/commitizen-action@master
111 with:
112 github_token: ${{ secrets.PERSONAL_ACCESS_TOKEN }}
113 changelog_increment_filename: body.md
114 - name: Release
115 uses: ncipollo/release-action@v1
116 with:
117 tag: v${{ env.REVISION }}
118 bodyFile: "body.md"
119 skipIfReleaseExists: true
120 env:
121 GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
122 ```
123
124 You can find the complete workflow in our repository at [bumpversion.yml](https://github.com/commitizen-tools/commitizen/blob/master/.github/workflows/bumpversion.yml).
125
126 ### Previewing the version bump on pull requests
127
128 To help reviewers spot unexpected version bumps before merging, you can run
129 `cz bump --dry-run` on every pull request and post (or update) a sticky
130 comment summarizing the would-be version bump.
131
132 Create `.github/workflows/pr-bump-preview.yml`:
133
134 ```yaml title=".github/workflows/pr-bump-preview.yml"
135 name: PR bump preview
136
137 on:
138 pull_request_target:
139 types: [opened, reopened, synchronize, ready_for_review]
140
141 permissions:
142 contents: read
143 pull-requests: write
144
145 jobs:
146 bump-preview:
147 # Skip drafts and fork PRs (see "How it works" below).
148 if: >
149 ${{
150 github.event.pull_request.draft == false &&
151 github.event.pull_request.head.repo.full_name ==
152 github.event.pull_request.base.repo.full_name
153 }}
154 runs-on: ubuntu-latest
155 steps:
156 - name: Check out PR head
157 uses: actions/checkout@v6
158 with:
159 ref: ${{ github.event.pull_request.head.sha }}
160 fetch-depth: 0
161 fetch-tags: true
162 persist-credentials: false
163 - uses: commitizen-tools/setup-cz@main
164 with:
165 set-git-config: false
166 - name: Run cz bump --dry-run
167 id: dry-run
168 run: |
169 set +e
170 output="$(cz bump --dry-run --yes 2>&1)"
171 status=$?
172 set -e
173 {
174 echo "status=${status}"
175 echo "output<<__CZ_BUMP_PREVIEW__"
176 printf '%s\n' "${output}"
177 echo "__CZ_BUMP_PREVIEW__"
178 } >> "$GITHUB_OUTPUT"
179 - name: Build comment body
180 env:
181 STATUS: ${{ steps.dry-run.outputs.status }}
182 OUTPUT: ${{ steps.dry-run.outputs.output }}
183 run: |
184 {
185 echo "<!-- commitizen-bump-preview -->"
186 echo "## 🔍 Commitizen bump preview"
187 echo ""
188 case "${STATUS}" in
189 0)
190 echo "Merging this PR will produce the following bump:"
191 echo ""
192 echo '```'
193 printf '%s\n' "${OUTPUT}"
194 echo '```'
195 ;;
196 21)
197 echo "No commits in this PR are eligible for a version bump."
198 ;;
199 *)
200 echo "⚠️ \`cz bump --dry-run\` exited with status \`${STATUS}\`:"
201 echo ""
202 echo '```'
203 printf '%s\n' "${OUTPUT}"
204 echo '```'
205 ;;
206 esac
207 } > comment.md
208 - name: Find existing preview comment
209 id: find-comment
210 uses: peter-evans/find-comment@v3
211 with:
212 token: ${{ secrets.GITHUB_TOKEN }}
213 issue-number: ${{ github.event.pull_request.number }}
214 comment-author: "github-actions[bot]"
215 body-includes: "<!-- commitizen-bump-preview -->"
216 - uses: peter-evans/create-or-update-comment@v5
217 with:
218 token: ${{ secrets.GITHUB_TOKEN }}
219 comment-id: ${{ steps.find-comment.outputs.comment-id }}
220 issue-number: ${{ github.event.pull_request.number }}
221 body-path: comment.md
222 edit-mode: replace
223 ```
224
225 #### How it works
226
227 - **Trigger**: `pull_request_target` runs in the context of the base
228 repository, which gives the workflow `pull-requests: write` permission
229 even for PRs from forks. We deliberately gate the job to **same-repo PRs
230 only** (`head.repo == base.repo`); fork PRs are skipped. This is because
231 `cz bump` renders [Jinja templates from the working directory][jinja]
232 whenever [`update_changelog_on_bump`](../config/configuration_file.md) is
233 enabled, and the renderer is not sandboxed — running it against
234 fork-controlled files under a write token would risk arbitrary code
235 execution and token exfiltration. Same-repo PRs are written by
236 collaborators who already have push access, so the same risk doesn't
237 apply.
238 - **Setup**: [`commitizen-tools/setup-cz`](https://github.com/commitizen-tools/setup-cz)
239 installs the Commitizen CLI; no language-specific build tooling is required.
240 - **Defense in depth**: `persist-credentials: false` on `actions/checkout`
241 keeps the workflow token out of the local git config.
242 - **Dry-run**: `cz bump --dry-run --yes` computes the next version (and, if
243 `update_changelog_on_bump` is set in your config, also the changelog
244 entries that would be produced). Exit code `21` (`NoneIncrementExit`)
245 is treated as "no eligible bump" rather than a failure.
246 - **Sticky comment**: [`peter-evans/find-comment`](https://github.com/peter-evans/find-comment)
247 looks up an existing comment by the hidden HTML marker
248 `<!-- commitizen-bump-preview -->` and bot author, then
249 [`peter-evans/create-or-update-comment`](https://github.com/peter-evans/create-or-update-comment)
250 edits it in place (or creates a new one on the first run when the
251 marker is not yet present), instead of leaving a growing trail of
252 comments.
253
254 [jinja]: https://github.com/commitizen-tools/commitizen/blob/master/commitizen/changelog.py
255
256 You can find the complete workflow in our repository at [pr-bump-preview.yml](https://github.com/commitizen-tools/commitizen/blob/master/.github/workflows/pr-bump-preview.yml).
257
258 ### Publishing a Python package
259
260 After a new version tag is created by the bump workflow, you can automatically publish your package to PyPI.
261
262 #### Step 1: Create a PyPI API token
263
264 1. Go to [PyPI Account Settings](https://pypi.org/manage/account/)
265 2. Scroll to the "API tokens" section
266 3. Click "Add API token"
267 4. Give it a name (e.g., "GitHub Actions")
268 5. Set the scope (project-specific or account-wide)
269 6. Click "Add token" and **copy the token immediately**
270
271 !!! tip "Using trusted publishing (recommended)"
272 Instead of API tokens, consider using [PyPI trusted publishing](https://docs.pypi.org/trusted-publishers/) with OpenID Connect (OIDC). This is more secure as it doesn't require storing secrets. The `pypa/gh-action-pypi-publish` action supports trusted publishing when you configure it in your PyPI project settings.
273
274 #### Step 2: Add the token as a repository secret
275
276 1. Go to your repository on GitHub
277 2. Navigate to `Settings > Secrets and variables > Actions`
278 3. Click "New repository secret"
279 4. Name it `PYPI_PASSWORD`
280 5. Paste the PyPI token
281 6. Click "Add secret"
282
283 #### Step 3: Create the publish workflow
284
285 Create a new file `.github/workflows/pythonpublish.yml` that triggers on tag pushes:
286
287 ```yaml title=".github/workflows/pythonpublish.yml"
288 name: Upload Python Package
289
290 on:
291 push:
292 tags:
293 - "*" # Will trigger for every tag, alternative: 'v*'
294
295 jobs:
296 deploy:
297 runs-on: ubuntu-latest
298 steps:
299 - uses: actions/checkout@v6
300 with:
301 fetch-depth: 0
302 - name: Set up Python
303 uses: actions/setup-python@v4
304 with:
305 python-version: "3.x"
306 - name: Install Poetry
307 uses: snok/install-poetry@v1
308 with:
309 version: latest
310 virtualenvs-in-project: true
311 virtualenvs-create: true
312 - name: Install dependencies
313 run: |
314 poetry --version
315 poetry install
316 - name: Build and publish
317 env:
318 POETRY_HTTP_BASIC_PYPI_USERNAME: __token__
319 POETRY_HTTP_BASIC_PYPI_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
320 run: poetry publish --build
321 ```
322
323 This workflow uses Poetry to build and publish the package. You can find the complete workflow in our repository at [pythonpublish.yml](https://github.com/commitizen-tools/commitizen/blob/master/.github/workflows/pythonpublish.yml).
324
325 !!! note "Alternative publishing methods"
326 You can also use [pypa/gh-action-pypi-publish](https://github.com/pypa/gh-action-pypi-publish) or other build tools like `setuptools`, `flit`, or `hatchling` to publish your package.