name: VC gen

on:
  workflow_dispatch:
  pull_request:
    paths-ignore:
      - '**.vv'
      - '**.out'
      - '**.md'
      - '**.yml'
      - '!**/gen_vc_ci.yml'
      - 'cmd/tools/**'
      - '!cmd/tools/builders/**.v'
  push:
    paths-ignore:
      - '**.vv'
      - '**.out'
      - '**.md'
      - '**.yml'
      - '!**/gen_vc_ci.yml'
      - 'cmd/tools/**'
      - '!cmd/tools/builders/**.v'

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
  group: gen_vc-${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: ${{ !contains(github.ref, 'master')}}

jobs:
  build-vc:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Build V
        run: make -j4
      - name: Regenerate v.c and v_win.c
        run: |
          git config --global user.email "vlang-bot@users.noreply.github.com"
          git config --global user.name "vlang-bot"

          COMMIT_HASH="$(git rev-parse HEAD)"
          COMMIT_MSG="$(git log -1 --oneline --pretty='%s' HEAD)"

          rm -rf vc
          ./v retry -- git clone --depth=1 "https://vlang-bot:${{ secrets.VLANG_BOT_SECRET }}@github.com/vlang/vc.git"

          rm -rf vc/v.c vc/v_win.c
          ./v -o vc/v.c     -cross               cmd/v
          ./v -o vc/v_win.c -os windows -cc msvc cmd/v

          sed -i "1s/^/#define V_COMMIT_HASH \"$COMMIT_HASH\"\n/" vc/v.c
          sed -i "1s/^/#define V_COMMIT_HASH \"$COMMIT_HASH\"\n/" vc/v_win.c

          # do some sanity checks for the generated v.c file:
          grep 'Turned ON custom defines: no_backtrace,cross'  vc/v.c
          grep '#define CUSTOM_DEFINE_cross' vc/v.c

          # ensure the generated C files for the compiler, are over 5000 lines long, as a safety measure
          [ "$(wc -l < vc/v.c)" -gt 5000 ]
          [ "$(wc -l < vc/v_win.c)" -gt 5000 ]

          git -C vc add v.c v_win.c
          git -C vc commit -m "[v:master] $COMMIT_HASH - $COMMIT_MSG"

          # in case there are recent commits:
          ./v retry -- git -C vc pull --rebase origin master
          git -C vc log -3

      - name: Deploy
        if: github.event_name == 'push' && github.repository == 'vlang/v' && github.ref == 'refs/heads/master'
        run: git -C vc push || true
