name: release

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

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always
  # Pinned tag of the sibling am-fs-core repo used to satisfy the path dep
  # during local build/verify. Bump in lockstep with the am-fs-core version
  # constraint in Cargo.toml when releasing a new fs-ext4 minor.
  FS_CORE_REF: v0.2.2

jobs:
  test:
    name: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - name: clone am-fs-core sibling
        shell: bash
        run: git clone --depth 1 --branch "$FS_CORE_REF" https://github.com/antimatter-studios/rust-fs-core.git ../rust-fs-core

      - uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: 1.95.0
          components: clippy
      - uses: Swatinem/rust-cache@v2

      - name: verify tag matches Cargo.toml version
        run: |
          tag="${GITHUB_REF_NAME#v}"
          crate_ver=$(grep -m1 '^version' Cargo.toml | sed -E 's/version *= *"(.*)"/\1/')
          if [ "$tag" != "$crate_ver" ]; then
            echo "tag $tag does not match Cargo.toml version $crate_ver" >&2
            exit 1
          fi

      # capi_basic integration tests mount real ext4 images generated by
      # the qemu-hosted Alpine VM in test-disks/. Mirrors ci.yml's setup
      # so the release-time check exercises the same path as PR CI.
      - name: install qemu (for test-disk generator)
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y -qq qemu-system-x86 libarchive-tools
      - name: cache alpine VM assets
        uses: actions/cache@v4
        with:
          path: test-disks/.vm-cache
          key: vm-cache-alpine-3.21.4
      - name: generate test disks
        run: bash test-disks/build-ext4-feature-images.sh

      - run: cargo test --all-targets
      - run: cargo clippy --all-targets -- -D warnings

  publish:
    name: publish to crates.io
    needs: test
    runs-on: ubuntu-latest
    environment: release
    permissions:
      id-token: write
      contents: read
    steps:
      - uses: actions/checkout@v5

      - name: clone am-fs-core sibling
        shell: bash
        run: git clone --depth 1 --branch "$FS_CORE_REF" https://github.com/antimatter-studios/rust-fs-core.git ../rust-fs-core

      - uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: 1.95.0

      - uses: rust-lang/crates-io-auth-action@v1.0.4
        id: auth

      - name: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
        # No `--locked`: publish must rewrite the `am-fs-core` path
        # dependency into its registry equivalent in the packaged
        # lockfile, which `--locked` forbids ("cannot update the lock
        # file"). The verify-build resolves am-fs-core from crates.io
        # via the `version` constraint, so the published artifact is
        # pinned by that constraint, not by the local path checkout.
        run: cargo publish
