version: 2

# this block contains anchors to reusable blocks of config.
references:
  setup_env: &setup_env
    docker:
      - image: circleci/node:8.11.0
  save_cache: &save_cache
    key: v1-dependency-cache-{{ checksum "yarn.lock" }}
    paths:
      - node_modules
  restore_cache: &restore_cache
    keys:
      - v1-dependency-cache-{{ checksum "yarn.lock" }}
      - v1-dependency-cache-
  reports_path: &reports_path
    path: ./reports
  run_on_tags: &run_on_tags
    filters:
      # run this job for tags as well
      tags:
        only: /.*/

jobs:
  build:
    <<: *setup_env
    steps:
      - checkout
      - restore_cache: *restore_cache
      - attach_workspace:
          at: '.'
      - run: yarn --frozen-lockfile
      - save_cache: *save_cache
      - run: mkdir ./reports
      - run: yarn compile
      - run: yarn lint --format junit --out ./reports/tslint.xml
      - store_artifacts:
          path: dist
      - store_test_results: *reports_path
      - persist_to_workspace:
          root: '.'
          paths:
            - dist

  test:
    <<: *setup_env
    steps:
      - checkout
      - restore_cache: *restore_cache
      - attach_workspace:
          at: '.'
      - run:
          command: yarn test --ci --testResultsProcessor="jest-junit"
          environment:
            JEST_JUNIT_OUTPUT: ./reports/jest.xml
      - store_test_results: *reports_path

  preview:
    <<: *setup_env
    steps:
      - checkout
      - restore_cache: *restore_cache
      - attach_workspace:
          at: '.'
      - run: yarn docs
      - store_artifacts:
          path: docs
      - run:
          name: Submit Github comment with links to built artifacts
          command: node theme/bot.js
          environment:
            # circle-github-bot@0.4.0 expects this env variable
            CIRCLE_ARTIFACTS: dopedopedope

  publish:
    <<: *setup_env
    steps:
      - checkout
      - restore_cache: *restore_cache
      - attach_workspace:
          at: '.'
      - run: echo "//registry.npmjs.org/:_authToken=${NPM_AUTH_TOKEN}" > .npmrc
      - run: chmod 0600 .npmrc
      - run: npm publish

workflows:
  version: 2
  build:
    jobs:
      - build: *run_on_tags
      - test: *run_on_tags
      - preview:
          requires: [build]
          # this job never runs on tags and ignores master
          filters:
            branches:
              ignore: /master/
      - publish:
          requires: [build, test]
          filters:
            # run this job only on tags, never on branches
            tags:
              only: /^release-.*/
            branches:
              ignore: /.*/

