name: Benchmark Reports

on:
  pull_request:
    branches: "main"
    types:
      - opened
      - reopened
      - synchronize
      - ready_for_review
  merge_group:
  workflow_dispatch:

env:
  CARGO_TERM_COLOR: always
  NODE_VERSION: "18.17.1"
  PYTHON_VERSION: "3.11"
  RUST_TOOLCHAIN_VERSION: "1.80"
  RUST_TOOLCHAIN_COMPONENTS: rustfmt clippy

jobs:
  runMemoryProfile:
    if: ${{ !github.event.pull_request.draft }}
    name: run memory profile
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@v2
        with:
          ref: main
      - uses: Swatinem/rust-cache@v2
      - run: |
          MAIN_MEASUREMENT=$(cargo run --bin memtest)
          echo "MAIN_MEASUREMENT<<EOF" >> $GITHUB_ENV
          echo "$MAIN_MEASUREMENT" >> $GITHUB_ENV
          echo "EOF" >> $GITHUB_ENV
      - run: |
          echo "${{env.MAIN_MEASUREMENT}}"
          echo $MAIN_MEASUREMENT

      - uses: actions/checkout@v2
      - run: |
          BRANCH_MEASUREMENT=$(cargo run --bin memtest)
          echo "BRANCH_MEASUREMENT<<EOF" >> $GITHUB_ENV
          echo "$BRANCH_MEASUREMENT" >> $GITHUB_ENV
          echo "EOF" >> $GITHUB_ENV
      - run: |
          echo "${{env.BRANCH_MEASUREMENT}}"
          echo $BRANCH_MEASUREMENT
      - uses: actions/github-script@v6
        with:
          script: |
            if (${{ env.BRANCH_MEASUREMENT }} !== ${{ env.MAIN_MEASUREMENT }}) {
              const difference = ${{ env.BRANCH_MEASUREMENT }} - ${{ env.MAIN_MEASUREMENT }};
              try {
                await github.rest.issues.createComment({
                  issue_number: context.issue.number,
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  body: `_Change in memory usage detected by benchmark._
            ## Memory Report for ${{ github.sha }}

            | Test                        | This Branch | On Main  | Difference |
            |-----------------------------|-------------|----------| ---------- |
            | compile core + standard lib | ${{ env.BRANCH_MEASUREMENT }} bytes | ${{ env.MAIN_MEASUREMENT }} bytes | ${difference} bytes`
                })
              } catch (err) {
                core.warning(`Failed writing comment on GitHub issue: ${err}`)
              }
            } else {
              console.log("no change in memory usage detected by benchmark");
            }
        if: ${{ github.base_ref != null }}
