name: Publish to crates.io

on:
  release:
    types: [published]

permissions:
  id-token: write
  contents: read

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.release.tag_name }}

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Update Cargo.toml version
        run: |
          # タグ名(v1.2.3など)から'v'を取り除いてバージョンを取得
          VERSION="${{ github.event.release.tag_name }}"
          VERSION="${VERSION#v}"
          # Cargo.tomlの最初のversion行を置換
          sed -i "0,/^version = \".*\"/{s/^version = \".*\"/version = \"$VERSION\"/}" Cargo.toml

      - name: Authenticate with crates.io
        id: auth
        uses: rust-lang/crates-io-auth-action@v1

      - name: Publish to crates.io
        run: cargo publish --allow-dirty
        env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
