# These environment variables must be set in CircleCI UI
#
# NPM_TOKEN - A valid NPM token for releases
version: 2.1

references:
  defaults: &defaults
    working_directory: ~/eslint-plugin-amo
    docker:
      # This is the NodeJS version we run in production.
      - image: cimg/node:22.22

  defaults-next: &defaults-next
    working_directory: ~/eslint-plugin-amo
    docker:
      # This is the next NodeJS version we will support.
      - image: cimg/node:24.14

  restore_build_cache: &restore_build_cache
    restore_cache:
      name: restore npm package cache
      keys:
        - npm-packages-{{ checksum "package-lock.json" }}

  run_npm_install: &run_npm_install
    run:
      name: install dependencies
      command: npm install

  save_build_cache: &save_build_cache
    save_cache:
      name: save npm package cache
      key: npm-packages-{{ checksum "package-lock.json" }}
      paths:
        - ./node_modules

  restore_next_build_cache: &restore_next_build_cache
    restore_cache:
      name: restore npm package cache
      keys:
        - next-npm-packages-{{ checksum "package-lock.json" }}

  save_next_build_cache: &save_next_build_cache
    save_cache:
      name: save npm package cache
      key: next-npm-packages-{{ checksum "package-lock.json" }}
      paths:
        - ./node_modules

jobs:
  test:
    <<: *defaults
    steps:
      - checkout
      - *restore_build_cache
      - *run_npm_install
      - *save_build_cache
      - run: npm test
      # Set up a workspace to share data between this job and the `release-tag`
      # one when we want to publish a new npm version.
      - persist_to_workspace:
          root: ~/eslint-plugin-amo
          paths: .

  test-next:
    <<: *defaults-next
    steps:
      - checkout
      - *restore_next_build_cache
      - *run_npm_install
      - *save_next_build_cache
      - run: npm test

  release-tag:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/eslint-plugin-amo
      - run:
          name: authenticate with registry
          # We don't want to expand the token in this file, npm will do it.
          command: echo '//registry.npmjs.org/:_authToken=${NPM_TOKEN}' > ~/eslint-plugin-amo/.npmrc
      - run:
          name: publish package
          command: npm publish

workflows:
  version: 2
  default-workflow:
    jobs:
      - test:
          filters: # required since `release-tag` has tag filters AND requires `test`
            tags:
              only: /.*/
      - test-next
      - release-tag:
          requires:
            - test
          filters:
            tags:
              only: /.*/
            branches:
              ignore: /.*/
