version: 2.1

orbs:
  codecov: codecov/codecov@1.0.2

defaults: &defaults
  docker:
    - image: circleci/node:12

  working_directory: ~/repo

jobs:
  test:
    <<: *defaults

    steps:
      - checkout

      - restore_cache:
          name: Restore Yarn Package Cache
          keys:
            - yarn-packages-{{ checksum "yarn.lock" }}

      - run:
          name: Install Dependencies
          command: yarn install --frozen-lockfile

      - save_cache:
          name: Save Yarn Package Cache
          key: yarn-packages-{{ checksum "yarn.lock" }}
          paths:
            - ~/.cache/yarn

      - run: yarn build

      - persist_to_workspace:
          root: ~/repo
          paths: .

      - run:
          name: Lint with ESLint
          command: yarn lint -- --format junit -o reports/junit/js-lint-results.xml

      - run:
          name: Run tests with JUnit as reporter
          command: yarn jest --ci --maxWorkers=2 --reporters=default --reporters=jest-junit --collectCoverage=true
          environment:
            JEST_JUNIT_OUTPUT: "reports/junit/js-test-results.xml"

      - store_test_results:
          path: reports/junit
      - store_artifacts:
          path: reports/junit
      - codecov/upload:
          file: coverage/*.json

  deploy:
    <<: *defaults

    steps:
      - attach_workspace:
          at: ~/repo

      - run:
          name: Authenticate with NPM registry
          command: echo "//registry.npmjs.org/:_authToken=$npm_TOKEN" > ~/repo/.npmrc

      - run:
          name: Publish package
          command: npm publish

workflows:
  version: 2
  test-deploy:
    jobs:
      - test:
          filters:
            tags:
              only: /^v.*/
      - deploy:
          requires:
            - test
          filters:
            tags:
              only: /^v.*/
            branches:
              ignore: /.*/
