version: 2.1

jobs:
  build:
    docker:
      - image: alpine
    steps:
      - checkout
      - run: |
          apk add --no-cache \
            python3 \
            pkgconfig \
            make \
            g++ \
            imagemagick imagemagick-dev \
            nodejs \
            npm
      - restore_cache:
          keys:
            - node-modules-{{ checksum "package-lock.json" }}
            - node-modules-
      - run: npm i
      - save_cache:
          key: node-modules-{{ checksum "package-lock.json" }}
          paths:
            - node_modules
      - run: npm run build
      - persist_to_workspace:
          root: .
          paths:
            - .

  test:
    docker:
      - image: alpine
    steps:
      - attach_workspace:
          at: .
      - run: |
          apk add --no-cache \
            imagemagick imagemagick-dev \
            nodejs \
            npm
      - run: |
          npm run test:coverage
          npm run coverage
      - store_test_results:
          path: .
      - store_artifacts:
          path: ./coverage/lcov-report

  publish:
    docker:
      - image: cimg/node:14.18
    steps:
      - attach_workspace:
          at: .
      - run: |
          export COMMIT_MESSAGE="$(git log --format=oneline -n 1 $CIRCLE_SHA1)"

          if [[ $COMMIT_MESSAGE == *"[skip npm]"* ]]; then
            echo "Skipping npm publish."
          else
            echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > .npmrc
            npm publish
          fi

workflows:
  build_and_test:
    jobs:
      - build
      - test:
          requires:
            - build
      - publish:
          context: npm
          requires:
            - test
          filters:
            branches:
              only:
                - main

  test_nightly:
    triggers:
      - schedule:
          cron: '0 0 * * *'
          filters:
            branches:
              only:
                - main
    jobs:
      - build
      - test:
          requires:
            - build
