# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

# include-install-pnpm
#
# This template can be included in pipelines to install pnpm with store caching enabled.

parameters:
  # The path containing the project(s) to build.
  - name: buildDirectory
    type: string

  # If set to false, the pnpm store will not be cached or restored from cache.
  - name: enableCache
    type: boolean
    default: true

  # The path to the pnpm store. The contents here will be cached and restored when using pnpm in a pipeline.
  - name: pnpmStorePath
    type: string
    default: $(Pipeline.Workspace)/.pnpm-store

steps:
  - ${{ if eq(parameters.enableCache, true) }}:
      - task: Cache@2
        displayName: Cache pnpm store
        timeoutInMinutes: 3
        continueOnError: true
        inputs:
          # Caches are already scoped to individual pipelines, so no need to include the release group name or tag
          # in the cache key
          key: pnpm-store | $(Agent.OS) | $(Agent.OSArchitecture) | ${{ parameters.buildDirectory }}/pnpm-lock.yaml
          path: ${{ parameters.pnpmStorePath }}
          restoreKeys: |
            pnpm-store | $(Agent.OS) | $(Agent.OSArchitecture)

  # workspace-concurrency 0 means use use the CPU core count. This is better than the default (4) for larger agents.
  - bash: |
      echo "Using node $(node --version)"
      storePath=${{ parameters.pnpmStorePath }}
      if [[ '$(Agent.OS)' == 'Windows_NT' ]]; then
        npm install -g corepack@0.31.0 --force
        corepack enable
        storePath=$PNPM_STORE_PATH
      else
        npm install -g corepack@0.31.0
        sudo corepack enable
      fi
      pnpm config set store-dir $storePath
      pnpm config set -g workspace-concurrency 0
      echo "Using pnpm $(pnpm -v)"
      echo "Using pnpm store path $(pnpm store path)"
    displayName: Install and configure pnpm
    workingDirectory: ${{ parameters.buildDirectory }}
    # The previous task (cache restoration) can timeout, which is classified as canceled, but since it's just cache
    # restoration, we want to continue even if it timed out.
    condition: or(succeeded(), canceled())
    env:
      PNPM_STORE_PATH: ${{ replace(parameters.pnpmStorePath, '\', '/') }}
