name: Publish Rust Crate

on:
  push:
    branches: [main]

env:
  CARGO_TERM_COLOR: always

jobs:
  publish-crate:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres
        ports:
          - 5432:5432
        env:
          POSTGRES_DB: postgres
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    steps:
      - uses: actions/checkout@v2

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

      - name: Run migrations
        run: |
          cargo install refinery_cli
          refinery migrate -e MESSAGE_DB_CONNECTION_URI files -p ./migrations
        env:
          MESSAGE_DB_CONNECTION_URI: "postgresql://postgres:postgres@localhost:5432/postgres"

      - name: Run tests
        run: cargo test
        env:
          RUST_LOG: "info"
          MESSAGE_DB_CONNECTION_URI: "postgresql://postgres:postgres@localhost:5432/postgres"

      - name: Publish crate
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
