#!/usr/bin/env bash set -euo pipefail expected_version="${GENARRATIVE_NPM_VERSION:?GENARRATIVE_NPM_VERSION 不能为空}" if [[ ! "${expected_version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then echo "[jenkins-npm] 非法 npm 版本: ${expected_version}" >&2 return 1 2>/dev/null || exit 1 fi if [[ -n "${GENARRATIVE_JENKINS_NPM_PREFIX:-}" ]]; then npm_prefix="${GENARRATIVE_JENKINS_NPM_PREFIX}" else npm_home="${HOME:?HOME 不能为空}" npm_prefix="${npm_home}/.local/share/genarrative/npm-${expected_version}" fi pinned_npm="${npm_prefix}/bin/npm" actual_version="" if [[ -x "${pinned_npm}" ]]; then actual_version="$("${pinned_npm}" --version 2>/dev/null || true)" fi if [[ "${actual_version}" != "${expected_version}" ]]; then bootstrap_npm="$(command -v npm || true)" if [[ -z "${bootstrap_npm}" ]]; then echo "[jenkins-npm] 缺少用于引导固定版本的 npm" >&2 return 1 2>/dev/null || exit 1 fi echo "[jenkins-npm] 准备 npm ${expected_version} (bootstrap=${bootstrap_npm})" mkdir -p "${npm_prefix}" "${bootstrap_npm}" install --global --prefix "${npm_prefix}" "npm@${expected_version}" --ignore-scripts --no-audit --no-fund fi export PATH="${npm_prefix}/bin:${PATH}" actual_version="$(npm --version)" if [[ "${actual_version}" != "${expected_version}" ]]; then echo "[jenkins-npm] npm 版本不匹配:期望 ${expected_version},实际 ${actual_version}" >&2 return 1 2>/dev/null || exit 1 fi echo "[jenkins-npm] npm=$(command -v npm) version=${actual_version}"