name: Release
on:
  workflow_dispatch:
  push:
    tags:
      - v[0-9]+.[0-9]+.[0-9]+

jobs:
  build:
    uses: ./.github/workflows/build.yml
    with:
      run_test: false

  release:
    name: Release
    runs-on: ubuntu-latest
    needs: build
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Display structure of downloaded files
        run: ls -lR
        working-directory: artifacts

      - name: Prepare release artifacts
        run: |
          mkdir -p target
          mv artifacts/tree-sitter.wasm/* target/
          rm -r artifacts/tree-sitter.wasm
          for platform in $(cd artifacts; ls | sed 's/^tree-sitter\.//'); do
            exe=$(ls artifacts/tree-sitter.$platform/tree-sitter*)
            gzip --stdout --name $exe > target/tree-sitter-$platform.gz
          done
          rm -rf artifacts
          ls -l target/

      - name: Create release
        uses: softprops/action-gh-release@v1
        with:
          name: ${{ github.ref_name }}
          tag_name: ${{ github.ref_name }}
          fail_on_unmatched_files: true
          files: |
            target/tree-sitter-*.gz
            target/tree-sitter.wasm
            target/tree-sitter.js

  crates_io:
    name: Publish CLI to Crates.io
    runs-on: ubuntu-latest
    needs: release
    steps:
      - uses: actions/checkout@v4

      - name: Setup Rust
        uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: stable
          override: true

      - name: Publish crates to Crates.io
        uses: katyo/publish-crates@v2
        with:
          registry-token: ${{ secrets.CARGO_REGISTRY_TOKEN }}

  npm:
    name: Publish lib to npmjs.com
    runs-on: ubuntu-latest
    needs: release
    strategy:
      fail-fast: false
      matrix:
        directory: ["cli/npm", "lib/binding_web"]
    steps:
      - uses: actions/checkout@v4

      - name: Build wasm
        if: matrix.directory == 'lib/binding_web'
        run: ./script/build-wasm

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 18
          registry-url: "https://registry.npmjs.org"

      - name: Publish lib to npmjs.com
        env:
          NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}}
        run: |
          cd ${{ matrix.directory }}
          npm publish
