version: 2

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

jobs:
  build:
    <<: *defaults

    steps:
      - checkout
      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "yarn.lock" }}
      - run: yarn install
      - run: yarn build
      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "yarn.lock" }}
      # - run: yarn test
      - persist_to_workspace:
          root: ~/repo
          paths: .

  deploy:
    <<: *defaults
    steps:
      - run:
          name: Placeholder
          command: echo "CircleCI cannot do AND operand on filters so this is a workaround"

  publish:
    <<: *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

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