version: 2

defaults:
  workspace_root: &workspace_root
    ~/react-native-dotenv

  nodejs_container: &nodejs_container
    working_directory: *workspace_root
    docker:
      - image: circleci/node:12-stretch

  filters: &default_filters
    tags:
      only: '/v[0-9]+(\.[0-9]+)*/'

  attach_workspace: &attach_workspace
    attach_workspace:
      at: *workspace_root

  restore_node_modules: &restore_node_modules
    restore_cache:
      name: Restore node_modules cache
      keys:
        - v3-react-native-dotenv-node-{{ .Branch }}-{{ checksum "yarn.lock" }}
        - v3-react-native-dotenv-node-main-{{ checksum "yarn.lock" }}
        - v3-react-native-dotenv-node-main-

jobs:
  checkout:
    <<: *nodejs_container
    steps:
      - checkout

      - persist_to_workspace:
          root: *workspace_root
          paths:
            - ./

  install:
    <<: *nodejs_container
    steps:
      - *attach_workspace
      - *restore_node_modules

      - restore_cache:
          name: Restore yarn cache
          keys:
            - v3-react-native-dotenv-yarn-{{ checksum "yarn.lock" }}
            - v3-react-native-dotenv-yarn-

      - run:
          name: Install dependencies
          command: yarn --frozen-lockfile

      - save_cache:
          name: Save yarn cache
          key: v3-react-native-dotenv-yarn-{{ checksum "yarn.lock" }}
          paths:
            - ~/.cache/yarn/

      - save_cache:
          name: Save node_modules cache
          key: v3-react-native-dotenv-node-{{ .Branch }}-{{ checksum "yarn.lock" }}
          paths:
            - node_modules/

  lint:
    <<: *nodejs_container
    steps:
      - *attach_workspace
      - *restore_node_modules

      - run:
          name: Lint JavaScript
          command: yarn xo

  test:
    <<: *nodejs_container
    steps:
      - *attach_workspace
      - *restore_node_modules

      - run:
          name: Run tests
          command: yarn test

      - store_test_results:
          path: reports/tests/

      - run:
          name: Upload code coverage to codecov
          command: yarn codecov

workflows:
  version: 2

  push:
    jobs:
      - checkout:
          filters: *default_filters

      - install:
          requires:
            - checkout
          filters: *default_filters

      - lint:
          requires:
            - install
          filters: *default_filters

      - test:
          requires:
            - install
          filters: *default_filters
