version: 2.1
defaults: &defaults
  docker:
    - image: circleci/node:latest
  working_directory: ~/repo

restore_src_cache: &restore_src_cache
  keys:
    - source-v7-{{ .Branch }}-{{ .Revision }} # cache hit from the current git revision
    - source-v7-{{ .Branch }}- # cache hit from the current branch
    - source-v7- # any cache hit

save_src_cache: &save_src_cache
  key: source-v7-{{ .Branch }}-{{ .Revision }}
  paths:
    - ~/repo

restore_npm_cache: &restore_npm_cache
  keys:
    - npm-deps-v7-{{ checksum "package.json" }}
    # fallback to using the latest cache if no exact match is found
    - npm-deps-v7-

save_npm_cache: &save_npm_cache
  key: npm-deps-v7-{{ checksum "package.json" }}
  paths:
    - node_modules

save_build_cache: &save_build_cache
  key: build-v7-{{ .Branch }}-{{ .Revision }}
  paths:
    - ~/repo/dist

avoid_hosts_unkown_github: &avoid_hosts_unknown_github
  name: Avoid hosts unknown for github
  command: mkdir ~/.ssh/ && echo -e "Host github.com\n\tStrictHostKeyChecking no\n" > ~/.ssh/config

auth_npm: &auth_npm
  name: 'set up npm auth'
  command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/repo/.npmrc

configure_git_email: &configure_git_email
  name: 'configure git email'
  command: git config user.email "circleci@pie-framework.org"

configure_git_user: &configure_git_user
  name: 'configure git user'
  command: git config user.name "Circle ci"

restore_build_cache: &restore_build_cache
  keys:
    - build-v7-{{ .Branch }}-{{ .Revision }}

jobs:
  install:
    <<: *defaults
    steps:
      - restore_cache: *restore_src_cache
      - checkout
      - save_cache: *save_src_cache
      - restore_cache: *restore_npm_cache
      - run: npm install
      - save_cache: *save_npm_cache

  test:
    <<: *defaults
    steps:
      - restore_cache: *restore_src_cache
      - restore_cache: *restore_npm_cache
      - run: npm test

  release:
    <<: *defaults
    steps:
      - run: *auth_npm
      - run: *avoid_hosts_unknown_github
      - restore_cache: *restore_src_cache
      - restore_cache: *restore_npm_cache
      - restore_cache: *restore_build_cache
      - run: *configure_git_email
      - run: *configure_git_user
      - run:
          name: check git status
          command: git status
      - run:
          name: release
          command: npm run release

workflows:
  version: 2
  main:
    jobs:
      - install
      - test:
          requires:
            - install
      - release:
          requires:
            - test
