restore_cache: &restore_cache
  keys:
    - node-modules-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ .Branch }}-{{ checksum "package-lock.json" }}
    - node-modules-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ checksum "package-lock.json" }}

save_cache: &save_cache
  key: node-modules-{{ arch }}-{{ .Environment.CIRCLE_JOB }}-{{ .Branch }}-{{ checksum "package-lock.json" }}
  paths:
    - node_modules

docker: &docker
  - image: "node:10"

browser_testing_steps: &browser_testing_steps
  - checkout
  - attach_workspace:
      at: "."
  - run: npm run build
  - run: npm test
  - store_test_results:
      path: reports
  - store_artifacts:
      path: reports

version: 2

jobs:
  install:
    docker: *docker
    environment:
      NPM_CONFIG_LOGLEVEL: warn
    steps:
      - checkout
      - restore_cache: *restore_cache
      - run: npm ci
      - save_cache: *save_cache
      - persist_to_workspace:
          root: .
          paths:
            - node_modules

  lint:
    docker: *docker
    steps:
      - checkout
      - attach_workspace:
          at: "."
      - run: npm run lint

  test:
    docker: *docker
    steps: *browser_testing_steps

  ensure-valid-credentials:
    docker: *docker
    steps:
      - checkout
      - attach_workspace:
          at: "."
      - run:
          name: "Check that the Semantic Release credentials are valid"
          command: |
            echo '//registry.npmjs.org/:_authToken=${NPM_TOKEN}' > ./.npmrc
            npm whoami

  release:
    docker: *docker
    environment:
      NODE_ENV: production
    steps:
      - checkout
      - attach_workspace:
          at: "."
      - deploy:
          name: "Semantic Release"
          command: |
            echo '//registry.npmjs.org/:_authToken=${NPM_TOKEN}' > ./.npmrc
            npm run build
            npm run semantic-release

workflows:
  version: 2
  build:
    jobs:
      - install
      - lint:
          requires:
            - install
      - test:
          context: "browser-testing"
          requires:
            - install
      - ensure-valid-credentials:
          context: "semantic-release"
          requires:
            - install
            - lint
            - test
      - release:
          context: "semantic-release"
          filters:
            branches:
              only: master
          requires:
            - install
            - lint
            - test
