name: Release mermaid-text

# Triggered by `mermaid-text-*` tags. Library-only — publishes the
# `mermaid-text` crate to crates.io and creates a small GitHub Release
# pointing at the changelog. No cross-platform binaries (the CLI inside
# `mermaid-text` is intended for end-users via `cargo install`, not as
# a packaged binary; the parent `markdown-reader` ships separately on
# `v*` tags).

on:
  push:
    tags:
      - "mermaid-text-*"
  workflow_dispatch:
    inputs:
      publish_crate:
        description: "Publish to crates.io"
        type: boolean
        default: true

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always
  CARGO_INCREMENTAL: 0

jobs:
  release:
    name: Create GitHub Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Extract changelog section
        id: changelog
        run: |
          # Tag format: `mermaid-text-X.Y.Z` → version = `X.Y.Z`
          VERSION=${GITHUB_REF_NAME#mermaid-text-}
          CHANGELOG=crates/mermaid-text/CHANGELOG.md
          if [ -f "$CHANGELOG" ]; then
            # Match `## VERSION` or `## [VERSION]` — both styles appear
            # in the wild. Keep extracting until the next `## ` header.
            BODY=$(awk \
              -v v="$VERSION" \
              'BEGIN{re="^## (\\["v"\\]|"v"( |$))"} \
               $0 ~ re {found=1; next} \
               found && /^## / {exit} \
               found {print}' \
              "$CHANGELOG")
          else
            BODY="Release ${GITHUB_REF_NAME}"
          fi
          printf '%s' "$BODY" > release_notes.md

      - name: Publish GitHub Release
        uses: softprops/action-gh-release@v3
        with:
          name: ${{ github.ref_name }}
          body_path: release_notes.md
          token: ${{ secrets.GITHUB_TOKEN }}

  publish-crate:
    name: Publish mermaid-text to crates.io
    needs: [release]
    runs-on: ubuntu-latest
    if: >
      (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/mermaid-text-')) ||
      (github.event_name == 'workflow_dispatch' && inputs.publish_crate == true)
    steps:
      - uses: actions/checkout@v6

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Publish mermaid-text
        run: cargo publish --package mermaid-text --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
