version: 2

buildSteps: &buildSteps
  - checkout
  - run:
      name: Install
      command: npm install --loglevel warn
  - run:
      name: Test
      command: npm test --loglevel warn
  - persist_to_workspace:
      # Persist all job output, so we can (potentially) use it for deploys
      root: ../
      paths:
        - ./node-*

jobs:
  node-6:
    docker:
      - image: circleci/node:6
    working_directory: ~/node-6
    steps: *buildSteps

  node-8:
    docker:
      - image: circleci/node:8
    working_directory: ~/node-8
    steps: *buildSteps

  node-10:
    docker:
      - image: circleci/node:10
    working_directory: ~/node-10
    steps: *buildSteps

  deploy:
    # For this to work NPM_TOKEN must be set for the account used for publishing
    docker:
      - image: circleci/node:8
    steps:
      - attach_workspace:
          at: $CIRCLE_WORKING_DIRECTORY
      - run:
          name: Login
          command: |
            echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
            npm whoami
      - deploy:
          name: Deploy
          command: npm publish
          # Output used for publish is from node 8 build
          working_directory: $CIRCLE_WORKING_DIRECTORY/node-8

workflows:
  version: 2
  build:
    jobs:
      - node-6:
          # Run for all tags (required to allow the deploy to trigger on version tags)
          filters:
            tags:
              only: /.*/
      - node-8:
          # Run for all tags (required to allow the deploy to trigger on version tags)
          filters:
            tags:
              only: /.*/
      - node-10:
          # Run for all tags (required to allow the deploy to trigger on version tags)
          filters:
            tags:
              only: /.*/
      - deploy:
          # Deploy passing builds if they're tagged with a version
          requires:
            - node-6
            - node-8
            - node-10
          filters:
            tags:
              only: /^v\d+\.\d+\.\d+$/
            branches:
              ignore: /.*/
