stages:
  - build
  - test
  - pages
  - build_image
  - staging

variables:
  IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME


# ========================== Build Testing section =========================== #
build_test_env:
  image: python:3.6
  stage: build
  script:
    - python -m venv .venv
    - source .venv/bin/activate
    - make install
  artifacts:
    paths:
      - .venv/
    expire_in: 20 minutes
  cache:
    paths:
      - .venv

# ============================== Testing section ============================= #
# ----------------------------- Backend subsection --------------------------- #
.test_template_virtualenv: &test_definition_virtualenv
  image: python:3.6
  before_script:
    - source .venv/bin/activate
  dependencies:
    - build_test_env

test_pytest:
  <<: *test_definition_virtualenv
  stage: test
  services:
    - postgres:9.5
  script:
    - DJANGO_SETTINGS_MODULE=grady.settings pytest --cov
  artifacts:
    paths:
      - .coverage

test_flake8:
  <<: *test_definition_virtualenv
  stage: test
  script:
    - flake8 --exclude=migrations --ignore=N802 core

# ----------------------------- Frontend subsection -------------------------- #
.test_template_frontend: &test_definition_frontend
  image: node:carbon
  before_script:
    - cd frontend/

test_frontend:
  <<: *test_definition_frontend
  stage: test
  script:
    - yarn install
    - yarn test --single-run
  cache:
    paths:
      - frontend/node_modules/

# =========================== Gitlab pages section =========================== #
pages:
  <<: *test_definition_virtualenv
  stage:
    pages
  script:
    - coverage html -d public
  dependencies:
    - test_pytest
    - build_test_env
  artifacts:
    paths:
      - public
  only:
    - master

# =========================== Build Image section ============================ #
build_backend:
  image: docker:latest
  stage: build_image
  script:
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
    - docker build -t $IMAGE_TAG .
    - docker push $IMAGE_TAG
  only:
    - master

# ============================== Staging section ============================= #
.staging_template: &staging_definition
  stage: staging
  image: docker:latest
  only:
    - master
  before_script:
    - apk add --update py-pip && pip install docker-compose

staging:
  <<: *staging_definition
  environment:
    name: review/$CI_COMMIT_REF_NAME
    url: https://staging.grady.janmax.org
    on_stop: staging_stop
  script:
    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN $CI_REGISTRY
    - docker-compose up -d --force-recreate

staging_stop:
  <<: *staging_definition
  script:
    - docker-compose rm --force --stop
  when: manual
  environment:
    name: review/$CI_COMMIT_REF_NAME
    action: stop