name: Publish to crates.io

on:
  push:
    branches: [master]

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - name: Get local version
        id: local
        run: echo "version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml)" >> "$GITHUB_OUTPUT"

      - name: Get published version
        id: published
        run: echo "version=$(cargo search diself --limit 1 | sed -n 's/^diself = "\(.*\)".*/\1/p')" >> "$GITHUB_OUTPUT"

      - name: Publish to crates.io
        if: steps.local.outputs.version != steps.published.outputs.version
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
