name: CodeQL

on:
  push:
    branches: [ main, master ]
    paths:
      - "pg_integrity_checksums.c"
      - "pg_integrity_checksums.h"
      - "cli/**"
      - ".github/workflows/codeql.yml"
  pull_request:
    branches: [ main, master ]
    paths:
      - "pg_integrity_checksums.c"
      - "pg_integrity_checksums.h"
      - "cli/**"
      - ".github/workflows/codeql.yml"
  schedule:
    - cron: '23 4 * * 1'

permissions:
  actions: read
  contents: read
  security-events: write

jobs:
  analyze:
    name: Analyze C sources
    runs-on: ubuntu-latest
    timeout-minutes: 30

    steps:
      - name: Checkout repository
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

      - name: Install PostgreSQL build dependencies
        run: |
          sudo apt-get update
          # Do not use postgresql-server-dev-all here: on the GitHub runner it
          # is the Ubuntu metapackage, which pins postgresql-common to the
          # Ubuntu version and conflicts with the PGDG repository already
          # configured on the image.
          sudo apt-get install -y postgresql-server-dev-16 build-essential

      - name: Initialize CodeQL
        uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
        with:
          languages: c-cpp

      - name: Build extension for analysis
        run: |
          PG_CONFIG="$(find /usr/lib/postgresql -name pg_config | sort -V | tail -1)"
          echo "Using $PG_CONFIG"
          # PostgreSQL packages built with LLVM try to emit .bc files and may
          # require a clang version that is not installed on the runner.
          # Bitcode is not needed for CodeQL, so disable it.
          make PG_CONFIG="$PG_CONFIG" with_llvm=no clean all

      - name: Perform CodeQL analysis
        uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
        with:
          category: "/language:c-cpp"

  analyze-go:
    name: Analyze Go CLI
    runs-on: ubuntu-latest
    timeout-minutes: 20

    steps:
      - name: Checkout repository
        uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

      - name: Set up Go
        uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
        with:
          go-version-file: cli/go.mod
          cache-dependency-path: cli/go.sum

      - name: Initialize CodeQL
        uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
        with:
          languages: go

      - name: Build CLI for analysis
        run: |
          cd cli
          go build ./...

      - name: Perform CodeQL analysis
        uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4
        with:
          category: "/language:go"
