# GitLab CI/CD Pipeline for ETPlot
# Builds a Docker image and runs tests inside it.

stages:
  - build
  - test
  - publish

variables:
  IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
  IMAGE_LATEST: $CI_REGISTRY_IMAGE:latest

# ---------------------------------------------------------------------------
# Build
# ---------------------------------------------------------------------------

build:image:
  stage: build
  image: docker:27
  services:
    - docker:27-dind
  variables:
    DOCKER_TLS_CERTDIR: "/certs"
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
  script:
    - docker build --pull -t "$IMAGE_TAG" .
    - docker push "$IMAGE_TAG"
  rules:
    - if: $CI_COMMIT_BRANCH

# ---------------------------------------------------------------------------
# Test
# ---------------------------------------------------------------------------

.test_base:
  stage: test
  image: docker:27
  services:
    - docker:27-dind
  variables:
    DOCKER_TLS_CERTDIR: "/certs"
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
    - docker pull "$IMAGE_TAG"
  needs:
    - build:image

test:pytest:
  extends: .test_base
  script:
    - docker run --rm -w /app "$IMAGE_TAG" python -m pytest tests/ -v
  artifacts:
    when: always
    expire_in: 30 days

test:coverage:
  extends: .test_base
  script:
    - |
      docker run --rm -w /app \
        -v "$CI_PROJECT_DIR:/artifacts" \
        "$IMAGE_TAG" \
        python -m pytest tests/ \
        --cov=gallery \
        --cov-report=xml:/artifacts/coverage.xml \
        --cov-report=term
  coverage: '/TOTAL.*\s+(\d+%)$/'
  artifacts:
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage.xml
    paths:
      - coverage.xml
    expire_in: 30 days

# ---------------------------------------------------------------------------
# Publish latest tag on main
# ---------------------------------------------------------------------------

publish:latest:
  stage: publish
  image: docker:27
  services:
    - docker:27-dind
  variables:
    DOCKER_TLS_CERTDIR: "/certs"
  before_script:
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" "$CI_REGISTRY"
  script:
    - docker pull "$IMAGE_TAG"
    - docker tag "$IMAGE_TAG" "$IMAGE_LATEST"
    - docker push "$IMAGE_LATEST"
  needs:
    - test:pytest
    - test:coverage
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
