name: Continuous integration

on:
  pull_request:
  push:
    branches:
      - master
    tags:
      - '*'

env:
  HAS_SECRETS: ${{ secrets.HAS_SECRETS }}
  PYTHON_KEYRING_BACKEND: keyring.backends.null.Keyring

jobs:
  main:
    name: Continuous integration
    runs-on: ubuntu-22.04
    timeout-minutes: 15
    if: "!startsWith(github.event.head_commit.message, '[skip ci] ')"

    steps:
      - name: GitHub event
        run: echo ${GITHUB_EVENT} | python3 -m json.tool
        env:
          GITHUB_EVENT: ${{ toJson(github) }}

      - uses: actions/checkout@v4

      - run: echo "${HOME}/.local/bin" >> ${GITHUB_PATH}
      - run: python3 -m pip install --user --requirement=ci/requirements.txt

      - uses: actions/cache@v4
        with:
          path: ~/.cache/pre-commit
          key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}
          restore-keys: "pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}\npre-commit-"
      - run: pre-commit run --all-files
      - run: git diff --exit-code --patch > /tmp/pre-commit.patch || true
        if: failure()

      - uses: actions/upload-artifact@v4
        with:
          name: Apply pre-commit fix.patch
          path: /tmp/pre-commit.patch
          retention-days: 1
        if: failure()
      - name: Print environment information
        run: c2cciutils-env
        env:
          GITHUB_EVENT: ${{ toJson(github) }}

      - name: Init pypi
        run: |-
          echo "[pypi]" > ~/.pypirc
          echo "username = ${{ secrets.PYPI_USERNAME }}" >> ~/.pypirc
          echo "password = ${{ secrets.PYPI_PASSWORD }}" >> ~/.pypirc
        if: env.HAS_SECRETS == 'HAS_SECRETS'
      - name: Publish
        run: c2cciutils-publish
        env:
          SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
          GITHUB_TOKEN: ${{ secrets.TOKEN }}
        if: env.HAS_SECRETS == 'HAS_SECRETS'
      - run: git diff --exit-code --patch > /tmp/dpkg-versions.patch || true
        if: failure()
      - uses: actions/upload-artifact@v4
        with:
          name: Update dpkg versions list.patch
          path: /tmp/dpkg-versions.patch
          retention-days: 1
        if: failure()