# Check https://circleci.com/docs/2.0/language-javascript/ for more details
version: 2
jobs:
  run_tests:
    docker:
      - image: circleci/node:12

    working_directory: ~/repo

    steps:
      - checkout

      - run: sudo git clone https://github.com/sstephenson/bats.git ~/bats
      - run: pushd ~/bats && sudo bash install.sh /usr/local && popd

      - run: ln -s ~/repo ~/$CIRCLE_PROJECT_REPONAME

      # Download and cache dependencies
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "package.json" }}
          # fallback to using the latest cache if no exact match is found
          - v1-dependencies-

      - run: npm install

      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}

      - run: npm run commitlint-last-commit
      - run: npm test

  npm_publish:
    working_directory: ~/repo
    docker:
      - image: circleci/node:12
    steps:
      - checkout
      - run:
          name: auth with npm
          command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/repo/.npmrc
      - run: bash .circleci/npm-publish.sh

  build_docker_image:
    working_directory: ~/repo
    docker:
      - image: docker:18
    steps:
      - checkout
      - setup_remote_docker
      - run: sh .circleci/docker-build.sh

workflows:
  version: 2
  test:
    jobs:
      - run_tests
  publish:
    jobs:
      - run_tests:
          filters: &filters-publish
            branches:
              ignore: /.*/
            tags:
              only: /^v.*/
      - build_docker_image:
          requires:
            - run_tests
          filters:
            <<: *filters-publish
      - npm_publish:
          requires:
            - run_tests
          filters:
            <<: *filters-publish
