name: Publish to crates.io

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  publish:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    
    steps:
    - uses: actions/checkout@v4

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

    - name: Cache cargo registry
      uses: actions/cache@v3
      with:
        path: |
          ~/.cargo/registry
          ~/.cargo/git
          target
        key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}

    - name: Run tests
      run: cargo test

    - name: Publish to crates.io
      run: |
        cargo publish --allow-dirty --registry crates-io
      env:
        CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}