57 lines
1.9 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 13:37:35 +08:00
const target = await readTarget(pkgJson, 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
}
2022-02-22 13:37:35 +08:00
async function readTarget(packageJsonPath: string, version?: string | undefined) {
if (version) return `pnpm@${version}`
const { packageManager } = JSON.parse(await readFile(packageJsonPath, 'utf8'))
if (typeof packageManager !== 'string') {
throw new Error(`No pnpm version is specified.
Please specify it by one of the following way:
- in the GitHub Action config with the key "version"
- in the package.json with the key "packageManager" (See https://nodejs.org/api/corepack.html)`)
}
if (!packageManager.startsWith('pnpm@')) {
throw new Error('Invalid packageManager field in package.json')
}
return packageManager
}
2020-05-08 11:29:39 +07:00
export default runSelfInstaller