name: Publish

on:
  push:
    tags:
      - "v*"
  workflow_dispatch:
    inputs:
      publish:
        description: "Set to true to actually publish to crates.io"
        type: boolean
        required: true
        default: false

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always

jobs:
  verify-release:
    name: Verify release artifact
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Cargo publish dry-run
        run: cargo publish --dry-run --locked

  publish:
    name: Publish to crates.io
    needs: verify-release
    if: ${{ github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.publish) }}
    runs-on: ubuntu-latest
    environment: crates-io
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Publish
        run: cargo publish --locked
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
