version: 2

defaults: &defaults
  working_directory: ~/repo
  docker:
    - image: circleci/node:8.9.1

jobs:
  test:
    <<: *defaults
    steps:
      - checkout
      # Download and cache dependencies
      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "package.json" }}
      - run:
          name: Install dependencies
          command: |
            npm install
      - save_cache:
          key: v1-dependencies-{{ checksum "package.json" }}
          paths:
            - ./node_modules
      - persist_to_workspace:
          root: ~/repo
          paths: .
      - run:
          name: Code Climate Test Reporter
          command: |
            # download test reporter as a static binary
            curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
            chmod +x ./cc-test-reporter
      - run:
          name: Run Tests
          command: |
            # notify Code Climate of a pending test report using `before-build`
            set -e
            ./cc-test-reporter before-build
            npm test
            # upload test report to Code Climate using `after-build`
            ./cc-test-reporter after-build --exit-code $?
  deploy:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/repo
      - run:
          name: Authenticate with registry
          command: echo "//registry.npmjs.org/:_authToken=$npm_TOKEN" > ~/repo/.npmrc
      - run:
          name: Publish package
          command: npm publish --access public

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