name: CI

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
defaults:
  run:
    shell: bash

# Cancel any in-flight jobs for the same PR/branch so there's only one active
# at a time
concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  test:
    name: Test
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        mode: [debug, release]
    runs-on: ${{ matrix.os }}
    steps:
    - uses: actions/checkout@v2
    - name: Install Rust
      run: rustup update stable --no-self-update && rustup default stable
    - name: Install wasm32-unknown-unknown target
      run: rustup target add wasm32-unknown-unknown
    - name: Install wasm32-wasi target
      run: rustup target add wasm32-wasi

    - run: |
        curl https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-16/wasi-sdk-16.0-linux.tar.gz -L | tar xzvf -
        echo "WASI_SDK_PATH=`pwd`/wasi-sdk-16.0" >> $GITHUB_ENV
      if : matrix.os == 'ubuntu-latest'
    - run: |
        curl https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-16/wasi-sdk-16.0-macos.tar.gz -L | tar xzvf -
        echo "WASI_SDK_PATH=`pwd`/wasi-sdk-16.0" >> $GITHUB_ENV
      if : matrix.os == 'macos-latest'
    - run: |
        curl https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-16/wasi-sdk-16.0-mingw.tar.gz -L | tar xzvf -
        echo "WASI_SDK_PATH=`pwd`/wasi-sdk-16.0" >> $GITHUB_ENV
      if : matrix.os == 'windows-latest'

    - uses: actions/setup-node@v2
      with:
        node-version: '16'
    - name: Install NPM packages
      run: npm install
      working-directory: crates/gen-js
    - uses: actions/setup-python@v1
      with:
        python-version: 3.9
    - run: pip install mypy wasmtime
    - if: matrix.mode == 'release'
      name: Test release build
      run: cargo test --workspace --release
    - if: matrix.mode != 'release'
      name: Test debug build
      run: cargo test --workspace

  rustfmt:
    name: Rustfmt
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Install Rust
      run: rustup update stable && rustup default stable && rustup component add rustfmt
    - name: Format source code
      run: cargo fmt -- --check

  demo:
    name: Build wit-bindgen demo
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - run: rustup update stable --no-self-update && rustup default stable
    - run: rustup target add wasm32-unknown-unknown
    - run: npm install
      working-directory: crates/wit-bindgen-demo
    - run: ./crates/wit-bindgen-demo/build.sh
    - uses: JamesIves/github-pages-deploy-action@4.1.4
      with:
        branch: gh-pages
        folder: static
        single-commit: true
      if: github.event_name == 'push' && github.ref == 'refs/heads/main'
