action-setup/src/install-pnpm/run.ts

54 lines
1.6 KiB
TypeScript
Raw Normal View History

2022-02-08 14:44:50 +02:00
import { addPath, exportVariable } from '@actions/core'
2020-05-08 13:06:16 +07:00
import { spawn } from 'child_process'
2020-05-08 13:47:46 +07:00
import { execPath } from 'process'
2022-02-08 14:44:50 +02:00
import path from 'path'
2022-02-22 12:26:05 +08:00
import { remove, ensureFile, writeFile, readFile } from 'fs-extra'
import fetch from '@pnpm/fetch'
2020-05-08 11:29:39 +07:00
import { Inputs } from '../inputs'
2020-05-08 21:34:25 +07:00
export async function runSelfInstaller(inputs: Inputs): Promise<number> {
2021-03-23 12:42:43 +07:00
const { version, dest } = inputs
2022-02-08 14:44:50 +02:00
const pkgJson = path.join(dest, 'package.json')
2022-02-22 12:26:05 +08:00
let target: string
if (!version) {
const packageManager = JSON.parse(await readFile(pkgJson, 'utf8')).packageManager
if (packageManager) {
if (!packageManager.startsWith('pnpm@')) {
throw new Error('packageManager field is not pnpm')
}
target = packageManager
} else {
throw new Error('None of packageManager (in package.json) or version (in action config) is defined')
}
} else {
target = `pnpm@${version}`
}
2021-03-23 12:42:43 +07:00
await remove(dest)
await ensureFile(pkgJson)
await writeFile(pkgJson, JSON.stringify({ private: true }))
const cp = spawn(execPath, ['-', 'install', target, '--no-lockfile'], {
2021-03-23 12:48:54 +07:00
cwd: dest,
2020-05-08 13:06:16 +07:00
stdio: ['pipe', 'inherit', 'inherit'],
})
const response = await fetch('https://get.pnpm.io/v6.16.js')
if (!response.body) throw new Error('Did not receive response body')
2020-05-08 21:34:25 +07:00
response.body.pipe(cp.stdin)
2020-05-08 13:06:16 +07:00
const exitCode = await new Promise<number>((resolve, reject) => {
2020-05-08 13:06:16 +07:00
cp.on('error', reject)
cp.on('close', resolve)
2020-05-08 11:29:39 +07:00
})
if (exitCode === 0) {
2022-02-08 14:44:50 +02:00
const pnpmHome = path.join(dest, 'node_modules/.bin')
addPath(pnpmHome)
exportVariable('PNPM_HOME', pnpmHome)
}
return exitCode
2020-05-08 11:29:39 +07:00
}
export default runSelfInstaller