Compare commits

..

5 Commits

Author SHA1 Message Date
khai96_
271a9df5fb Try different ways 2020-05-09 20:57:00 +07:00
khai96_
3b5e8836ec Update dist/index.js 2020-05-09 20:52:54 +07:00
khai96_
0fa2b7d3a5 Use console.log 2020-05-09 20:52:27 +07:00
khai96_
c3e0d9f20f Update dist/index.js 2020-05-09 20:50:21 +07:00
khai96_
d2316507fd Inspect isPost 2020-05-09 20:47:42 +07:00
32 changed files with 1000 additions and 238756 deletions

14
.github/FUNDING.yml vendored
View File

@@ -1,2 +1,12 @@
custom:
- https://opencollective.com/pnpm
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: khai96_
open_collective: # Collective unavailable
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # disabled
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

View File

@@ -1,7 +0,0 @@
version: 2
updates:
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: weekly
open-pull-requests-limit: 10

View File

@@ -3,7 +3,6 @@ name: Test Action
on:
- push
- pull_request
- workflow_dispatch
jobs:
test_default_inputs:
@@ -15,19 +14,19 @@ jobs:
fail-fast: false
matrix:
pnpm:
- 9.15.5
- 4.11.1
os:
- ubuntu-latest
- macos-latest
- windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- name: Run the action
uses: ./
with:
version: 9.15.5
version: 4.11.1
- name: 'Test: which'
run: which pnpm; which pnpx
@@ -35,8 +34,8 @@ jobs:
- name: 'Test: install'
run: pnpm install
test_dest:
name: Test with dest
test_explicit_inputs:
name: Test with explicit inputs
runs-on: ${{ matrix.os }}
@@ -44,132 +43,25 @@ jobs:
fail-fast: false
matrix:
pnpm:
- 9.15.5
- 4.11.1
os:
- ubuntu-latest
- macos-latest
- windows-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- name: Run the action
uses: ./
with:
version: 9.15.5
version: 4.11.1
dest: ~/test/pnpm
bin_dest: ~/test/pnpm/.bin
registry: http://registry.yarnpkg.com/
- name: 'Test: which'
run: which pnpm && which pnpx
- name: 'Test: install'
run: pnpm install
test_standalone:
name: Test with standalone
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
- macos-latest
- windows-latest
standalone:
- true
- false
steps:
- uses: actions/checkout@v4
- name: Run the action
uses: ./
with:
version: 9.15.0
standalone: ${{ matrix.standalone }}
- name: install Node.js
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
- name: 'Test: which (pnpx)'
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: |
if pnpm install; then
echo "pnpm install should fail"
exit 1
else
echo "pnpm install failed as expected"
fi
test_run_install:
name: 'Test with run_install (${{ matrix.run_install.name }}, ${{ matrix.os }})'
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
pnpm:
- 9.15.5
os:
- ubuntu-latest
- macos-latest
- windows-latest
run_install:
- name: 'null'
value: 'null'
- name: 'empty object'
value: '{}'
- name: 'recursive'
value: |
recursive: true
- name: 'global'
value: |
args:
- --global
- --global-dir=./pnpm-global
- npm
- yarn
- name: 'array'
value: |
- {}
- recursive: true
- args:
- --global
- --global-dir=./pnpm-global
- npm
- yarn
steps:
- uses: actions/checkout@v4
- name: Run the action
uses: ./
with:
version: 9.15.5
run_install: ${{ matrix.run_install.value }}
- name: 'Test: which'
run: which pnpm; which pnpx
- name: 'Test: install'
run: pnpm install

3
.gitignore vendored
View File

@@ -2,12 +2,9 @@ node_modules
*.log
/dist/*
!/dist/index.js
!/dist/pnpm.cjs
!/dist/worker.js
tmp
temp
*.tmp
*.temp
tmp.*
temp.*
.pnpm-store

141
README.md
View File

@@ -1,64 +1,28 @@
> ## :warning: Upgrade from v2!
>
> The v2 version of this action [has stopped working](https://github.com/pnpm/action-setup/issues/135) with newer Node.js versions. Please, upgrade to the latest version to fix any issues.
# Setup PNPM
# Setup pnpm
Install pnpm package manager.
Install PNPM package manager.
## Inputs
### `version`
Version of pnpm to install.
**Optional** when there is a [`packageManager` field in the `package.json`](https://nodejs.org/api/corepack.html).
otherwise, this field is **required** It supports npm versioning scheme, it could be an exact version (such as `6.24.1`), or a version range (such as `6`, `6.x.x`, `6.24.x`, `^6.24.1`, `*`, etc.), or `latest`.
**Required** Version of PNPM to install.
### `dest`
**Optional** Where to store pnpm files.
**Optional** Where to store PNPM files.
### `bin_dest`
**Optional** Where to store executables (`pnpm` and `pnpx` commands).
### `registry`
**Optional** Registry to download PNPM from.
### `run_install`
**Optional** (_default:_ `null`) If specified, run `pnpm install`.
If `run_install` is either `null` or `false`, pnpm will not install any npm package.
If `run_install` is `true`, pnpm will install dependencies recursively.
If `run_install` is a YAML string representation of either an object or an array, pnpm will execute every install commands.
#### `run_install.recursive`
**Optional** (_type:_ `boolean`, _default:_ `false`) Whether to use `pnpm recursive install`.
#### `run_install.cwd`
**Optional** (_type:_ `string`) Working directory when run `pnpm [recursive] install`.
#### `run_install.args`
**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`
**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.
### `standalone`
**Optional** (_type:_ `boolean`, _default:_ `false`) When set to true, [@pnpm/exe](https://www.npmjs.com/package/@pnpm/exe), which is a Node.js bundled package, will be installed, enabling using `pnpm` without Node.js.
This is useful when you want to use a incompatible pair of Node.js and pnpm.
**Optional** If specified, run `pnpm install`.
## Outputs
@@ -68,100 +32,33 @@ Expanded path of inputs#dest.
### `bin_dest`
Location of `pnpm` and `pnpx` command.
Expanded path of inputs#bin_dest.
## Usage example
### Install only pnpm without `packageManager`
This works when the repo either doesn't have a `package.json` or has a `package.json` but it doesn't specify `packageManager`.
```yaml
on:
- push
- pull_request
jobs:
install:
runs-on: ubuntu-latest
steps:
- uses: pnpm/action-setup@v4
- uses: actions/checkout@v2
- uses: pnpm/action-setup@v1.1.0
with:
version: 10
```
### Install only pnpm with `packageManager`
Omit `version` input to use the version in the [`packageManager` field in the `package.json`](https://nodejs.org/api/corepack.html).
```yaml
on:
- push
- pull_request
jobs:
install:
runs-on: ubuntu-latest
steps:
- uses: pnpm/action-setup@v4
```
### Install pnpm and a few npm packages
```yaml
on:
- push
- pull_request
jobs:
install:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
with:
version: 10
run_install: |
- recursive: true
args: [--strict-peer-dependencies]
- args: [--global, gulp, prettier, typescript]
```
### Use cache to reduce installation time
```yaml
on:
- push
- pull_request
jobs:
cache-and-install:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
name: Install pnpm
with:
version: 10
cache: true
version: 4.11.1
- name: Install dependencies
run: pnpm install
```
**Note:** You don't need to run `pnpm store prune` at the end; post-action has already taken care of that.
## Notes
This action does not setup Node.js for you, use [actions/setup-node](https://github.com/actions/setup-node) yourself.
## License
[MIT](https://github.com/pnpm/action-setup/blob/master/LICENSE.md) © [Hoàng Văn Khải](https://github.com/KSXGitHub/)
[MIT](https://git.io/JfclH) © [Hoàng Văn Khải](https://github.com/KSXGitHub/)

View File

@@ -1,42 +1,29 @@
name: Setup pnpm
description: Install pnpm package manager
name: Setup PNPM
description: Install PNPM package manager
branding:
icon: package
color: orange
inputs:
version:
description: Version of pnpm to install
required: false
description: Version of PNPM to install
required: true
dest:
description: Where to store pnpm files
description: Where to store PNPM files
required: false
default: ~/setup-pnpm
bin_dest:
description: Where to store executables (pnpm and pnpx commands)
required: false
default: ~/setup-pnpm/.bin
registry:
description: Registry to download PNPM from
required: false
default: https://registry.npmjs.com
run_install:
description: If specified, run `pnpm install`
required: false
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:
description: File path to the package.json to read "packageManager" configuration. This path must be relative to the repository root (GITHUB_WORKSPACE).
required: false
default: 'package.json'
standalone:
description: When set to true, @pnpm/exe, which is a Node.js bundled package, will be installed, enabling using pnpm without Node.js.
required: false
default: 'false'
outputs:
dest:
description: Expanded path of inputs#dest
bin_dest:
description: Location of `pnpm` and `pnpx` command
runs:
using: node20
using: node12
main: dist/index.js
post: dist/index.js

11
dist/index.js vendored

File diff suppressed because one or more lines are too long

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,25 +1,25 @@
{
"private": true,
"scripts": {
"build:schemas": "ts-schema-autogen generate",
"build:ncc": "ncc build --minify --no-source-map-register --no-cache dist/tsc/index.js --out dist/",
"build": "tsc && pnpm run build:ncc",
"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"
"build": "pnpm run build:schemas && tsc && pnpm run build:ncc",
"start": "pnpm run build && sh ./run.sh"
},
"dependencies": {
"@actions/cache": "^4.1.0",
"@actions/core": "^1.10.1",
"@actions/exec": "^1.1.1",
"@actions/glob": "^0.5.0",
"@types/expand-tilde": "^2.0.2",
"@types/node": "^20.11.5",
"node-fetch": "^2.6.0",
"expand-tilde": "^2.0.2",
"yaml": "^2.3.4",
"zod": "^3.22.4"
"js-yaml": "^3.13.1",
"ajv": "^6.12.0",
"@actions/core": "^1.2.4",
"@types/expand-tilde": "^2.0.0",
"@types/node-fetch": "^2.5.7",
"@types/js-yaml": "^3.12.3",
"@types/node": "^13.13.5"
},
"devDependencies": {
"@vercel/ncc": "^0.38.1",
"pnpm": "^8.14.3",
"typescript": "^5.3.3"
"typescript": "^3.8.3",
"@ts-schema-autogen/cli": "^0.1.2",
"@zeit/ncc": "^0.22.1"
}
}

1473
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,10 +1,6 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"pinVersions": false,
"extends": [
"config:base"
],
"ignoreDeps": [
"ajv"
]
}

3
run.sh
View File

@@ -3,6 +3,7 @@
export HOME="$(pwd)"
export INPUT_VERSION=4.11.1
export INPUT_DEST='~/pnpm.temp'
export INPUT_BIN_DEST='~/pnpm.temp/.bin'
export INPUT_REGISTRY=https://registry.npmjs.com
export INPUT_RUN_INSTALL=null
export INPUT_standalone=false
exec node dist/index.js

View File

@@ -1,19 +0,0 @@
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

View File

@@ -1,39 +0,0 @@
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
}

View File

@@ -1,15 +0,0 @@
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

View File

@@ -1,18 +0,0 @@
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,39 +1,26 @@
import { setFailed, saveState, getState } from '@actions/core'
import restoreCache from './cache-restore'
import saveCache from './cache-save'
import getInputs, { Inputs } from './inputs'
import installPnpm from './install-pnpm'
import { setFailed, getState } from '@actions/core'
import getInputs from './inputs'
import setOutputs from './outputs'
import installPnpm from './install-pnpm'
import pnpmInstall from './pnpm-install'
import pruneStore from './pnpm-store-prune'
async function main() {
const isPost = getState('isPost')
console.log({
is_post: getState('is_post'),
isPost: getState('isPost'),
STATE_isPost: process.env['STATE_isPost'],
})
if (isPost) {
return
}
const inputs = getInputs()
if (getState('is_post') === 'true') {
await runPost(inputs)
} else {
await runMain(inputs)
}
}
async function runMain(inputs: Inputs) {
saveState('is_post', 'true')
await installPnpm(inputs)
console.log('Installation Completed!')
setOutputs(inputs)
await restoreCache(inputs)
pnpmInstall(inputs)
}
async function runPost(inputs: Inputs) {
pruneStore(inputs)
await saveCache(inputs)
}
main().catch(error => {
console.error(error)
setFailed(error)

View File

@@ -1,15 +1,13 @@
import { getBooleanInput, getInput, InputOptions } from '@actions/core'
import { getInput, InputOptions } from '@actions/core'
import expandTilde from 'expand-tilde'
import { RunInstall, parseRunInstall } from './run-install'
export interface Inputs {
readonly version?: string
readonly version: string
readonly dest: string
readonly cache: boolean
readonly cacheDependencyPath: string
readonly binDest: string
readonly registry: string
readonly runInstall: RunInstall[]
readonly packageJsonFile: string
readonly standalone: boolean
}
const options: InputOptions = {
@@ -19,13 +17,11 @@ const options: InputOptions = {
const parseInputPath = (name: string) => expandTilde(getInput(name, options))
export const getInputs = (): Inputs => ({
version: getInput('version'),
version: getInput('version', options),
dest: parseInputPath('dest'),
cache: getBooleanInput('cache'),
cacheDependencyPath: parseInputPath('cache_dependency_path'),
binDest: parseInputPath('bin_dest'),
registry: getInput('registry', options),
runInstall: parseRunInstall('run_install'),
packageJsonFile: parseInputPath('package_json_file'),
standalone: getBooleanInput('standalone'),
})
export default getInputs

View File

@@ -0,0 +1,21 @@
{
"$schema": "https://raw.githubusercontent.com/ksxnodeapps/ts-schema-autogen/master/packages/schemas/config.schema.json",
"instruction": {
"compilerOptions": {
"strict": true,
"target": "ES2018",
"lib": [
"ES2018",
"ES2019",
"ES2020",
"ESNext"
],
"moduleResolution": "Node",
"esModuleInterop": true,
"resolveJsonModule": true
},
"input": "run-install.ts",
"symbol": "RunInstallInput",
"output": "run-install-input.schema.json"
}
}

View File

@@ -0,0 +1,39 @@
{
"anyOf": [
{
"$ref": "#/definitions/RunInstall"
},
{
"type": "array",
"items": {
"$ref": "#/definitions/RunInstall"
}
},
{
"type": [
"null",
"boolean"
]
}
],
"definitions": {
"RunInstall": {
"type": "object",
"properties": {
"recursive": {
"type": "boolean"
},
"cwd": {
"type": "string"
},
"args": {
"type": "array",
"items": {
"type": "string"
}
}
}
}
},
"$schema": "http://json-schema.org/draft-07/schema#"
}

View File

@@ -1,41 +1,40 @@
import { getInput, error } from '@actions/core'
import { parse as parseYaml } from 'yaml'
import { z, ZodError } from 'zod'
import process from 'process'
import { safeLoad } from 'js-yaml'
import Ajv from 'ajv'
import { getInput, error, InputOptions } from '@actions/core'
import runInstallSchema from './run-install-input.schema.json'
const RunInstallSchema = z.object({
recursive: z.boolean().optional(),
cwd: z.string().optional(),
args: z.array(z.string()).optional(),
export interface RunInstall {
readonly recursive?: boolean
readonly cwd?: string
readonly args?: readonly string[]
}
export type RunInstallInput =
| null
| boolean
| RunInstall
| RunInstall[]
const options: InputOptions = {
required: true,
}
export function parseRunInstall(name: string): RunInstall[] {
const result: RunInstallInput = safeLoad(getInput(name, options))
const ajv = new Ajv({
allErrors: true,
async: false,
})
const RunInstallInputSchema = z.union([
z.null(),
z.boolean(),
RunInstallSchema,
z.array(RunInstallSchema),
])
export type RunInstallInput = z.infer<typeof RunInstallInputSchema>
export type RunInstall = z.infer<typeof RunInstallSchema>
export function parseRunInstall(inputName: string): RunInstall[] {
const input = getInput(inputName, { required: true })
const parsedInput: unknown = parseYaml(input)
try {
const result: RunInstallInput = RunInstallInputSchema.parse(parsedInput)
const validate = ajv.compile(runInstallSchema)
if (!validate(result)) {
for (const errorItem of validate.errors!) {
error(`with.run_install${errorItem.dataPath}: ${errorItem.message}`)
}
return process.exit(1)
}
if (!result) return []
if (result === true) return [{ recursive: true }]
if (Array.isArray(result)) return result
return [result]
} catch (exception: unknown) {
error(`Error for input "${inputName}" = ${input}`)
if (exception instanceof ZodError) {
error(`Errors: ${exception.errors}`)
} else {
error(`Exception: ${exception}`)
}
process.exit(1)
}
}

View File

@@ -1,15 +1,13 @@
import { setFailed, startGroup, endGroup } from '@actions/core'
import { setFailed } from '@actions/core'
import { Inputs } from '../inputs'
import runSelfInstaller from './run'
export { runSelfInstaller }
export async function install(inputs: Inputs) {
startGroup('Running self-installer...')
const status = await runSelfInstaller(inputs)
endGroup()
if (status) {
return setFailed(`Something went wrong, self-installer exits with code ${status}`)
return setFailed(`Something does wrong, self-installer exits with code ${status}`)
}
}

View File

@@ -1,115 +1,26 @@
import { addPath, exportVariable } from '@actions/core'
import { spawn } from 'child_process'
import { rm, writeFile, mkdir, copyFile } from 'fs/promises'
import { readFileSync } from 'fs'
import path from 'path'
import { execPath } from 'process'
import util from 'util'
import { downloadSelfInstaller } from '../self-installer'
import { Inputs } from '../inputs'
import { parse as parseYaml } from 'yaml'
export async function runSelfInstaller(inputs: Inputs): Promise<number> {
const { version, dest, packageJsonFile, standalone } = inputs
const { GITHUB_WORKSPACE } = process.env
// prepare self install
await rm(dest, { recursive: true, force: true })
// create dest directory after removal
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
if (GITHUB_WORKSPACE) {
try {
await copyFile(path.join(GITHUB_WORKSPACE, '.npmrc'), path.join(dest, '.npmrc'))
} catch (error) {
// Swallow error if .npmrc doesn't exist
if (!util.types.isNativeError(error) || !('code' in error) || error.code !== 'ENOENT') throw error
}
}
// prepare target pnpm
const target = await readTarget({ version, packageJsonFile, standalone })
const cp = spawn(execPath, [path.join(__dirname, 'pnpm.cjs'), 'install', target, '--no-lockfile'], {
cwd: dest,
const cp = spawn(execPath, {
env: {
PNPM_VERSION: inputs.version,
PNPM_DEST: inputs.dest,
PNPM_BIN_DEST: inputs.binDest,
PNPM_REGISTRY: inputs.registry,
},
stdio: ['pipe', 'inherit', 'inherit'],
})
const exitCode = await new Promise<number>((resolve, reject) => {
const response = await downloadSelfInstaller()
response.body.pipe(cp.stdin)
return new Promise((resolve, reject) => {
cp.on('error', reject)
cp.on('close', resolve)
})
if (exitCode === 0) {
const pnpmHome = path.join(dest, 'node_modules/.bin')
addPath(pnpmHome)
exportVariable('PNPM_HOME', pnpmHome)
}
return exitCode
}
async function readTarget(opts: {
readonly version?: string | undefined
readonly packageJsonFile: string
readonly standalone: boolean
}) {
const { version, packageJsonFile, standalone } = opts
const { GITHUB_WORKSPACE } = process.env
let packageManager
if (GITHUB_WORKSPACE) {
try {
const content = readFileSync(path.join(GITHUB_WORKSPACE, packageJsonFile), 'utf8');
({ packageManager } = packageJsonFile.endsWith(".yaml")
? parseYaml(content, { merge: true })
: JSON.parse(content)
)
} catch (error: unknown) {
// Swallow error if package.json doesn't exist in root
if (!util.types.isNativeError(error) || !('code' in error) || error.code !== 'ENOENT') throw error
}
}
if (version) {
if (
typeof packageManager === 'string' &&
packageManager.startsWith('pnpm@') &&
packageManager.replace('pnpm@', '') !== version
) {
throw new Error(`Multiple versions of pnpm specified:
- version ${version} in the GitHub Action config with the key "version"
- version ${packageManager} in the package.json with the key "packageManager"
Remove one of these versions to avoid version mismatch errors like ERR_PNPM_BAD_PM_VERSION`)
}
return `${ standalone ? '@pnpm/exe' : 'pnpm' }@${version}`
}
if (!GITHUB_WORKSPACE) {
throw new Error(`No workspace is found.
If you've intended to let pnpm/action-setup read preferred pnpm version from the "packageManager" field in the package.json file,
please run the actions/checkout before pnpm/action-setup.
Otherwise, please specify the pnpm version in the action configuration.`)
}
if (typeof packageManager !== 'string') {
throw new Error(`No pnpm version is specified.
Please specify it by one of the following ways:
- in the GitHub Action config with the key "version"
- in the package.json with the key "packageManager"`)
}
if (!packageManager.startsWith('pnpm@')) {
throw new Error('Invalid packageManager field in package.json')
}
if (standalone) {
return packageManager.replace('pnpm@', '@pnpm/exe@')
}
return packageManager
}
export default runSelfInstaller

View File

@@ -1,12 +1,10 @@
import { setOutput, addPath } from '@actions/core'
import { Inputs } from '../inputs'
import { getBinDest } from '../utils'
export function setOutputs(inputs: Inputs) {
const binDest = getBinDest(inputs)
addPath(binDest)
addPath(inputs.binDest)
setOutput('dest', inputs.dest)
setOutput('bin_dest', binDest)
setOutput('bin_dest', inputs.binDest)
}
export default setOutputs

View File

@@ -1,10 +1,14 @@
import { setFailed, startGroup, endGroup } from '@actions/core'
import process from 'process'
import path from 'path'
import { spawnSync } from 'child_process'
import { setFailed } from '@actions/core'
import { Inputs } from '../inputs'
import { patchPnpmEnv } from '../utils'
export function runPnpmInstall(inputs: Inputs) {
const env = patchPnpmEnv(inputs)
const env = {
...process.env,
PATH: inputs.binDest + path.delimiter + process.env.PATH
}
for (const options of inputs.runInstall) {
const args = ['install']
@@ -12,7 +16,7 @@ export function runPnpmInstall(inputs: Inputs) {
if (options.args) args.push(...options.args)
const cmdStr = ['pnpm', ...args].join(' ')
startGroup(`Running ${cmdStr}...`)
console.log('Running', cmdStr)
const { error, status } = spawnSync('pnpm', args, {
stdio: 'inherit',
@@ -21,8 +25,6 @@ export function runPnpmInstall(inputs: Inputs) {
env,
})
endGroup()
if (error) {
setFailed(error)
continue

View File

@@ -1,31 +0,0 @@
import { warning, startGroup, endGroup } from '@actions/core'
import { spawnSync } from 'child_process'
import { Inputs } from '../inputs'
import { patchPnpmEnv } from '../utils'
export function pruneStore(inputs: Inputs) {
if (inputs.runInstall.length === 0) {
console.log('Pruning is unnecessary.')
return
}
startGroup('Running pnpm store prune...')
const { error, status } = spawnSync('pnpm', ['store', 'prune'], {
stdio: 'inherit',
shell: true,
env: patchPnpmEnv(inputs),
})
endGroup()
if (error) {
warning(error)
return
}
if (status) {
warning(`command pnpm store prune exits with code ${status}`)
return
}
}
export default pruneStore

View File

@@ -0,0 +1,4 @@
import fetch from 'node-fetch'
import url from './url'
export const downloadSelfInstaller = () => fetch(url)
export default downloadSelfInstaller

View File

@@ -0,0 +1,2 @@
export * from './url'
export * from './download'

View File

@@ -0,0 +1,3 @@
export const ref = '301414cec74a2b6b63c95b42f2ad1790ccb980ed'
export const url = `https://raw.githubusercontent.com/pnpm/self-installer/${ref}/install.js`
export default url

View File

@@ -1,10 +0,0 @@
import path from 'path'
import process from 'process'
import { Inputs } from '../inputs'
export const getBinDest = (inputs: Inputs): string => path.join(inputs.dest, 'node_modules', '.bin')
export const patchPnpmEnv = (inputs: Inputs): NodeJS.ProcessEnv => ({
...process.env,
PATH: getBinDest(inputs) + path.delimiter + process.env.PATH,
})

View File

@@ -1,11 +1,15 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"target": "ES2018",
"module": "CommonJS",
"moduleResolution": "Node",
"resolveJsonModule": true,
"lib": [
"ES2023"
"ES2018",
"ES2019",
"ES2020",
"ESNext"
],
"outDir": "./dist/tsc",
"preserveConstEnums": true,