version: 2.1

defaults: &defaults
  working_directory: ~/truemail
  docker:
    - image: circleci/ruby:2.5.0-node
  environment:
    CC_TEST_REPORTER_ID: 693272a1328521f6f7c09d7ffd419b21c00410da26e98e94c687fdd38b26e2cb

orbs:
  ruby: circleci/ruby@1.1.2

references:
  restore_bundle_cache: &restore_bundle_cache
    restore_cache:
      keys:
        - truemail-{{ checksum "truemail.gemspec" }}

  bundle_install: &bundle_install
    run:
      name: Installing gems
      command: bundle install --path vendor/bundle

  save_bundle_cache: &save_bundle_cache
    save_cache:
      key: truemail-{{ checksum "truemail.gemspec" }}
      paths:
        - vendor/bundle

  install_codeclimate_reporter: &install_codeclimate_reporter
    run:
      name: Install Code Climate Test Reporter
      command: |
            curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
            chmod +x ./cc-test-reporter

jobs:
  linters:
    <<: *defaults

    steps:
      - checkout

      - <<: *restore_bundle_cache
      - <<: *bundle_install
      - <<: *save_bundle_cache

      - run:
          name: Running overcommit
          command: |
            bundle exec overcommit -s
            SKIP=AuthorEmail,AuthorName bundle exec overcommit -r

  tests:
    <<: *defaults

    steps:
      - checkout

      - <<: *restore_bundle_cache
      - <<: *bundle_install
      - <<: *save_bundle_cache
      - <<: *install_codeclimate_reporter

      - run:
          name: Running tests
          command: |
            mkdir /tmp/test-results
            ./cc-test-reporter before-build
            bundle exec rspec

      - run:
          name: Code Climate Test Coverage
          command: |
            ./cc-test-reporter format-coverage -t simplecov -o "coverage/codeclimate.$CIRCLE_NODE_INDEX.json"

      - store_test_results:
          path: /tmp/test-results

      - store_artifacts:
          path: /tmp/test-results
          destination: test-results

      - deploy:
          command: |
            ./cc-test-reporter sum-coverage --output - --parts $CIRCLE_NODE_TOTAL coverage/codeclimate.*.json | ./cc-test-reporter upload-coverage --debug --input -

  compatibility-with-ruby:
    parameters:
      ruby-version:
        type: string
    docker:
      - image: cimg/ruby:<< parameters.ruby-version >>
    steps:
      - checkout
      - ruby/install-deps:
          bundler-version: '1.16.6'
          with-cache: false
          path: './vendor/custom_bundle'
      - run:
          name: Running compatibility tests
          command: bundle exec rspec

workflows:
  build_and_test:
    jobs:
      - linters
      - tests
      - compatibility-with-ruby:
          matrix:
            parameters:
              ruby-version: ["2.6", "2.7", "3.0"]