Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

Add automated release workflow with version bumping (#170)

Punit Arani5543c870f4fd
diff --git a/.github/workflows/actionlint.yml b/.github/workflows/actionlint.yml
new file mode 100644
index 0000000..993b8ba
--- /dev/null
+++ b/.github/workflows/actionlint.yml
@@ -0,0 +1,30 @@
+name: Actionlint
+
+on:
+ push:
+ branches: [ main ]
+ paths:
+ - '.github/workflows/**'
+ - '.github/actionlint.yaml'
+ pull_request:
+ branches: [ main ]
+ paths:
+ - '.github/workflows/**'
+ - '.github/actionlint.yaml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ actionlint:
+ name: Lint workflow files
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Run actionlint
+ uses: raven-actions/actionlint@v2
+ with:
+ # Show inline annotations on the PR diff for any findings
+ matcher: true
diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 4667fce..860de08 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -33,7 +33,7 @@ jobs:
- name: Set up Python
run: uv python install 3.12
- - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV
+ - run: echo "cache_id=$(date --utc '+%V')" >> "$GITHUB_ENV"
- uses: actions/cache@v5
with:
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 207a2d0..e04a6fc 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -13,6 +13,13 @@ on:
options:
- testpypi
- pypi
+ workflow_call:
+ inputs:
+ environment:
+ description: 'Environment to publish to (pypi or testpypi)'
+ required: false
+ default: 'pypi'
+ type: string
permissions:
contents: read
@@ -65,7 +72,7 @@ jobs:
runs-on: ubuntu-latest
needs:
- release-build
- if: github.event_name == 'release' || (github.event_name == 'workflow_dispatch' && github.event.inputs.environment == 'pypi')
+ if: ${{ github.event_name == 'release' || inputs.environment == 'pypi' }}
permissions:
id-token: write
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
new file mode 100644
index 0000000..13758b8
--- /dev/null
+++ b/.github/workflows/release.yml
@@ -0,0 +1,244 @@
+name: Release
+
+on:
+ workflow_dispatch:
+ inputs:
+ bump:
+ description: 'Version bump type'
+ required: true
+ default: 'patch'
+ type: choice
+ options:
+ - patch
+ - minor
+ - major
+ - explicit
+ version:
+ description: 'Explicit version when bump=explicit (e.g. 0.9.0)'
+ required: false
+ type: string
+ dry_run:
+ description: 'Dry run: compute version + notes without committing/tagging/releasing'
+ required: false
+ default: false
+ type: boolean
+
+permissions:
+ contents: write
+
+concurrency:
+ group: release
+ cancel-in-progress: false
+
+jobs:
+ release:
+ outputs:
+ tag: ${{ steps.version.outputs.tag }}
+ new: ${{ steps.version.outputs.new }}
+ did_release: ${{ steps.mark.outputs.did_release }}
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout main
+ uses: actions/checkout@v6
+ with:
+ ref: main
+ fetch-depth: 0
+ token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Configure git
+ run: |
+ git config user.name "github-actions[bot]"
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
+
+ - name: Set up Python
+ uses: actions/setup-python@v6
+ with:
+ python-version: "3.12"
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@v7
+ with:
+ version: "latest"
+
+ - name: Compute next version
+ id: version
+ env:
+ BUMP: ${{ inputs.bump }}
+ EXPLICIT_VERSION: ${{ inputs.version }}
+ run: |
+ if [ "$BUMP" = "explicit" ]; then
+ if [ -z "$EXPLICIT_VERSION" ]; then
+ echo "::error::bump=explicit requires a 'version' input"
+ exit 1
+ fi
+ python scripts/bump_version.py --explicit "$EXPLICIT_VERSION" --github-output
+ else
+ python scripts/bump_version.py --bump "$BUMP" --github-output
+ fi
+
+ - name: Verify tag doesn't already exist
+ run: |
+ tag="${{ steps.version.outputs.tag }}"
+ if git rev-parse "refs/tags/${tag}" >/dev/null 2>&1; then
+ echo "::error::Tag ${tag} already exists"
+ exit 1
+ fi
+ if git ls-remote --tags --exit-code origin "refs/tags/${tag}" >/dev/null 2>&1; then
+ echo "::error::Tag ${tag} already exists on origin"
+ exit 1
+ fi
+
+ - name: Determine commit range for release notes
+ id: range
+ run: |
+ prev_tag=$(git tag --list 'v*' --sort=-v:refname | head -n1)
+ if [ -n "$prev_tag" ]; then
+ range="${prev_tag}..HEAD"
+ echo "prev_tag=${prev_tag}" >> "$GITHUB_OUTPUT"
+ else
+ # First release with this workflow: walk back to the last manual "Bump version" commit
+ prev=$(git log --grep='^Bump version' -n1 --format='%H' || true)
+ if [ -n "$prev" ]; then
+ range="${prev}..HEAD"
+ echo "prev_commit=${prev}" >> "$GITHUB_OUTPUT"
+ else
+ range="HEAD"
+ fi
+ fi
+ echo "range=${range}" >> "$GITHUB_OUTPUT"
+ echo "Using range: ${range}"
+
+ - name: Generate release notes
+ env:
+ RANGE: ${{ steps.range.outputs.range }}
+ NEW_VERSION: ${{ steps.version.outputs.new }}
+ PREV_TAG: ${{ steps.range.outputs.prev_tag }}
+ run: |
+ {
+ echo "## What's Changed"
+ echo
+ if [ "$RANGE" = "HEAD" ]; then
+ git log --pretty=format:'- %s (%h)' HEAD
+ else
+ git log --pretty=format:'- %s (%h)' "$RANGE"
+ fi
+ echo
+ echo
+ if [ -n "$PREV_TAG" ]; then
+ echo "**Full Changelog**: https://github.com/${GITHUB_REPOSITORY}/compare/${PREV_TAG}...v${NEW_VERSION}"
+ fi
+ } > release_notes.md
+ echo "----- release_notes.md -----"
+ cat release_notes.md
+ echo "----------------------------"
+
+ - name: Update pyproject.toml version
+ if: ${{ !inputs.dry_run }}
+ env:
+ BUMP: ${{ inputs.bump }}
+ EXPLICIT_VERSION: ${{ inputs.version }}
+ run: |
+ if [ "$BUMP" = "explicit" ]; then
+ python scripts/bump_version.py --explicit "$EXPLICIT_VERSION" --write
+ else
+ python scripts/bump_version.py --bump "$BUMP" --write
+ fi
+
+ - name: Refresh uv.lock
+ if: ${{ !inputs.dry_run }}
+ run: uv lock
+
+ - name: Commit and tag
+ if: ${{ !inputs.dry_run }}
+ env:
+ TAG: ${{ steps.version.outputs.tag }}
+ run: |
+ git add pyproject.toml uv.lock
+ if git diff --cached --quiet; then
+ echo "::error::No version changes staged; aborting."
+ exit 1
+ fi
+ git commit -m "chore(release): ${TAG}"
+ git tag -a "${TAG}" -m "Release ${TAG}"
+
+ - name: Push commit to main
+ if: ${{ !inputs.dry_run }}
+ run: |
+ for attempt in 1 2 3 4; do
+ if git push origin "HEAD:main"; then
+ exit 0
+ fi
+ if [ "$attempt" -eq 4 ]; then
+ echo "::error::git push of release commit failed after 4 attempts; nothing was pushed"
+ exit 1
+ fi
+ sleep $((2 ** attempt))
+ done
+
+ - name: Push tag
+ if: ${{ !inputs.dry_run }}
+ env:
+ TAG: ${{ steps.version.outputs.tag }}
+ run: |
+ for attempt in 1 2 3 4; do
+ if git push origin "${TAG}"; then
+ exit 0
+ fi
+ if [ "$attempt" -eq 4 ]; then
+ echo "::error::Tag push failed after 4 attempts."
+ echo "::error::The release commit was already pushed to main; recover by running:"
+ echo "::error:: git fetch origin && git push origin ${TAG}"
+ echo "::error::then create the GitHub Release for ${TAG} manually (publish.yml will fire)."
+ exit 1
+ fi
+ sleep $((2 ** attempt))
+ done
+
+ - name: Create GitHub Release
+ if: ${{ !inputs.dry_run }}
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ TAG: ${{ steps.version.outputs.tag }}
+ run: |
+ gh release create "${TAG}" \
+ --title "${TAG}" \
+ --notes-file release_notes.md \
+ --target main
+
+ - name: Mark release created
+ id: mark
+ if: ${{ !inputs.dry_run }}
+ run: echo "did_release=true" >> "$GITHUB_OUTPUT"
+
+ - name: Dry run summary
+ if: ${{ inputs.dry_run }}
+ env:
+ CURRENT: ${{ steps.version.outputs.current }}
+ NEW_VERSION: ${{ steps.version.outputs.new }}
+ TAG: ${{ steps.version.outputs.tag }}
+ run: |
+ {
+ echo "### Dry run"
+ echo
+ echo "- Current version: \`${CURRENT}\`"
+ echo "- Next version: \`${NEW_VERSION}\`"
+ echo "- Tag to create: \`${TAG}\`"
+ echo
+ echo "### Release notes preview"
+ echo
+ cat release_notes.md
+ } >> "$GITHUB_STEP_SUMMARY"
+
+ publish:
+ needs: release
+ if: ${{ needs.release.outputs.did_release == 'true' }}
+ uses: ./.github/workflows/publish.yml
+ with:
+ environment: pypi
+ permissions:
+ contents: read
+ checks: write
+ pull-requests: write
+ id-token: write
+ secrets: inherit
+
diff --git a/AGENTS.md b/AGENTS.md
index 625bb8b..0b702cb 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -23,6 +23,13 @@ All standard commands are in the `Makefile` and `CLAUDE.md`. Key ones:
- Run `uv run pytest -vv --ignore=tests/search/` to skip flaky API-dependent tests.
- One MCP test (`test_search_dates_round_trip`) also makes a live API call and may fail with empty results.
+### Releasing
+
+Releases are manual: GitHub Actions → **Release** → Run workflow on `main`,
+choose `bump=patch|minor|major|explicit`. Run with `dry_run=true` first to
+preview. Bump logic is in `scripts/bump_version.py` (testable). Full guide:
+`docs/guides/release.md`.
+
### MCP server notes
- The MCP HTTP endpoint requires `Accept: application/json, text/event-stream` header.
diff --git a/CLAUDE.md b/CLAUDE.md
index 75f92fd..c4b6078 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -139,6 +139,17 @@ Both tools accept the `emissions` filter (forwarded to Google's
**not** returned in CLI output or MCP tool responses. The filter operates
server-side; the data is not displayed in the current release.
+## Releasing
+
+Releases are cut manually via `.github/workflows/release.yml`
+(Actions → Release → Run workflow on `main`). Choose
+`bump=patch|minor|major|explicit`; the workflow bumps `pyproject.toml`,
+refreshes `uv.lock`, commits + tags + creates a GitHub Release, then calls
+`publish.yml` to upload to PyPI via Trusted Publishing. Always run with
+`dry_run=true` first to preview the version and release notes. The
+version-bump logic lives in `scripts/bump_version.py` (testable; covered
+by `tests/scripts/test_bump_version.py`). Full process: `docs/guides/release.md`.
+
## Code Style and Standards
- **Linting**: Uses Ruff with pycodestyle, pyflakes, isort, flake8-bugbear, and pydocstyle
diff --git a/Makefile b/Makefile
index 05c99da..b5e1174 100644
--- a/Makefile
+++ b/Makefile
@@ -66,6 +66,30 @@ devcontainer:
# Generate the requirements.txt file
requirements:
uv export --format requirements-txt --no-hashes > requirements.txt
+
+# Preview next versions for each bump kind (does not modify files)
+bump-preview:
+ @python scripts/bump_version.py --bump patch
+ @echo "---"
+ @python scripts/bump_version.py --bump minor
+ @echo "---"
+ @python scripts/bump_version.py --bump major
+
+# Preview release notes since the last tag (or last "Bump version" commit)
+release-notes:
+ @prev=$$(git tag --list 'v*' --sort=-v:refname | head -n1); \
+ if [ -z "$$prev" ]; then \
+ prev=$$(git log --grep='^Bump version' -n1 --format='%H'); \
+ fi; \
+ if [ -z "$$prev" ]; then \
+ echo "(no previous tag found, showing full history)"; \
+ git log --pretty=format:'- %s (%h)' HEAD; \
+ else \
+ echo "Commits since $$prev:"; \
+ git log --pretty=format:'- %s (%h)' "$$prev..HEAD"; \
+ fi
+ @echo
+
# Display help message by default
.DEFAULT_GOAL := help
help:
@@ -86,5 +110,7 @@ help:
@echo " make ci-docker - Run CI in Docker container"
@echo " make devcontainer - Build dev container image"
@echo " make requirements - Generate the requirements.txt file"
+ @echo " make bump-preview - Preview next version (patch/minor/major)"
+ @echo " make release-notes - Preview release notes since last tag"
# Declare the targets as phony
-.PHONY: help install install-dev install-all mcp mcp-http docs format lint lint-fix test test-mcp test-fuzz test-all ci ci-docker devcontainer requirements
+.PHONY: help install install-dev install-all mcp mcp-http docs format lint lint-fix test test-mcp test-fuzz test-all ci ci-docker devcontainer requirements bump-preview release-notes
diff --git a/docs/guides/release.md b/docs/guides/release.md
new file mode 100644
index 0000000..1f0dc8e
--- /dev/null
+++ b/docs/guides/release.md
@@ -0,0 +1,100 @@
+# Releasing
+
+Releases are driven by a manual GitHub Actions workflow. There is no auto-publish
+on push to `main`; cutting a release is always an explicit, one-click action.
+
+## Overview
+
+The release pipeline is two workflows:
+
+| Workflow | File | Trigger |
+| --- | --- | --- |
+| **Release** | `.github/workflows/release.yml` | `workflow_dispatch` only |
+| **Upload Python Package** | `.github/workflows/publish.yml` | `release: published`, `workflow_dispatch`, `workflow_call` |
+
+`release.yml` bumps the version in `pyproject.toml`, refreshes `uv.lock`,
+commits to `main`, creates an annotated tag and GitHub Release, then calls
+`publish.yml` to build and upload to PyPI via Trusted Publishing.
+
+`publish.yml` can also be triggered independently — by publishing a GitHub
+Release manually, or via `workflow_dispatch` (defaults to TestPyPI for
+safe smoke tests).
+
+## Cutting a release
+
+1. Go to **Actions → Release → Run workflow** on `main`.
+2. Choose the bump:
+ * `patch` (default) — bugfixes, small changes
+ * `minor` — new features, additive changes
+ * `major` — breaking changes
+ * `explicit` — set an exact version (also fill in the `version` input)
+3. Optional: set `dry_run: true` to preview the next version and release
+ notes without committing or publishing. The preview appears in the run
+ summary.
+4. Run again with `dry_run: false` to actually release.
+
+The workflow will:
+
+1. Compute the next version from `pyproject.toml`.
+2. Verify the tag doesn't already exist (locally and on the remote).
+3. Generate release notes from the commits in the range
+ `<previous tag>..HEAD`. On the very first release with no prior tag, it
+ walks back to the last manual `Bump version` commit.
+4. Update `pyproject.toml` and `uv.lock`.
+5. Commit `chore(release): vX.Y.Z` to `main`, tag `vX.Y.Z`, push both.
+6. Create a GitHub Release with the generated notes.
+7. Trigger `publish.yml` (run tests, build with `uv build`, `twine check`,
+ upload to PyPI via OIDC Trusted Publishing).
+
+## Previewing locally
+
+Use the same script the workflow uses:
+
+```bash
+# What would a minor bump produce?
+python scripts/bump_version.py --bump minor
+
+# Show the commits that would land in the next release
+git log --pretty=format:'- %s (%h)' "$(git describe --tags --abbrev=0)..HEAD"
+```
+
+`bump_version.py` only prints by default — pass `--write` to actually
+modify `pyproject.toml`.
+
+## Repository prerequisites
+
+These need to be in place once on the GitHub side:
+
+* **PyPI Trusted Publisher** for the `flights` project, bound to this repo
+ and the `pypi` environment. `publish.yml` requests an OIDC token via
+ `id-token: write` and uses `pypa/gh-action-pypi-publish`.
+* **Branch protection on `main`** must permit pushes from `github-actions[bot]`.
+ If protection blocks the bot, the release workflow's push will fail; switch
+ the checkout step's `token:` to a PAT secret instead.
+* **Workflow permissions**: `release.yml` requires `contents: write` (already
+ declared at the workflow level).
+
+## Troubleshooting
+
+* **`Tag vX.Y.Z already exists`** — someone tagged the same version earlier
+ (locally or on origin). Bump again or use `bump=explicit` with a different
+ version.
+* **Push to `main` rejected** — branch protection is blocking the bot. Either
+ add `github-actions[bot]` to the bypass list, or wire a PAT into the
+ checkout step's `token:`.
+* **PyPI publish step fails with OIDC error** — the Trusted Publisher
+ config on PyPI doesn't match this repo/workflow/environment. Re-check the
+ project's *Publishing* settings on PyPI.
+* **Release notes look wrong on first run** — the workflow walks back to the
+ last commit whose subject starts with `Bump version`. If you've changed
+ that convention, edit `release.yml`'s "Determine commit range" step.
+
+## Manual fallback
+
+If the workflow is broken and a release is urgent, you can still:
+
+1. Bump the version in `pyproject.toml` and `uv.lock` on a branch, merge to
+ `main`.
+2. Tag `vX.Y.Z` and push the tag.
+3. Create a GitHub Release in the UI from that tag — `publish.yml`'s
+ `release: published` trigger will pick it up and publish.
diff --git a/mkdocs.yml b/mkdocs.yml
index 265979a..e0e2104 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -104,4 +104,6 @@ nav:
- MCP Server: guides/mcp.md
- API Reference:
- Models: api/models.md
- - Search: api/search.md
\ No newline at end of file
+ - Search: api/search.md
+ - Contributing:
+ - Releasing: guides/release.md
\ No newline at end of file
diff --git a/scripts/bump_version.py b/scripts/bump_version.py
new file mode 100644
index 0000000..5aa4ba3
--- /dev/null
+++ b/scripts/bump_version.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python3
+"""Bump the version in pyproject.toml.
+
+Reads the current `[project].version` from ``pyproject.toml`` and writes a
+new value chosen by one of:
+
+* ``--bump {patch,minor,major}`` — increment the corresponding semver field
+* ``--explicit X.Y.Z`` — set an exact version
+
+Outputs (always to stdout, one per line, ``KEY=VALUE`` format):
+
+* ``current=<old version>``
+* ``new=<new version>``
+* ``tag=v<new version>``
+
+When ``--write`` is passed, ``pyproject.toml`` is updated in place. When
+``--github-output`` is passed, the same ``KEY=VALUE`` lines are appended
+to the file at ``$GITHUB_OUTPUT`` for use in GitHub Actions.
+
+The script is intentionally dependency-free (stdlib only) so it can run in
+minimal CI images without ``uv sync``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import sys
+from pathlib import Path
+
+try:
+ import tomllib # type: ignore[import-not-found]
+except ModuleNotFoundError: # Python < 3.11
+ import tomli as tomllib # type: ignore[import-not-found, no-redef]
+
+SEMVER_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)$")
+VERSION_LINE_RE = re.compile(r'(?m)^version\s*=\s*"[^"]+"')
+PROJECT_TABLE_RE = re.compile(r"(?m)^\[project\]\s*$")
+TABLE_HEADER_RE = re.compile(r"(?m)^\[[^\]]+\]\s*$")
+
+
+def read_current_version(pyproject: Path) -> str:
+ """Return the ``[project].version`` value from ``pyproject``."""
+ data = tomllib.loads(pyproject.read_text())
+ return data["project"]["version"]
+
+
+def compute_next_version(current: str, bump: str | None, explicit: str | None) -> str:
+ """Compute the next semver string given a current value and a bump kind.
+
+ When ``explicit`` is set it takes precedence; otherwise ``bump`` must be
+ one of ``patch``, ``minor``, or ``major``. Raises ``ValueError`` on any
+ malformed input.
+ """
+ if explicit is not None:
+ if not SEMVER_RE.match(explicit):
+ raise ValueError(f"Invalid explicit version: {explicit!r}")
+ return explicit
+
+ m = SEMVER_RE.match(current)
+ if not m:
+ raise ValueError(f"Cannot parse current version: {current!r}")
+ major, minor, patch = (int(x) for x in m.groups())
+
+ if bump == "patch":
+ patch += 1
+ elif bump == "minor":
+ minor += 1
+ patch = 0
+ elif bump == "major":
+ major += 1
+ minor = 0
+ patch = 0
+ else:
+ raise ValueError(f"Unknown bump type: {bump!r}")
+
+ return f"{major}.{minor}.{patch}"
+
+
+def write_new_version(pyproject: Path, new_version: str) -> None:
+ """Replace the ``[project].version`` line in ``pyproject`` with ``new_version``.
+
+ The substitution is scoped to the ``[project]`` table so a ``version`` key
+ in an earlier table (e.g. ``[tool.something]``) is never touched.
+ """
+ text = pyproject.read_text()
+ proj = PROJECT_TABLE_RE.search(text)
+ if not proj:
+ raise RuntimeError("No [project] table found in pyproject.toml")
+ section_start = proj.end()
+ next_header = TABLE_HEADER_RE.search(text, pos=section_start)
+ section_end = next_header.start() if next_header else len(text)
+ section = text[section_start:section_end]
+ updated_section, n = VERSION_LINE_RE.subn(f'version = "{new_version}"', section, count=1)
+ if n != 1:
+ raise RuntimeError("Failed to locate a version line within the [project] table")
+ pyproject.write_text(text[:section_start] + updated_section + text[section_end:])
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Run the CLI; returns a process exit code."""
+ parser = argparse.ArgumentParser(description="Bump the version in pyproject.toml")
+ parser.add_argument(
+ "--pyproject",
+ type=Path,
+ default=Path("pyproject.toml"),
+ help="Path to pyproject.toml (default: ./pyproject.toml)",
+ )
+ group = parser.add_mutually_exclusive_group(required=True)
+ group.add_argument(
+ "--bump",
+ choices=["patch", "minor", "major"],
+ help="Semver field to increment",
+ )
+ group.add_argument(
+ "--explicit",
+ metavar="X.Y.Z",
+ help="Set an exact version",
+ )
+ parser.add_argument(
+ "--write",
+ action="store_true",
+ help="Write the new version to pyproject.toml (default: print only)",
+ )
+ parser.add_argument(
+ "--github-output",
+ action="store_true",
+ help="Also append KEY=VALUE lines to $GITHUB_OUTPUT",
+ )
+ args = parser.parse_args(argv)
+
+ current = read_current_version(args.pyproject)
+ new = compute_next_version(current, args.bump, args.explicit)
+ tag = f"v{new}"
+
+ lines = [f"current={current}", f"new={new}", f"tag={tag}"]
+ for line in lines:
+ print(line)
+
+ if args.write:
+ write_new_version(args.pyproject, new)
+
+ if args.github_output:
+ gh_out = os.environ.get("GITHUB_OUTPUT")
+ if not gh_out:
+ print(
+ "::error::--github-output requested but $GITHUB_OUTPUT is not set",
+ file=sys.stderr,
+ )
+ return 1
+ with open(gh_out, "a") as fh:
+ for line in lines:
+ fh.write(line + "\n")
+
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/scripts/__init__.py b/tests/scripts/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/scripts/test_bump_version.py b/tests/scripts/test_bump_version.py
new file mode 100644
index 0000000..a3b580f
--- /dev/null
+++ b/tests/scripts/test_bump_version.py
@@ -0,0 +1,212 @@
+"""Tests for ``scripts/bump_version.py``."""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+SCRIPT_PATH = REPO_ROOT / "scripts" / "bump_version.py"
+
+
+def _load_module():
+ spec = importlib.util.spec_from_file_location("bump_version", SCRIPT_PATH)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+bump_version = _load_module()
+
+
+PYPROJECT_TEMPLATE = """\
+[project]
+name = "flights"
+version = "{version}"
+description = "test"
+"""
+
+
+def pyproject(tmp_path: Path) -> Path:
+ p = tmp_path / "pyproject.toml"
+ p.write_text(PYPROJECT_TEMPLATE.format(version="0.8.5"))
+ return p
+
+
+class TestComputeNextVersion:
+ @pytest.mark.parametrize(
+ "current, bump, expected",
+ [
+ ("0.8.5", "patch", "0.8.6"),
+ ("0.8.5", "minor", "0.9.0"),
+ ("0.8.5", "major", "1.0.0"),
+ ("1.2.3", "patch", "1.2.4"),
+ ("1.2.3", "minor", "1.3.0"),
+ ("1.2.3", "major", "2.0.0"),
+ ("0.0.0", "patch", "0.0.1"),
+ ("9.9.9", "minor", "9.10.0"),
+ ],
+ )
+ def test_bumps(self, current, bump, expected) -> None:
+ assert bump_version.compute_next_version(current, bump, None) == expected
+
+ def test_explicit_overrides_bump(self) -> None:
+ assert bump_version.compute_next_version("0.8.5", None, "1.2.3") == "1.2.3"
+
+ @pytest.mark.parametrize("bad", ["0.9", "abc", "1.2.3.4", "v1.2.3", "1.2.3-rc1", ""])
+ def test_invalid_explicit(self, bad) -> None:
+ with pytest.raises(ValueError):
+ bump_version.compute_next_version("0.8.5", None, bad)
+
+ @pytest.mark.parametrize("current", ["0.9", "abc", "v1.2.3"])
+ def test_invalid_current(self, current) -> None:
+ with pytest.raises(ValueError):
+ bump_version.compute_next_version(current, "patch", None)
+
+ def test_unknown_bump_type(self) -> None:
+ with pytest.raises(ValueError):
+ bump_version.compute_next_version("0.8.5", "weird", None)
+
+
+class TestReadWrite:
+ def test_read_current_version(self, pyproject: Path) -> None:
+ assert bump_version.read_current_version(pyproject) == "0.8.5"
+
+ def test_write_new_version_replaces_only_project_version(self, tmp_path: Path) -> None:
+ # Ensure other "version" lines (e.g. inside dep tables) are left alone.
+ content = '[project]\nversion = "0.8.5"\n[tool.something]\nversion = "9.9.9"\n'
+ p = tmp_path / "pyproject.toml"
+ p.write_text(content)
+ bump_version.write_new_version(p, "0.9.0")
+ out = p.read_text()
+ assert 'version = "0.9.0"' in out
+ # The unrelated tool table version should remain
+ assert 'version = "9.9.9"' in out
+ # Only one project version line
+ assert out.count('version = "0.9.0"') == 1
+
+ def test_write_raises_when_no_version_line(self, tmp_path: Path) -> None:
+ p = tmp_path / "pyproject.toml"
+ p.write_text("[project]\nname = 'x'\n")
+ with pytest.raises(RuntimeError):
+ bump_version.write_new_version(p, "0.9.0")
+
+ def test_write_raises_when_no_project_table(self, tmp_path: Path) -> None:
+ p = tmp_path / "pyproject.toml"
+ p.write_text('[tool.foo]\nversion = "1.0.0"\n')
+ with pytest.raises(RuntimeError):
+ bump_version.write_new_version(p, "0.9.0")
+
+ def test_write_ignores_version_in_earlier_table(self, tmp_path: Path) -> None:
+ # [tool.something] appears BEFORE [project]; its version must be left
+ # untouched even though it's the first 'version = "..."' line in the file.
+ content = (
+ "[tool.something]\n"
+ 'version = "9.9.9"\n'
+ "\n"
+ "[project]\n"
+ 'name = "flights"\n'
+ 'version = "0.8.5"\n'
+ )
+ p = tmp_path / "pyproject.toml"
+ p.write_text(content)
+ bump_version.write_new_version(p, "0.9.0")
+ out = p.read_text()
+ assert 'version = "9.9.9"' in out # tool version untouched
+ assert 'version = "0.9.0"' in out # project version bumped
+ assert 'version = "0.8.5"' not in out
+
+ def test_write_ignores_version_in_later_table(self, tmp_path: Path) -> None:
+ content = (
+ "[project]\n"
+ 'name = "flights"\n'
+ 'version = "0.8.5"\n'
+ "\n"
+ "[tool.something]\n"
+ 'version = "9.9.9"\n'
+ )
+ p = tmp_path / "pyproject.toml"
+ p.write_text(content)
+ bump_version.write_new_version(p, "0.9.0")
+ out = p.read_text()
+ assert 'version = "9.9.9"' in out
+ assert 'version = "0.9.0"' in out
+ assert 'version = "0.8.5"' not in out
+
+
+class TestCLI:
+ def _run(self, monkeypatch, args) -> int:
+ monkeypatch.setattr(sys, "argv", ["bump_version.py", *args])
+ return bump_version.main(args)
+
+ def test_print_only_does_not_modify_file(self, pyproject: Path, monkeypatch, capsys) -> None:
+ rc = self._run(monkeypatch, ["--pyproject", str(pyproject), "--bump", "minor"])
+ assert rc == 0
+ out = capsys.readouterr().out
+ assert "current=0.8.5" in out
+ assert "new=0.9.0" in out
+ assert "tag=v0.9.0" in out
+ # File untouched
+ assert bump_version.read_current_version(pyproject) == "0.8.5"
+
+ def test_write_updates_file(self, pyproject: Path, monkeypatch) -> None:
+ rc = self._run(
+ monkeypatch,
+ ["--pyproject", str(pyproject), "--bump", "patch", "--write"],
+ )
+ assert rc == 0
+ assert bump_version.read_current_version(pyproject) == "0.8.6"
+
+ def test_github_output_appends_kv_lines(
+ self, pyproject: Path, tmp_path: Path, monkeypatch
+ ) -> None:
+ gh_out = tmp_path / "gh_output"
+ gh_out.write_text("")
+ monkeypatch.setenv("GITHUB_OUTPUT", str(gh_out))
+ rc = self._run(
+ monkeypatch,
+ [
+ "--pyproject",
+ str(pyproject),
+ "--bump",
+ "major",
+ "--github-output",
+ ],
+ )
+ assert rc == 0
+ contents = gh_out.read_text().splitlines()
+ assert "current=0.8.5" in contents
+ assert "new=1.0.0" in contents
+ assert "tag=v1.0.0" in contents
+
+ def test_github_output_errors_when_env_missing(self, pyproject: Path, monkeypatch) -> None:
+ monkeypatch.delenv("GITHUB_OUTPUT", raising=False)
+ rc = self._run(
+ monkeypatch,
+ ["--pyproject", str(pyproject), "--bump", "patch", "--github-output"],
+ )
+ assert rc == 1
+
+ def test_bump_and_explicit_are_mutually_exclusive(self, pyproject: Path, monkeypatch) -> None:
+ # argparse exits with SystemExit(2) for arg errors
+ with pytest.raises(SystemExit):
+ self._run(
+ monkeypatch,
+ [
+ "--pyproject",
+ str(pyproject),
+ "--bump",
+ "patch",
+ "--explicit",
+ "1.0.0",
+ ],
+ )
+
+ def test_requires_one_of_bump_or_explicit(self, pyproject: Path, monkeypatch) -> None:
+ with pytest.raises(SystemExit):
+ self._run(monkeypatch, ["--pyproject", str(pyproject)])