version: 2.1

executors:
  default:
    docker:
      - image: circleci/node:14
    working_directory: ~/project

commands:
  attach_project:
    steps:
      - attach_workspace:
          at: ~/project

jobs:
  install-dependencies:
    executor: default
    steps:
      - checkout
      - attach_project
      - restore_cache:
          keys:
            - dependencies-{{ checksum "package.json" }}
      - run:
          name: Install dependencies
          command: |
            npm install
      - save_cache:
          key: dependencies-{{ checksum "package.json" }}
          paths: node_modules
      - persist_to_workspace:
          root: .
          paths: .

  lint:
    executor: default
    steps:
      - attach_project
      - run:
          name: Lint files
          command: |
            npm run lint

  typescript:
    executor: default
    steps:
      - attach_project
      - run:
          name: Typecheck files
          command: |
            npm run typescript

  unit-tests:
    executor: default
    steps:
      - attach_project
      - run:
          name: Run unit tests
          command: |
            npm test --coverage
      - store_artifacts:
          path: coverage
          destination: coverage

  build-package:
    executor: default
    steps:
      - attach_project
      - run:
          name: Build package
          command: |
            npm run prepare
  
  release:
    executor: default
    steps:
      - attach_project
      - run:
          name: Release to GitHub
          command: npm run release -- --ci

  publish:
    executor: default
    steps:
      - attach_project
      - run:
          name: Authenticate with registry
          command: |
            echo "//registry.npmjs.org/:authToken=$NPM_TOKEN" > ~/project/.npmrc
            echo "scope=$NPM_SCOPE"
      - run:
          name: Publish package
          run: npm publish --access public

workflows:
  build:
    jobs:
      - install-dependencies
      - lint:
          requires:
            - install-dependencies
      - typescript:
          requires:
            - install-dependencies
      - unit-tests:
          requires:
            - install-dependencies
      - build-package:
          requires:
            - install-dependencies
            - lint
            - typescript
            - unit-tests
      - release:
          context: mattermost-rn-libraries
          requires:
            - build-package
          fliters:
            branches:
              only: /^release-\d+$/
      - publish:
          context: mattermost-rn-libraries
          requires:
            - build-package
          filters:
            tags:
              only: /^v(\d+\.)(\d+\.)(\d+)(.*)?$/
            branches:
              ignore: /.*/
