version: 2

references:
  container: &container
    docker:
      - image: circleci/node:8.10-browsers
        environment:
          CHROME_PATH: /usr/bin/google-chrome
  
  restore_deps: &restore_deps
    restore_cache:
      keys:
        - v1-uswds-dependencies-{{ checksum "package-lock.json" }}
        - v1-uswds-dependencies-

jobs:
  build:
    <<: *container
    steps:
      - checkout
      - run:
          name: Install codeclimate
          command: sudo npm install -g codeclimate-test-reporter
      - restore_cache:
          keys:
          - v1-uswds-dependencies-{{ checksum "package-lock.json" }}
          - v1-uswds-dependencies-
      - run: npm install
      - save_cache:
          paths:
            - node_modules
          key: v1-uswds-dependencies-{{ checksum "package-lock.json" }}
      - run:
          name: Run test
          command: npm test
      - run:
          name: Run code coverage report
          command: npm run cover
      - run:
          name: Checking build
          command: |
            if [[ $(echo "$CIRCLE_BRANCH" | grep -c "pull") -le 0 ]]; then
              ls -agolf dist/
              codeclimate-test-reporter < coverage/lcov.info
            fi

  deploy:
    <<: *container
    steps:
      - checkout
      - restore_cache:
          keys:
          - v1-uswds-dependencies-{{ checksum "package-lock.json" }}
          - v1-uswds-dependencies-
      - run: npm install --ignore-scripts
      - run:
          name: Build the USWDS package
          command: npm run release
      - run:
          name: Publish to NPM
          command: |
            npm config set "//registry.npmjs.org/:_authToken=$NPM_TOKEN"
            npm publish
      - run:
          name: Update dependencies in Snyk dashboard
          command: snyk monitor --org=uswds

workflows:
  version: 2
  build_and_deploy:
    jobs:
      - build
      - deploy:
          requires:
            - build
          filters:
            branches:
              only: master
