version: 2

jobs:
  build:
    docker:
      - image: circleci/node:10
    working_directory: ~/repo
    steps:
      - checkout
      # Download and cache dependencies
      - restore_cache:
          keys:
            - v10-dependencies-{{ checksum "package.json" }}
            # fallback to using the latest cache if no exact match is found
            - v10-dependencies-
      - run:
          name: Install dependencies
          command: npm install
      - save_cache:
          paths:
            - node_modules
          key: v10-dependencies-{{ checksum "package.json" }}
      - run:
          name: Build and compile
          command: npm run build
      - run:
          name: Run tests
          command: npm test
      - run:
          name: Lint files
          command: npm run lint
      - run:
          name: Upload code coverage
          command: npx codecov
      - persist_to_workspace:
          root: ~/repo
          paths: .

  publish:
    docker:
      - image: circleci/node:10
    working_directory: ~/repo
    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

workflows:
  version: 2
  build_and_publish:
    jobs:
      - build:
          filters:
            tags:
              only: /.*/
      - publish:
          requires:
            - build
          filters:
            tags:
              only: /^v.*/
            branches:
              ignore: /.*/
