Rust

Continuous Integration

Recommendations for CI

Adapted from the rust docs to add single CI runs on pull requests and pushes, and publish step

https://doc.rust-lang.org/cargo/guide/continuous-integration.html

.github/workflows/ci.yml
name: CI

on:
  push:
    branches: ["main"]
  pull_request:
    branches: ["main"]
  release:
    types: [published]

env:
  CARGO_TERM_COLOR: always

jobs:
  build_and_test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        toolchain:
          - stable
          - beta
          - nightly
    steps:
      - uses: actions/checkout@v4
      - run: rustup update ${{ matrix.toolchain }} && rustup default ${{ matrix.toolchain }}
      - run: cargo build --verbose
      - run: cargo test --verbose
      - name: Publish
        if: github.ref_type == 'tag' && matrix.item =='stable'
        run: cargo publish --verbose
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
The publish step will only run when BOTH a tagged release happens and only on the 'stable' matrix.toolchain item
If conditionals are very tricky in Github actions, as empty strings are true by default (oh my!).Best to just click this link, but the below is what I am referring to, which will only run when BOTH a tagged release happens and only on the 'stable' matrix.toolchain item
.github/workflows/ci.yml
...
jobs:
  build_and_test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        toolchain:
          - stable
          - beta
          - nightly
    steps:
      ...
      - name: Publish (Preferred Option 1 that works, without ${{ }})
        if: github.ref_type == 'tag' && matrix.item =='stable'
        run: cargo publish --verbose
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
      - name: Publish (Option 2 that works, with ${{ }})
        if: ${{ (github.ref_type == 'tag') && (matrix.item =='stable') }}
        run: cargo publish --verbose
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}