---
include:
  - remote: https://jobs.just-ci.dev/v6.31.4/project-automation/version-pin-check.yml

variables:
  PYVERSION: slim
  PYTHON_EXCLUDE_PATHS: tests,setup.py,migrations
  PYTHON_EXCLUDE_REGEX: (tests|setup.py|migrations)
  PIP_DISABLE_PIP_VERSION_CHECK: "true"
  PIP_ROOT_USER_ACTION: ignore
  PIP_PACKAGE_INSTALL_DEFAULT_ARGS:
    --no-input -qqq --progress-bar=off --log=${CI_PROJECT_DIR}/pip-log.txt
    # If PIP_ENABLE_UV is set, then PIP_PACKAGE_INSTALL_DEFAULT_ARGS is overwritten by UV_PIP_PACKAGE_INSTALL_DEFAULT_ARGS
  PIP_PACKAGE_INSTALL_EXTRA_ARGS: ""
  UV_PIP_PACKAGE_INSTALL_DEFAULT_ARGS: -q --system

image:
  name: registry.gitlab.com/just-ci/images/python:$PYVERSION
  entrypoint: [""]

.python:pre:
  image:
    name: registry.gitlab.com/just-ci/images/python:$PYVERSION
    entrypoint: [""]
  stage: test
  script:
    - pip3 --version
    - pip3 install -qqq --progress-bar=off --log=${CI_PROJECT_DIR}/pip-log.txt
      ${JOB_PACKAGE} && echo "[+] ${JOB_PACKAGE} installed."
    - |
      echo "[*] Job info:"
      echo "Context path: ${PYTHON_CONTEXT:=.}"
      echo "User package: ${PYTHON_PACKAGE:-(not specified)}"
      echo "Excluded paths: ${PYTHON_EXCLUDE_PATHS:-(not specified)}"
      echo "Excluded regex: ${PYTHON_EXCLUDE_REGEX:-(not specified)}"
    - cd ${PYTHON_CONTEXT}
  artifacts:
    paths:
      - pip-log.txt
    when: always

.python:pre-install:
  stage: test
  script:
    - |
      pip3 --version
      if [ "${PIP_ENABLE_UV}" != "" ]; then
        pip3 install -qqq --progress-bar=off --log=${CI_PROJECT_DIR}/pip-log.txt uv
        uv --version
        shopt -s expand_aliases  # https://gitlab.com/gitlab-org/gitlab-runner/-/issues/1083
        alias pip3="uv pip"
        if [ "${VIRTUAL_ENV}" != "" ]; then
          UV_PIP_PACKAGE_INSTALL_DEFAULT_ARGS=${UV_PIP_PACKAGE_INSTALL_DEFAULT_ARGS/--system/}
        fi
        export PIP_PACKAGE_INSTALL_DEFAULT_ARGS=${UV_PIP_PACKAGE_INSTALL_DEFAULT_ARGS}
      fi
      echo "[*] Installing your package using these arguments: ${PIP_PACKAGE_INSTALL_DEFAULT_ARGS} ${PIP_PACKAGE_INSTALL_EXTRA_ARGS}"

    - |
      pip3 install ${PIP_PACKAGE_INSTALL_DEFAULT_ARGS} ${PIP_PACKAGE_INSTALL_EXTRA_ARGS} . || \
        {
          printf "[-] Install failed. Check 'pip-log.txt' in the job artifacts for details. ";
          if [ "${PIP_ALLOW_INSTALL_FAILURE}" != "" ]; then
            echo "PIP_ALLOW_INSTALL_FAILURE is set, so we continue. This may omit test results."
          else
            echo "To continue despite failure, set PIP_ALLOW_INSTALL_FAILURE. This may omit test results."
            exit 1
          fi
        }
  artifacts:
    paths:
      - pip-log.txt
    when: always

PIN-VERSION:PYVERSION:
  extends: .version-pin-check
  rules:
    - if: $PYVERSION !~ /^3\.[0-9]{1,2}.*$/
