version: 2

defaults: &defaults
  working_directory: ~/repo
  docker:
    - image: circleci/node:8.11.2

jobs:

  build:
    <<: *defaults  
    steps:
      - checkout
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "package.json" }}
          - v1-dependencies-

      - run: yarn install

      - run:
          name: Run build
          command: yarn build

      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}
  
  lint:
    <<: *defaults  
    steps:
      - checkout
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "package.json" }}
          - v1-dependencies-

      - run: yarn install
      
      - run:
          name: Run lint
          command: yarn lint --format junit -o reports/junit/js-lint-results.xml

      - store_test_results:
          path: reports/junit

      - store_artifacts:
          path: reports/junit

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

      - persist_to_workspace:
          root: ~/repo
          paths: .

  test:
    <<: *defaults  
    steps:
      - checkout
      - restore_cache:
          keys:
          - v1-dependencies-{{ checksum "package.json" }}
          - v1-dependencies-

      - run: yarn install
      
      - run:
          name: Run tests
          command: yarn test:unit

      - run:
          name: "JavaScript Test Suite"
          command: yarn jest --ci --reporters="jest-junit"
          environment:
            JEST_JUNIT_OUTPUT: "reports/junit/js-test-results.xml"

      - store_test_results:
          path: reports/junit

      - store_artifacts:
          path: reports/junit

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

      - persist_to_workspace:
          root: ~/repo
          paths: .
  
  deployDocs:
    <<: *defaults
    filters:
      branches:
        only: master
    environment:
      - SOURCE_BRANCH: master
      - TARGET_BRANCH: gh-pages
    docker:
      - image: circleci/node:8.11.2
    steps:
      - checkout
      - run: yarn global add vuepress
      - run: sh ./deploy.sh

workflows:
  version: 2
  test-deploy:
    jobs:
      - build
      - test
      - lint
      - deployDocs
