defaults: &defaults
  working_directory: ~/src
  docker:
    - image: circleci/node:8.11@sha256:46a1ff8ab7579d46bef45eaa4a079f6f1917df329a6d064b68210c68b29a071a

whitelist: &whitelist
  paths:
    - "**"

version: 2
jobs:
  checkout:
    <<: *defaults
    steps:
      - checkout
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "package.json" }}
          - v1-dependencies-
      - run:
          name: Install Dependencies
          command: npm install
      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}
      - persist_to_workspace:
          root: ~/src
          <<: *whitelist

  build:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/src
      - run:
          name: Compile source
          command: make compile
      - persist_to_workspace:
          root: ~/src
          <<: *whitelist

  test:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/src
      - run:
          name: Run tests
          command: make test-ci
      - persist_to_workspace:
          root: ~/src
          <<: *whitelist

  codecov:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/src
      - run:
          name: Publish Code coverage
          command: bash <(curl -s https://codecov.io/bash)

  deploy:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/src
      - run: 
          name: Write NPM Token to ~/.npmrc
          command: echo "//registry.npmjs.org/:_authToken=${NPM_TOKEN}" >> ~/.npmrc
      - run:
          name: Publish to NPM
          command: npm publish --access=public

workflows:
  version: 2
  build:
    jobs:
      - checkout
      - build:
          requires:
            - checkout
      - test:
          requires:
            - build
      - codecov:
          requires:
            - test

  release:
    jobs:
      - checkout:
          filters:
            tags:
              only: /v[0-9]+(\.[0-9]+)*/
            branches:
              ignore: /.*/
      - build:
          filters:
            tags:
              only: /v[0-9]+(\.[0-9]+)*/
            branches:
              ignore: /.*/
          requires:
            - checkout
      - test:
          filters:
            tags:
              only: /v[0-9]+(\.[0-9]+)*/
            branches:
              ignore: /.*/
          requires:
            - build
      - codecov:
          filters:
            tags:
              only: /v[0-9]+(\.[0-9]+)*/
            branches:
              ignore: /.*/
          requires:
            - test
      - deploy:
          filters:
            tags:
              only: /v[0-9]+(\.[0-9]+)*/
            branches:
              ignore: /.*/
          requires:
            - test
            - codecov
