version: 2.1

orbs:
  node: circleci/node@5.1.0

commands:
  run_danger_command:
    description: 'Run danger checks'
    steps:
      - run:
          name: Setup danger github token # set the DANGER_GITHUB_API_TOKEN to the GITHUB_TOKEN from the common context
          command: echo "export DANGER_GITHUB_API_TOKEN=${GITHUB_TOKEN}" >> $BASH_ENV

      - run:
          name: Run Danger Checks
          command: yarn danger ci -d danger.config.js

  run_lint_command:
    description: 'Run ESLint'
    steps:
      - run:
          name: 'Run ESLint'
          command: 'yarn run eslint'

  publish_package_command:
    description: 'Publish to npm'
    steps:
      - run:
          name: 'Authenticate with registry'
          command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/.npmrc
      - run:
          name: 'Publish package'
          command: npm publish --access public

jobs:
  publish_job:
    description: 'Publish the Package'
    docker:
      - image: 'cimg/node:lts'
    resource_class: small
    steps:
      - attach_workspace:
          at: ./
      - publish_package_command

  run_tests_job:
    description: 'Run Tests'
    docker:
      - image: 'cimg/node:lts'
    parameters:
      persist_workspace:
        type: boolean
        default: false
    resource_class: small
    steps:
      - checkout
      - node/install-packages:
          pkg-manager: yarn
      - run_lint_command
      - run_danger_command
      - when:
          condition: << parameters.persist_workspace >>
          steps:
            - persist_to_workspace:
                root: ./
                paths:
                  - ./

workflows:
  version: 2
  integrity_check:
    jobs:
      - run_tests_job:
          context:
            - common # use GITHUB_TOKEN
          name: Node LTS

  publish:
    jobs:
      - run_tests_job:
          context:
            - common # use GITHUB_TOKEN
          persist_workspace: true
          filters:
            tags:
              only: /^v.*/
            branches:
              ignore: /.*/

      - publish_job:
          context:
            - frontend-secrets # use NPM_TOKEN
          requires:
            - run_tests_job
          filters:
            tags:
              only: /^v.*/
            branches:
              ignore: /.*/
