name: Build, test and analyze

on:
  pull_request:
    branches: [ master ]
  workflow_call:

jobs:

  # Run linter to ensure new code respect coding rules
  lint:
    name: Lint code
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - name: Setup NodeJS
        uses: actions/setup-node@v2
        with:
          node-version: 17
      - name: Setup metrics
        run: npm ci
      - name: Check contributions requirements
        run: npm run test-contrib
        env:
          PR_AUTHOR: ${{ github.event.pull_request.user.login }}
      - name: Run linter
        run: npm run linter

  # Build docker image from branch and run tests
  build:
    name: Build and test
    runs-on: ubuntu-latest
    needs: [ lint ]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2
      - name: Format code with dprint
        run: |
          curl -fsSL https://dprint.dev/install.sh | sh
          cp /home/runner/.dprint/bin/dprint /usr/local/bin/dprint
          npm install -g eslint
          dprint fmt --config .github/config/dprint.json
      - name: Build lowlighter/metrics:${{ github.head_ref || 'master' }}
        run: docker build -t lowlighter/metrics:$(echo ${{ github.head_ref || 'master' }} | sed 's/\//-/g') .
      - name: Run tests
        run: docker run --rm --entrypoint="" lowlighter/metrics:$(echo ${{ github.head_ref || 'master' }} | sed 's/\//-/g') npm run test-metrics

  # Run CodeQL on branch
  analyze:
    name: Analyze code
    runs-on: ubuntu-latest
    needs: [ lint ]
    steps:
      - name: Checkout repository
        uses: actions/checkout@v2
      - name: Setup CodeQL
        uses: github/codeql-action/init@v1
        with:
          languages: javascript
          config-file: ./.github/config/codeql.yml
      - name: Analyze code
        uses: github/codeql-action/analyze@v1