Compare commits

...

16 Commits

Author SHA1 Message Date
Zoltan Kochan
6b87c4621a
fix: Windows standalone mode — bypass broken npm shims (#217)
* fix: overwrite npm .cmd wrappers for @pnpm/exe on Windows

npm creates .cmd wrappers that invoke bin entries through `node`,
but @pnpm/exe bins are native executables, not JavaScript files.
This causes pnpm commands to silently fail on Windows.

* fix: copy pnpm.exe to .bin/ on Windows for standalone mode

The .cmd wrapper approach didn't work because CMD doesn't properly
wait for extensionless PE binaries. Instead, copy the actual .exe
(and .cmd for pnpx) from @pnpm/exe into .bin/ so PATHEXT finds
pnpm.exe directly, bypassing npm's broken node-wrapping shim.

* fix: add @pnpm/exe dir to PATH on Windows instead of .bin shims

On Windows, npm's .bin shims can't properly execute the extensionless
native binaries from @pnpm/exe. Instead of trying to fix the shims,
add the @pnpm/exe directory directly to PATH where pnpm.exe lives.

* test: validate pnpm --version output in CI

All version checks now capture output and assert it matches a semver
pattern. Previously, a silently failing pnpm (exit 0, no output)
would pass the tests.

* debug: log pnpm --version output during setup

* fix: remove duplicate addPath in setOutputs that shadowed pnpm.exe

setOutputs called addPath(node_modules/.bin) AFTER installPnpm had
already added the correct path (@pnpm/exe on Windows). Since
GITHUB_PATH entries are prepended, .bin ended up first in PATH,
causing PowerShell to find npm's broken shims instead of pnpm.exe.

* fix: add PNPM_HOME/bin to PATH on all platforms

* fix: address review feedback — PATH ordering and regex anchoring

- Swap addPath order so pnpmHome (with pnpm.exe) is prepended last
  and has highest precedence over pnpmHome/bin.
- Anchor version regex with $ and allow prerelease suffixes.
2026-03-27 20:42:10 +01:00
Zoltan Kochan
994d756a33
feat: read pnpm version from devEngines.packageManager (#211)
* feat: read pnpm version from devEngines.packageManager field

When no version is specified in the action config or the packageManager
field of package.json, fall back to devEngines.packageManager.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: skip self-update for devEngines.packageManager and add CI tests

pnpm auto-switches to the right version when devEngines.packageManager
is set, so self-update is unnecessary. This also enables range support
(e.g. ">=9.15.0") which self-update doesn't handle.

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-27 11:10:47 +01:00
Zoltan Kochan
738f428026
docs: upgrade pnpm/action-setup from v4 to v5 2026-03-26 22:31:06 +01:00
Zoltan Kochan
62bce64275
fix: extract pnpm version from packageManager field instead of returning undefined (#216)
When packageManager is set to e.g. "pnpm@9.1.0+sha...", strip the
"pnpm@" prefix and any "+sha..." hash suffix so the action installs
the correct version. Previously returning undefined caused failures
on Windows.
2026-03-25 13:59:54 +01:00
Zoltan Kochan
58e6119fe4
feat!: replace bundled pnpm binary with npm + lockfile bootstrap (#212)
* feat!: replace bundled pnpm binary with npm + lockfile bootstrap

Remove the 9MB bundled pnpm.cjs/worker.js and instead use npm ci with
committed package-lock.json files (~5KB) to install a bootstrap pnpm,
which then installs the target version with integrity verification via
the project's pnpm-lock.yaml.

Also switch from ncc to esbuild and modernize to ESM.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: bundle as CJS to support @actions/* packages

The @actions/* packages use CJS require() for Node.js builtins,
which fails with "Dynamic require of 'os' is not supported" when
bundled as ESM. Switch esbuild output to CJS format.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: remove "type": "module" from package.json

Node.js treats dist/index.js as ESM due to "type": "module",
but the bundle uses CJS require() calls. Remove the field so
Node.js defaults to CJS for .js files.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: remove packageManager field and fix Windows npm spawn

- Remove packageManager from package.json to avoid version conflict
  when the action tests against itself (uses: ./)
- Use shell: true on Windows so spawn can find npm.cmd

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: always use pnpm (not @pnpm/exe) for bootstrap and update lockfile

The bootstrap only needs regular pnpm to install the target package.
@pnpm/exe requires install scripts which we skip with --ignore-scripts.
Also regenerate pnpm-lock.yaml to match current package.json.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: use --no-lockfile for target install

--lockfile-dir pointing to GITHUB_WORKSPACE causes the bootstrap pnpm
to use the project's pnpm-lock.yaml (which tracks project deps, not
pnpm itself), corrupting the install. Revert to --no-lockfile for now.
Lockfile-based integrity verification can be added when pnpm v11 has
proper support for verifying the pnpm package itself.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: run bootstrap pnpm via node instead of bin shim

Use `node .../pnpm/bin/pnpm.cjs` to run the bootstrap pnpm, matching
the approach used by the old bundled pnpm.cjs. This avoids issues with
the .bin symlink on different platforms.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: use pnpm self-update instead of installing target separately

- Bootstrap pnpm via npm ci (verified by lockfile)
- Use `pnpm self-update <version>` for explicit version
- Let pnpm handle packageManager field automatically
- Remove standalone/exe-specific install logic (pnpm handles this)
- Update tests to not run pnpm install against the action repo itself

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: support standalone mode with @pnpm/exe bootstrap

- When standalone=true, bootstrap with @pnpm/exe via npm ci
- When standalone=false, bootstrap with pnpm via npm ci
- Both use pnpm self-update to reach the target version
- Remove --ignore-scripts from npm ci so @pnpm/exe install scripts run
- Add standalone test back to CI

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* debug: add logging to diagnose pnpm not found on PATH

Log .bin directory contents after npm ci to understand why
pnpm binary is not found in subsequent CI steps.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: ensure pnpm bin link exists after npm ci

npm ci sometimes doesn't create the .bin/pnpm symlink for
@pnpm/exe (observed on Linux CI). Manually create the symlink
if it's missing after npm ci completes.

This fixes the case where standalone=true with no explicit version
(relying on packageManager field) — pnpm self-update wouldn't run,
leaving .bin empty and pnpm not found on PATH.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add PNPM_HOME/bin to PATH for pnpm v11

pnpm v11 moved global binaries from PNPM_HOME to PNPM_HOME/bin.
Add the new bin subdirectory to PATH so that pnpm's global bin
directory check passes. This is backwards compatible — the extra
PATH entry is harmless for older pnpm versions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add packages field to pnpm-workspace.yaml

pnpm v9 requires the packages field in pnpm-workspace.yaml.
Without it, `pnpm --version` fails with "packages field missing or empty".

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix pnpm-workspace.yaml

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-21 14:02:31 +01:00
axel7083
2e223e0f0d
chore(workflows): adding pr-check.yaml to validate dist folder (#213)
* chore(workflows): adding pr-check.yaml to validate dist/index.js

Signed-off-by: axel7083 <42176370+axel7083@users.noreply.github.com>

* fix: update dist/index.js

Signed-off-by: axel7083 <42176370+axel7083@users.noreply.github.com>

---------

Signed-off-by: axel7083 <42176370+axel7083@users.noreply.github.com>
2026-03-19 14:52:48 +01:00
Zoltan Kochan
fc06bc1257
feat!: run the action on Node.js 24 (#205) 2026-03-13 11:30:26 +01:00
Zoltan Kochan
b906affcce
Revert "feat!: run the action on Node.js 24 (#205)"
This reverts commit 9b5745cdf0.
2026-03-11 15:54:42 +01:00
Zoltan Kochan
9b5745cdf0
feat!: run the action on Node.js 24 (#205) 2026-02-17 13:30:54 +01:00
Boosted-Bonobo
1e1c8eafbd
ci: pin github actions (#199) 2025-12-15 14:31:35 +01:00
Khải
b9e1dbc72f
fix(ci): exclude macos (#197) 2025-12-10 13:54:29 +01:00
Khải
61bc82c7df
refactor: remove star imports (#196) 2025-12-10 13:14:52 +01:00
Jeremiasz Major
e94b270858
feat: store caching (#188)
* add pnpm store caching

* style: format

* no semicolons
* no star imports
* import order

* style: no star imports

---------

Co-authored-by: khai96_ <hvksmr1996@gmail.com>
2025-12-07 22:16:49 +01:00
Chris Martin
ee7b8711bd
Clarify that package_json_file is relative to GITHUB_WORKSPACE (#184)
* Clarify that package_json_file is relative to GITHUB_WORKSPACE

Clarify the description for package_json_file parameter to specify that the path must be relative to the repository root.

* Apply suggestion from @zkochan

---------

Co-authored-by: Zoltan Kochan <z@kochan.io>
2025-12-07 01:36:02 +01:00
silverwind
3a0024f066
Remove unused @types/node-fetch dependency (#186) 2025-12-05 16:50:59 +01:00
Roman Usherenko
72f04517b7
Update README.md (#175)
fix the string run_install example
2025-12-05 15:32:46 +01:00
24 changed files with 1549 additions and 237594 deletions

28
.github/workflows/pr-check.yaml vendored Normal file
View File

@ -0,0 +1,28 @@
name: pr-check
on: [ pull_request ]
permissions:
contents: read
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: true
jobs:
check-dist:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Setup pnpm
uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v5.0.0
with:
run_install: true
version: 9
- name: Update dist/index.js
run: pnpm run build
- name: Check for uncommitted changes in dist
run: git diff --exit-code dist/index.js

View File

@ -22,7 +22,7 @@ jobs:
- windows-latest - windows-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Run the action - name: Run the action
uses: ./ uses: ./
@ -32,8 +32,23 @@ jobs:
- name: 'Test: which' - name: 'Test: which'
run: which pnpm; which pnpx run: which pnpm; which pnpx
- name: 'Test: install' - name: 'Test: version'
run: pnpm install run: |
actual="$(pnpm --version)"
echo "pnpm version: ${actual}"
if [[ ! "${actual}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-.+)?$ ]]; then
echo "ERROR: pnpm --version did not produce valid output"
exit 1
fi
shell: bash
- name: 'Test: install in a fresh project'
run: |
mkdir /tmp/test-project
cd /tmp/test-project
pnpm init
pnpm add is-odd
shell: bash
test_dest: test_dest:
name: Test with dest name: Test with dest
@ -51,7 +66,7 @@ jobs:
- windows-latest - windows-latest
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Run the action - name: Run the action
uses: ./ uses: ./
@ -62,8 +77,15 @@ jobs:
- name: 'Test: which' - name: 'Test: which'
run: which pnpm && which pnpx run: which pnpm && which pnpx
- name: 'Test: install' - name: 'Test: version'
run: pnpm install run: |
actual="$(pnpm --version)"
echo "pnpm version: ${actual}"
if [[ ! "${actual}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-.+)?$ ]]; then
echo "ERROR: pnpm --version did not produce valid output"
exit 1
fi
shell: bash
test_standalone: test_standalone:
name: Test with standalone name: Test with standalone
@ -75,50 +97,87 @@ jobs:
matrix: matrix:
os: os:
- ubuntu-latest - ubuntu-latest
- macos-latest
- windows-latest - windows-latest
standalone:
- true
- false
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Run the action - name: Run the action
uses: ./ uses: ./
with: with:
version: 9.15.0 version: 9.15.0
standalone: ${{ matrix.standalone }} standalone: true
- name: install Node.js - name: 'Test: which'
uses: actions/setup-node@v4
with:
# pnpm@7.0.0 is not compatible with Node.js 12
node-version: 12.22.12
- name: 'Test: which (pnpm)'
run: which pnpm run: which pnpm
- name: 'Test: which (pnpx)' - name: 'Test: version'
if: matrix.standalone == false
run: which pnpx
- name: 'Test: install when standalone is true'
if: matrix.standalone
run: pnpm install
- name: 'Test: install when standalone is false'
if: matrix.standalone == false
# Since the default shell on windows runner is pwsh, we specify bash explicitly
shell: bash
run: | run: |
if pnpm install; then actual="$(pnpm --version)"
echo "pnpm install should fail" echo "pnpm version: ${actual}"
if [[ ! "${actual}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-.+)?$ ]]; then
echo "ERROR: pnpm --version did not produce valid output"
exit 1 exit 1
else
echo "pnpm install failed as expected"
fi fi
shell: bash
- name: 'Test: install in a fresh project'
run: |
mkdir /tmp/test-standalone
cd /tmp/test-standalone
pnpm init
pnpm add is-odd
shell: bash
test_dev_engines:
name: Test with devEngines.packageManager
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- macos-latest
- windows-latest
version:
- '9.15.5'
- '>=9.15.0'
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Set up package.json with devEngines.packageManager
run: echo '{"devEngines":{"packageManager":{"name":"pnpm","version":"${{ matrix.version }}","onFail":"download"}}}' > package.json
shell: bash
- name: Run the action
uses: ./
- name: 'Test: which'
run: which pnpm; which pnpx
- name: 'Test: version'
run: |
set -e
required='${{ matrix.version }}'
actual="$(pnpm --version)"
echo "pnpm version: ${actual}"
if [ "${required}" = ">=9.15.0" ]; then
min="9.15.0"
if [ "$(printf '%s\n' "${min}" "${actual}" | sort -V | head -n1)" != "${min}" ]; then
echo "Expected pnpm version >= ${min}, but got ${actual}"
exit 1
fi
else
if [ "${actual}" != "${required}" ]; then
echo "Expected pnpm version ${required}, but got ${actual}"
exit 1
fi
fi
shell: bash
test_run_install: test_run_install:
name: 'Test with run_install (${{ matrix.run_install.name }}, ${{ matrix.os }})' name: 'Test with run_install (${{ matrix.run_install.name }}, ${{ matrix.os }})'
@ -137,11 +196,6 @@ jobs:
run_install: run_install:
- name: 'null' - name: 'null'
value: 'null' value: 'null'
- name: 'empty object'
value: '{}'
- name: 'recursive'
value: |
recursive: true
- name: 'global' - name: 'global'
value: | value: |
args: args:
@ -149,18 +203,9 @@ jobs:
- --global-dir=./pnpm-global - --global-dir=./pnpm-global
- npm - npm
- yarn - yarn
- name: 'array'
value: |
- {}
- recursive: true
- args:
- --global
- --global-dir=./pnpm-global
- npm
- yarn
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1
- name: Run the action - name: Run the action
uses: ./ uses: ./
@ -171,5 +216,12 @@ jobs:
- name: 'Test: which' - name: 'Test: which'
run: which pnpm; which pnpx run: which pnpm; which pnpx
- name: 'Test: install' - name: 'Test: version'
run: pnpm install run: |
actual="$(pnpm --version)"
echo "pnpm version: ${actual}"
if [[ ! "${actual}" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-.+)?$ ]]; then
echo "ERROR: pnpm --version did not produce valid output"
exit 1
fi
shell: bash

2
.gitignore vendored
View File

@ -2,8 +2,6 @@ node_modules
*.log *.log
/dist/* /dist/*
!/dist/index.js !/dist/index.js
!/dist/pnpm.cjs
!/dist/worker.js
tmp tmp
temp temp
*.tmp *.tmp

View File

@ -42,6 +42,14 @@ If `run_install` is a YAML string representation of either an object or an array
**Optional** (_type:_ `string[]`) Additional arguments after `pnpm [recursive] install`, e.g. `[--ignore-scripts, --strict-peer-dependencies]`. **Optional** (_type:_ `string[]`) Additional arguments after `pnpm [recursive] install`, e.g. `[--ignore-scripts, --strict-peer-dependencies]`.
### `cache`
**Optional** (_type:_ `boolean`, _default:_ `false`) Whether to cache the pnpm store directory.
### `cache_dependency_path`
**Optional** (_type:_ `string|string[]`, _default:_ `pnpm-lock.yaml`) File path to the pnpm lockfile, which contents hash will be used as a cache key.
### `package_json_file` ### `package_json_file`
**Optional** (_type:_ `string`, _default:_ `package.json`) File path to the `package.json`/[`package.yaml`](https://github.com/pnpm/pnpm/pull/1799) to read "packageManager" configuration. **Optional** (_type:_ `string`, _default:_ `package.json`) File path to the `package.json`/[`package.yaml`](https://github.com/pnpm/pnpm/pull/1799) to read "packageManager" configuration.
@ -78,7 +86,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: pnpm/action-setup@v4 - uses: pnpm/action-setup@v5
with: with:
version: 10 version: 10
``` ```
@ -97,7 +105,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: pnpm/action-setup@v4 - uses: pnpm/action-setup@v5
``` ```
### Install pnpm and a few npm packages ### Install pnpm and a few npm packages
@ -114,10 +122,10 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: pnpm/action-setup@v4 - uses: pnpm/action-setup@v5
with: with:
version: 10 version: 10
run_install: run_install: |
- recursive: true - recursive: true
args: [--strict-peer-dependencies] args: [--strict-peer-dependencies]
- args: [--global, gulp, prettier, typescript] - args: [--global, gulp, prettier, typescript]
@ -138,17 +146,11 @@ jobs:
- name: Checkout - name: Checkout
uses: actions/checkout@v4 uses: actions/checkout@v4
- uses: pnpm/action-setup@v4 - uses: pnpm/action-setup@v5
name: Install pnpm name: Install pnpm
with: with:
version: 10 version: 10
run_install: false cache: true
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'
- name: Install dependencies - name: Install dependencies
run: pnpm install run: pnpm install

View File

@ -15,8 +15,16 @@ inputs:
description: If specified, run `pnpm install` description: If specified, run `pnpm install`
required: false required: false
default: 'null' default: 'null'
cache:
description: Whether to cache the pnpm store directory
required: false
default: 'false'
cache_dependency_path:
description: File path to the pnpm lockfile, which contents hash will be used as a cache key
required: false
default: 'pnpm-lock.yaml'
package_json_file: package_json_file:
description: File path to the package.json to read "packageManager" configuration description: File path to the package.json to read "packageManager" configuration. This path must be relative to the repository root (GITHUB_WORKSPACE).
required: false required: false
default: 'package.json' default: 'package.json'
standalone: standalone:
@ -29,6 +37,6 @@ outputs:
bin_dest: bin_dest:
description: Location of `pnpm` and `pnpx` command description: Location of `pnpm` and `pnpx` command
runs: runs:
using: node20 using: node24
main: dist/index.js main: dist/index.js
post: dist/index.js post: dist/index.js

BIN
dist/index.js vendored

Binary file not shown.

220780
dist/pnpm.cjs vendored

File diff suppressed because one or more lines are too long

16625
dist/worker.js vendored

File diff suppressed because it is too large Load Diff

View File

@ -1,23 +1,23 @@
{ {
"private": true, "private": true,
"scripts": { "scripts": {
"build:ncc": "ncc build --minify --no-source-map-register --no-cache dist/tsc/index.js --out dist/", "build:bundle": "esbuild src/index.ts --bundle --platform=node --target=node24 --format=cjs --minify --outfile=dist/index.js --loader:.json=json",
"build": "tsc && pnpm run build:ncc", "build": "pnpm run build:bundle",
"start": "pnpm run build && sh ./run.sh", "start": "pnpm run build && sh ./run.sh"
"update-pnpm-dist": "pnpm install && cp ./node_modules/pnpm/dist/pnpm.cjs ./dist/pnpm.cjs && cp ./node_modules/pnpm/dist/worker.js ./dist/worker.js"
}, },
"dependencies": { "dependencies": {
"@actions/cache": "^4.1.0",
"@actions/core": "^1.10.1", "@actions/core": "^1.10.1",
"@actions/exec": "^1.1.1",
"@actions/glob": "^0.5.0",
"@types/expand-tilde": "^2.0.2", "@types/expand-tilde": "^2.0.2",
"@types/node": "^20.11.5", "@types/node": "^22.0.0",
"@types/node-fetch": "^2.6.11",
"expand-tilde": "^2.0.2", "expand-tilde": "^2.0.2",
"yaml": "^2.3.4", "yaml": "^2.3.4",
"zod": "^3.22.4" "zod": "^3.22.4"
}, },
"devDependencies": { "devDependencies": {
"@vercel/ncc": "^0.38.1", "esbuild": "^0.27.4",
"pnpm": "^8.14.3",
"typescript": "^5.3.3" "typescript": "^5.3.3"
} }
} }

File diff suppressed because it is too large Load Diff

4
pnpm-workspace.yaml Normal file
View File

@ -0,0 +1,4 @@
packages:
- '.'
allowBuilds:
esbuild: true

View File

@ -0,0 +1,19 @@
import { isFeatureAvailable } from '@actions/cache'
import { endGroup, startGroup, warning } from '@actions/core'
import { Inputs } from '../inputs'
import { runRestoreCache } from './run'
export async function restoreCache(inputs: Inputs) {
if (!inputs.cache) return
if (!isFeatureAvailable()) {
warning('Cache is not available, skipping cache restoration')
return
}
startGroup('Restoring cache...')
await runRestoreCache(inputs)
endGroup()
}
export default restoreCache

39
src/cache-restore/run.ts Normal file
View File

@ -0,0 +1,39 @@
import { restoreCache } from '@actions/cache'
import { debug, info, saveState, setOutput } from '@actions/core'
import { getExecOutput } from '@actions/exec'
import { hashFiles } from '@actions/glob'
import os from 'os'
import { Inputs } from '../inputs'
export async function runRestoreCache(inputs: Inputs) {
const cachePath = await getCacheDirectory()
saveState('cache_path', cachePath)
const fileHash = await hashFiles(inputs.cacheDependencyPath)
if (!fileHash) {
throw new Error('Some specified paths were not resolved, unable to cache dependencies.')
}
const primaryKey = `pnpm-cache-${process.env.RUNNER_OS}-${os.arch()}-${fileHash}`
debug(`Primary key is ${primaryKey}`)
saveState('cache_primary_key', primaryKey)
let cacheKey = await restoreCache([cachePath], primaryKey)
setOutput('cache-hit', Boolean(cacheKey))
if (!cacheKey) {
info(`Cache is not found`)
return
}
saveState('cache_restored_key', cacheKey)
info(`Cache restored from key: ${cacheKey}`)
}
async function getCacheDirectory() {
const { stdout } = await getExecOutput('pnpm store path --silent')
const cacheFolderPath = stdout.trim()
debug(`Cache folder is set to "${cacheFolderPath}"`)
return cacheFolderPath
}

15
src/cache-save/index.ts Normal file
View File

@ -0,0 +1,15 @@
import { setFailed } from '@actions/core'
import { Inputs } from '../inputs'
import { runSaveCache } from './run'
export async function saveCache(inputs: Inputs) {
if (!inputs.cache) return
try {
await runSaveCache()
} catch (error) {
setFailed((error as Error).message)
}
}
export default saveCache

18
src/cache-save/run.ts Normal file
View File

@ -0,0 +1,18 @@
import { saveCache } from '@actions/cache'
import { getState, info } from '@actions/core'
export async function runSaveCache() {
const state = getState('cache_restored_key')
const primaryKey = getState('cache_primary_key')
const cachePath = getState('cache_path')
if (primaryKey === state) {
info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`)
return
}
const cacheId = await saveCache([cachePath], primaryKey)
if (cacheId == -1) return
info(`Cache saved with the key: ${primaryKey}`)
}

View File

@ -1,5 +1,7 @@
import { setFailed, saveState, getState } from '@actions/core' import { setFailed, saveState, getState } from '@actions/core'
import getInputs from './inputs' import restoreCache from './cache-restore'
import saveCache from './cache-save'
import getInputs, { Inputs } from './inputs'
import installPnpm from './install-pnpm' import installPnpm from './install-pnpm'
import setOutputs from './outputs' import setOutputs from './outputs'
import pnpmInstall from './pnpm-install' import pnpmInstall from './pnpm-install'
@ -7,15 +9,31 @@ import pruneStore from './pnpm-store-prune'
async function main() { async function main() {
const inputs = getInputs() const inputs = getInputs()
const isPost = getState('is_post')
if (isPost === 'true') return pruneStore(inputs) if (getState('is_post') === 'true') {
await runPost(inputs)
} else {
await runMain(inputs)
}
}
async function runMain(inputs: Inputs) {
saveState('is_post', 'true') saveState('is_post', 'true')
await installPnpm(inputs) await installPnpm(inputs)
console.log('Installation Completed!') console.log('Installation Completed!')
setOutputs(inputs) setOutputs(inputs)
await restoreCache(inputs)
pnpmInstall(inputs) pnpmInstall(inputs)
} }
async function runPost(inputs: Inputs) {
pruneStore(inputs)
await saveCache(inputs)
}
main().catch(error => { main().catch(error => {
console.error(error) console.error(error)
setFailed(error) setFailed(error)

View File

@ -5,6 +5,8 @@ import { RunInstall, parseRunInstall } from './run-install'
export interface Inputs { export interface Inputs {
readonly version?: string readonly version?: string
readonly dest: string readonly dest: string
readonly cache: boolean
readonly cacheDependencyPath: string
readonly runInstall: RunInstall[] readonly runInstall: RunInstall[]
readonly packageJsonFile: string readonly packageJsonFile: string
readonly standalone: boolean readonly standalone: boolean
@ -19,6 +21,8 @@ const parseInputPath = (name: string) => expandTilde(getInput(name, options))
export const getInputs = (): Inputs => ({ export const getInputs = (): Inputs => ({
version: getInput('version'), version: getInput('version'),
dest: parseInputPath('dest'), dest: parseInputPath('dest'),
cache: getBooleanInput('cache'),
cacheDependencyPath: parseInputPath('cache_dependency_path'),
runInstall: parseRunInstall('run_install'), runInstall: parseRunInstall('run_install'),
packageJsonFile: parseInputPath('package_json_file'), packageJsonFile: parseInputPath('package_json_file'),
standalone: getBooleanInput('standalone'), standalone: getBooleanInput('standalone'),

View File

@ -1,5 +1,5 @@
import { getInput, error } from '@actions/core' import { getInput, error } from '@actions/core'
import * as yaml from 'yaml' import { parse as parseYaml } from 'yaml'
import { z, ZodError } from 'zod' import { z, ZodError } from 'zod'
const RunInstallSchema = z.object({ const RunInstallSchema = z.object({
@ -20,7 +20,7 @@ export type RunInstall = z.infer<typeof RunInstallSchema>
export function parseRunInstall(inputName: string): RunInstall[] { export function parseRunInstall(inputName: string): RunInstall[] {
const input = getInput(inputName, { required: true }) const input = getInput(inputName, { required: true })
const parsedInput: unknown = yaml.parse(input) const parsedInput: unknown = parseYaml(input)
try { try {
const result: RunInstallInput = RunInstallInputSchema.parse(parsedInput) const result: RunInstallInput = RunInstallInputSchema.parse(parsedInput)

View File

@ -0,0 +1,282 @@
{
"name": "bootstrap-exe",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"@pnpm/exe": "11.0.0-beta.3"
}
},
"node_modules/@pnpm/exe": {
"version": "11.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@pnpm/exe/-/exe-11.0.0-beta.3.tgz",
"integrity": "sha512-yWNlHHdYmvf4c0MCkCzAa4csJDPdA+7yJCbXBUDXMbUu/0Zv/AxtO77q24MwlnBUC0dWeA+0F/pPmdkR9aTV2A==",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"@reflink/reflink": "0.1.19"
},
"bin": {
"pn": "pn",
"pnpm": "pnpm",
"pnpx": "pnpx",
"pnx": "pnx"
},
"funding": {
"url": "https://opencollective.com/pnpm"
},
"optionalDependencies": {
"@pnpm/linux-arm64": "11.0.0-beta.3",
"@pnpm/linux-x64": "11.0.0-beta.3",
"@pnpm/macos-arm64": "11.0.0-beta.3",
"@pnpm/macos-x64": "11.0.0-beta.3",
"@pnpm/win-arm64": "11.0.0-beta.3",
"@pnpm/win-x64": "11.0.0-beta.3"
}
},
"node_modules/@pnpm/linux-arm64": {
"version": "11.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@pnpm/linux-arm64/-/linux-arm64-11.0.0-beta.3.tgz",
"integrity": "sha512-TF2fyuCY9GggR4kfhjo1hMmgn+rIohenwNoH0tLPM7JlBK7/UAIFt1LI+o999tRwTCEw7gnxHFwtI2vyQuDfNw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/pnpm"
}
},
"node_modules/@pnpm/linux-x64": {
"version": "11.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@pnpm/linux-x64/-/linux-x64-11.0.0-beta.3.tgz",
"integrity": "sha512-7GrLsnSuDH62y486GUTwJdohGIC1ugz9ZJkbKOHgxIAkNGcSTJ1IkkdARtv7/WMmOEwwESDmtpOQ6LmjnpDMSA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"funding": {
"url": "https://opencollective.com/pnpm"
}
},
"node_modules/@pnpm/macos-arm64": {
"version": "11.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@pnpm/macos-arm64/-/macos-arm64-11.0.0-beta.3.tgz",
"integrity": "sha512-NQKgI1DURrEiOUzpxL0Mc+yn7DV4tpShqGnjaJLbz8ZCXsX/qhmybebvCG3r+IfSk3P5KID66lcgC/Osiaz0Dg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/pnpm"
}
},
"node_modules/@pnpm/macos-x64": {
"version": "11.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@pnpm/macos-x64/-/macos-x64-11.0.0-beta.3.tgz",
"integrity": "sha512-Ky22KFYHXx8+8WU4KJT9NXVgzFioL2w9pHTQjsqTK70AbxiErscPYhrFIehlCNbXjgs+tGVIy13QNKkiwvmS8w==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"funding": {
"url": "https://opencollective.com/pnpm"
}
},
"node_modules/@pnpm/win-arm64": {
"version": "11.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@pnpm/win-arm64/-/win-arm64-11.0.0-beta.3.tgz",
"integrity": "sha512-7L8TFNDm25m+XYSyhcola3YFd/li6BZzzl56SsyGnZabsvUslMwnDiJad48wOz8IuN7zsrTSGh+X/x6F+GdrFQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"funding": {
"url": "https://opencollective.com/pnpm"
}
},
"node_modules/@pnpm/win-x64": {
"version": "11.0.0-beta.3",
"resolved": "https://registry.npmjs.org/@pnpm/win-x64/-/win-x64-11.0.0-beta.3.tgz",
"integrity": "sha512-Z/6OpMUaIpggXjCtWEhp6kWjiT/2EImhkJAu8AodOORqeNcWouGEq3sO4XU0em6d+pAHmdV0hWMQ2xCUmPVuiA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"funding": {
"url": "https://opencollective.com/pnpm"
}
},
"node_modules/@reflink/reflink": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink/-/reflink-0.1.19.tgz",
"integrity": "sha512-DmCG8GzysnCZ15bres3N5AHCmwBwYgp0As6xjhQ47rAUTUXxJiK+lLUxaGsX3hd/30qUpVElh05PbGuxRPgJwA==",
"license": "MIT",
"engines": {
"node": ">= 10"
},
"optionalDependencies": {
"@reflink/reflink-darwin-arm64": "0.1.19",
"@reflink/reflink-darwin-x64": "0.1.19",
"@reflink/reflink-linux-arm64-gnu": "0.1.19",
"@reflink/reflink-linux-arm64-musl": "0.1.19",
"@reflink/reflink-linux-x64-gnu": "0.1.19",
"@reflink/reflink-linux-x64-musl": "0.1.19",
"@reflink/reflink-win32-arm64-msvc": "0.1.19",
"@reflink/reflink-win32-x64-msvc": "0.1.19"
}
},
"node_modules/@reflink/reflink-darwin-arm64": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink-darwin-arm64/-/reflink-darwin-arm64-0.1.19.tgz",
"integrity": "sha512-ruy44Lpepdk1FqDz38vExBY/PVUsjxZA+chd9wozjUH9JjuDT/HEaQYA6wYN9mf041l0yLVar6BCZuWABJvHSA==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@reflink/reflink-darwin-x64": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink-darwin-x64/-/reflink-darwin-x64-0.1.19.tgz",
"integrity": "sha512-By85MSWrMZa+c26TcnAy8SDk0sTUkYlNnwknSchkhHpGXOtjNDUOxJE9oByBnGbeuIE1PiQsxDG3Ud+IVV9yuA==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@reflink/reflink-linux-arm64-gnu": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink-linux-arm64-gnu/-/reflink-linux-arm64-gnu-0.1.19.tgz",
"integrity": "sha512-7P+er8+rP9iNeN+bfmccM4hTAaLP6PQJPKWSA4iSk2bNvo6KU6RyPgYeHxXmzNKzPVRcypZQTpFgstHam6maVg==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@reflink/reflink-linux-arm64-musl": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink-linux-arm64-musl/-/reflink-linux-arm64-musl-0.1.19.tgz",
"integrity": "sha512-37iO/Dp6m5DDaC2sf3zPtx/hl9FV3Xze4xoYidrxxS9bgP3S8ALroxRK6xBG/1TtfXKTvolvp+IjrUU6ujIGmA==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@reflink/reflink-linux-x64-gnu": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink-linux-x64-gnu/-/reflink-linux-x64-gnu-0.1.19.tgz",
"integrity": "sha512-jbI8jvuYCaA3MVUdu8vLoLAFqC+iNMpiSuLbxlAgg7x3K5bsS8nOpTRnkLF7vISJ+rVR8W+7ThXlXlUQ93ulkw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@reflink/reflink-linux-x64-musl": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink-linux-x64-musl/-/reflink-linux-x64-musl-0.1.19.tgz",
"integrity": "sha512-e9FBWDe+lv7QKAwtKOt6A2W/fyy/aEEfr0g6j/hWzvQcrzHCsz07BNQYlNOjTfeytrtLU7k449H1PI95jA4OjQ==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@reflink/reflink-win32-arm64-msvc": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink-win32-arm64-msvc/-/reflink-win32-arm64-msvc-0.1.19.tgz",
"integrity": "sha512-09PxnVIQcd+UOn4WAW73WU6PXL7DwGS6wPlkMhMg2zlHHG65F3vHepOw06HFCq+N42qkaNAc8AKIabWvtk6cIQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@reflink/reflink-win32-x64-msvc": {
"version": "0.1.19",
"resolved": "https://registry.npmjs.org/@reflink/reflink-win32-x64-msvc/-/reflink-win32-x64-msvc-0.1.19.tgz",
"integrity": "sha512-E//yT4ni2SyhwP8JRjVGWr3cbnhWDiPLgnQ66qqaanjjnMiu3O/2tjCPQXlcGc/DEYofpDc9fvhv6tALQsMV9w==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
}
}
}

View File

@ -0,0 +1,30 @@
{
"name": "bootstrap-pnpm",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"pnpm": "11.0.0-beta.3"
}
},
"node_modules/pnpm": {
"version": "11.0.0-beta.3",
"resolved": "https://registry.npmjs.org/pnpm/-/pnpm-11.0.0-beta.3.tgz",
"integrity": "sha512-6PrfRjycZV4vRX6ttG9oR6pOgbI2/OcF2QLOzHm35UcRuvtqP4zf3wQfAAPwEbeu1uAbpSg/Q5cL8h32tumy6Q==",
"license": "MIT",
"bin": {
"pn": "bin/pnpm.mjs",
"pnpm": "bin/pnpm.mjs",
"pnpx": "bin/pnpx.mjs",
"pnx": "bin/pnpx.mjs"
},
"engines": {
"node": ">=22.13"
},
"funding": {
"url": "https://opencollective.com/pnpm"
}
}
}
}

View File

@ -1,71 +1,101 @@
import { addPath, exportVariable } from '@actions/core' import { addPath, exportVariable } from '@actions/core'
import { spawn } from 'child_process' import { spawn } from 'child_process'
import { rm, writeFile, mkdir, copyFile } from 'fs/promises' import { rm, writeFile, mkdir, symlink } from 'fs/promises'
import { readFileSync } from 'fs' import { readFileSync, existsSync } from 'fs'
import path from 'path' import path from 'path'
import { execPath } from 'process'
import util from 'util' import util from 'util'
import { Inputs } from '../inputs' import { Inputs } from '../inputs'
import YAML from 'yaml' import { parse as parseYaml } from 'yaml'
import pnpmLock from './bootstrap/pnpm-lock.json'
import exeLock from './bootstrap/exe-lock.json'
const BOOTSTRAP_PNPM_PACKAGE_JSON = JSON.stringify({ private: true, dependencies: { pnpm: pnpmLock.packages['node_modules/pnpm'].version } })
const BOOTSTRAP_EXE_PACKAGE_JSON = JSON.stringify({ private: true, dependencies: { '@pnpm/exe': exeLock.packages['node_modules/@pnpm/exe'].version } })
export async function runSelfInstaller(inputs: Inputs): Promise<number> { export async function runSelfInstaller(inputs: Inputs): Promise<number> {
const { version, dest, packageJsonFile, standalone } = inputs const { version, dest, packageJsonFile } = inputs
const { GITHUB_WORKSPACE } = process.env
// prepare self install // pnpm v11 requires Node >= 22.13; use standalone (exe) bootstrap which
// bundles its own Node.js when the system Node is too old
const systemNode = await getSystemNodeVersion()
const standalone = inputs.standalone || systemNode.major < 22 || (systemNode.major === 22 && systemNode.minor < 13)
// Install bootstrap pnpm via npm (integrity verified by committed lockfile)
await rm(dest, { recursive: true, force: true }) await rm(dest, { recursive: true, force: true })
// create dest directory after removal
await mkdir(dest, { recursive: true }) await mkdir(dest, { recursive: true })
const pkgJson = path.join(dest, 'package.json')
// we have ensured the dest directory exists, we can write the file directly
await writeFile(pkgJson, JSON.stringify({ private: true }))
// copy .npmrc if it exists to install from custom registry const lockfile = standalone ? exeLock : pnpmLock
if (GITHUB_WORKSPACE) { const packageJson = standalone ? BOOTSTRAP_EXE_PACKAGE_JSON : BOOTSTRAP_PNPM_PACKAGE_JSON
try { await writeFile(path.join(dest, 'package.json'), packageJson)
await copyFile(path.join(GITHUB_WORKSPACE, '.npmrc'), path.join(dest, '.npmrc')) await writeFile(path.join(dest, 'package-lock.json'), JSON.stringify(lockfile))
} catch (error) {
// Swallow error if .npmrc doesn't exist const npmExitCode = await runCommand('npm', ['ci'], { cwd: dest })
if (!util.types.isNativeError(error) || !('code' in error) || error.code !== 'ENOENT') throw error if (npmExitCode !== 0) {
} return npmExitCode
} }
// prepare target pnpm // On Windows with standalone mode, npm's .bin shims can't properly
const target = await readTarget({ version, packageJsonFile, standalone }) // execute the extensionless @pnpm/exe native binaries. Add the
const cp = spawn(execPath, [path.join(__dirname, 'pnpm.cjs'), 'install', target, '--no-lockfile'], { // @pnpm/exe directory directly to PATH so pnpm.exe is found natively.
cwd: dest, const pnpmHome = standalone && process.platform === 'win32'
stdio: ['pipe', 'inherit', 'inherit'], ? path.join(dest, 'node_modules', '@pnpm', 'exe')
}) : path.join(dest, 'node_modules', '.bin')
// pnpm expects PNPM_HOME/bin in PATH for global binaries (e.g. node
const exitCode = await new Promise<number>((resolve, reject) => { // installed via `pnpm runtime`). Add it first so the next addPath
cp.on('error', reject) // (pnpmHome itself, which contains pnpm.exe) has higher precedence.
cp.on('close', resolve) addPath(path.join(pnpmHome, 'bin'))
})
if (exitCode === 0) {
const pnpmHome = path.join(dest, 'node_modules/.bin')
addPath(pnpmHome) addPath(pnpmHome)
exportVariable('PNPM_HOME', pnpmHome) exportVariable('PNPM_HOME', pnpmHome)
// Ensure pnpm bin link exists — npm ci sometimes doesn't create it
if (process.platform !== 'win32') {
const pnpmBinLink = path.join(dest, 'node_modules', '.bin', 'pnpm')
if (!existsSync(pnpmBinLink)) {
await mkdir(path.join(dest, 'node_modules', '.bin'), { recursive: true })
const target = standalone
? path.join('..', '@pnpm', 'exe', 'pnpm')
: path.join('..', 'pnpm', 'bin', 'pnpm.mjs')
await symlink(target, pnpmBinLink)
} }
}
const bootstrapPnpm = standalone
? path.join(dest, 'node_modules', '@pnpm', 'exe', process.platform === 'win32' ? 'pnpm.exe' : 'pnpm')
: path.join(dest, 'node_modules', 'pnpm', 'bin', 'pnpm.mjs')
// Determine the target version
const targetVersion = readTargetVersion({ version, packageJsonFile })
if (targetVersion) {
const cmd = standalone ? bootstrapPnpm : process.execPath
const args = standalone ? ['self-update', targetVersion] : [bootstrapPnpm, 'self-update', targetVersion]
const exitCode = await runCommand(cmd, args, { cwd: dest })
if (exitCode !== 0) {
return exitCode return exitCode
} }
}
async function readTarget(opts: { return 0
}
function readTargetVersion(opts: {
readonly version?: string | undefined readonly version?: string | undefined
readonly packageJsonFile: string readonly packageJsonFile: string
readonly standalone: boolean }): string | undefined {
}) { const { version, packageJsonFile } = opts
const { version, packageJsonFile, standalone } = opts
const { GITHUB_WORKSPACE } = process.env const { GITHUB_WORKSPACE } = process.env
let packageManager let packageManager: string | undefined
let devEngines: { packageManager?: { name?: string; version?: string } } | undefined
if (GITHUB_WORKSPACE) { if (GITHUB_WORKSPACE) {
try { try {
const content = readFileSync(path.join(GITHUB_WORKSPACE, packageJsonFile), 'utf8'); const content = readFileSync(path.join(GITHUB_WORKSPACE, packageJsonFile), 'utf8');
({ packageManager } = packageJsonFile.endsWith(".yaml") const manifest = packageJsonFile.endsWith(".yaml")
? YAML.parse(content, { merge: true }) ? parseYaml(content, { merge: true })
: JSON.parse(content) : JSON.parse(content)
) packageManager = manifest.packageManager
devEngines = manifest.devEngines
} catch (error: unknown) { } catch (error: unknown) {
// Swallow error if package.json doesn't exist in root // Swallow error if package.json doesn't exist in root
if (!util.types.isNativeError(error) || !('code' in error) || error.code !== 'ENOENT') throw error if (!util.types.isNativeError(error) || !('code' in error) || error.code !== 'ENOENT') throw error
@ -84,7 +114,16 @@ async function readTarget(opts: {
Remove one of these versions to avoid version mismatch errors like ERR_PNPM_BAD_PM_VERSION`) Remove one of these versions to avoid version mismatch errors like ERR_PNPM_BAD_PM_VERSION`)
} }
return `${ standalone ? '@pnpm/exe' : 'pnpm' }@${version}` return version
}
// pnpm will automatically download and switch to the right version
if (typeof packageManager === 'string' && packageManager.startsWith('pnpm@')) {
return undefined
}
if (devEngines?.packageManager?.name === 'pnpm' && devEngines.packageManager.version) {
return undefined
} }
if (!GITHUB_WORKSPACE) { if (!GITHUB_WORKSPACE) {
@ -94,22 +133,36 @@ please run the actions/checkout before pnpm/action-setup.
Otherwise, please specify the pnpm version in the action configuration.`) Otherwise, please specify the pnpm version in the action configuration.`)
} }
if (typeof packageManager !== 'string') {
throw new Error(`No pnpm version is specified. throw new Error(`No pnpm version is specified.
Please specify it by one of the following ways: Please specify it by one of the following ways:
- in the GitHub Action config with the key "version" - in the GitHub Action config with the key "version"
- in the package.json with the key "packageManager"`) - in the package.json with the key "packageManager"
- in the package.json with the key "devEngines.packageManager"`)
} }
if (!packageManager.startsWith('pnpm@')) { function getSystemNodeVersion(): Promise<{ major: number; minor: number }> {
throw new Error('Invalid packageManager field in package.json') return new Promise((resolve) => {
const cp = spawn('node', ['--version'], { stdio: ['pipe', 'pipe', 'pipe'], shell: process.platform === 'win32' })
let output = ''
cp.stdout.on('data', (data: Buffer) => { output += data.toString() })
cp.on('close', () => {
const match = output.match(/^v(\d+)\.(\d+)/)
resolve(match ? { major: parseInt(match[1], 10), minor: parseInt(match[2], 10) } : { major: 0, minor: 0 })
})
cp.on('error', () => resolve({ major: 0, minor: 0 }))
})
} }
if (standalone) { function runCommand(cmd: string, args: string[], opts: { cwd: string }): Promise<number> {
return packageManager.replace('pnpm@', '@pnpm/exe@') return new Promise<number>((resolve, reject) => {
} const cp = spawn(cmd, args, {
cwd: opts.cwd,
return packageManager stdio: ['pipe', 'inherit', 'inherit'],
shell: process.platform === 'win32',
})
cp.on('error', reject)
cp.on('close', resolve)
})
} }
export default runSelfInstaller export default runSelfInstaller

View File

@ -1,10 +1,11 @@
import { setOutput, addPath } from '@actions/core' import { setOutput } from '@actions/core'
import { Inputs } from '../inputs' import { Inputs } from '../inputs'
import { getBinDest } from '../utils' import { getBinDest } from '../utils'
export function setOutputs(inputs: Inputs) { export function setOutputs(inputs: Inputs) {
const binDest = getBinDest(inputs) const binDest = getBinDest(inputs)
addPath(binDest) // NOTE: addPath is already called in installPnpm — do not call it again
// here, as a second addPath would shadow the correct entry on Windows.
setOutput('dest', inputs.dest) setOutput('dest', inputs.dest)
setOutput('bin_dest', binDest) setOutput('bin_dest', binDest)
} }

View File

@ -6,5 +6,5 @@ export const getBinDest = (inputs: Inputs): string => path.join(inputs.dest, 'no
export const patchPnpmEnv = (inputs: Inputs): NodeJS.ProcessEnv => ({ export const patchPnpmEnv = (inputs: Inputs): NodeJS.ProcessEnv => ({
...process.env, ...process.env,
PATH: getBinDest(inputs) + path.delimiter + process.env.PATH, PATH: path.join(getBinDest(inputs), 'bin') + path.delimiter + getBinDest(inputs) + path.delimiter + process.env.PATH,
}) })

View File

@ -1,26 +1,19 @@
{ {
"compilerOptions": { "compilerOptions": {
"target": "ES2022", "target": "ES2022",
"module": "Node16", "module": "ESNext",
"moduleResolution": "bundler",
"resolveJsonModule": true, "resolveJsonModule": true,
"lib": [ "lib": [
"ES2023" "ES2023"
], ],
"outDir": "./dist/tsc", "noEmit": true,
"preserveConstEnums": true,
"incremental": false,
"declaration": true,
"sourceMap": true,
"importHelpers": false,
"strict": true, "strict": true,
"pretty": true, "pretty": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true, "noUnusedParameters": true,
"noImplicitReturns": true, "noImplicitReturns": true,
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"esModuleInterop": true, "esModuleInterop": true
"experimentalDecorators": true,
"emitDecoratorMetadata": true
} }
} }