feat: using env variables in setting names and values (#9319)

This commit is contained in:
Zoltan Kochan
2025-03-23 12:57:09 +01:00
committed by GitHub
parent 3a90ec1f8f
commit 5b35dff19d
3 changed files with 38 additions and 2 deletions

View File

@@ -0,0 +1,6 @@
---
"@pnpm/config": minor
"pnpm": minor
---
It should be possible to use env variables in `pnpm-workspace.yaml` setting names and value.

View File

@@ -1,4 +1,5 @@
import path from 'path'
import { envReplace } from '@pnpm/config.env-replace'
import { PnpmError } from '@pnpm/error'
import {
type SupportedArchitectures,
@@ -61,7 +62,7 @@ export function getOptionsFromRootManifest (manifestDir: string, manifest: Proje
export function getOptionsFromPnpmSettings (manifestDir: string, pnpmSettings: PnpmSettings, manifest?: ProjectManifest): OptionsFromRootManifest {
const renamedKeys = ['allowNonAppliedPatches'] as const satisfies Array<keyof PnpmSettings>
const settings: OptionsFromRootManifest = omit(renamedKeys, pnpmSettings)
const settings: OptionsFromRootManifest = omit(renamedKeys, replaceEnvInSettings(pnpmSettings))
if (settings.overrides) {
if (Object.keys(settings.overrides).length === 0) {
delete settings.overrides
@@ -89,6 +90,20 @@ export function getOptionsFromPnpmSettings (manifestDir: string, pnpmSettings: P
return settings
}
function replaceEnvInSettings (settings: PnpmSettings): PnpmSettings {
const newSettings: PnpmSettings = {}
for (const [key, value] of Object.entries(settings)) {
const newKey = envReplace(key, process.env)
if (typeof value === 'string') {
// @ts-expect-error
newSettings[newKey as keyof PnpmSettings] = envReplace(value, process.env)
} else {
newSettings[newKey as keyof PnpmSettings] = value
}
}
return newSettings
}
function createVersionReferencesReplacer (manifest: ProjectManifest): (spec: string) => string {
const allDeps = {
...manifest.devDependencies,

View File

@@ -1,5 +1,11 @@
import path from 'path'
import { getOptionsFromRootManifest } from '../lib/getOptionsFromRootManifest'
import { getOptionsFromRootManifest, getOptionsFromPnpmSettings } from '../lib/getOptionsFromRootManifest'
const ORIGINAL_ENV = process.env
afterEach(() => {
process.env = { ...ORIGINAL_ENV }
})
test('getOptionsFromRootManifest() should read "resolutions" field for compatibility with Yarn', () => {
const options = getOptionsFromRootManifest(process.cwd(), {
@@ -159,3 +165,12 @@ test('getOptionsFromRootManifest() should return patchedDependencies', () => {
})
expect(options.patchedDependencies).toStrictEqual({ foo: path.resolve('foo.patch') })
})
test('getOptionsFromPnpmSettings() replaces env variables in settings', () => {
process.env.PNPM_TEST_KEY = 'foo'
process.env.PNPM_TEST_VALUE = 'bar'
const options = getOptionsFromPnpmSettings(process.cwd(), {
'${PNPM_TEST_KEY}': '${PNPM_TEST_VALUE}', // eslint-disable-line
} as any) as any // eslint-disable-line
expect(options.foo).toEqual('bar')
})