Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions config/env-replace/env-replace.docs.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,23 @@ import { envReplace } from '@pnpm/config.env-replace'

envReplace('${foo}', process.env)
```

## `stripEnvFallback`

```ts
function stripEnvFallback(settingValue: string): string;
```

Strips fallback values from environment variable placeholders, leaving only the variable name.

Usage:

```ts
import { stripEnvFallback } from '@pnpm/config.env-replace'

stripEnvFallback('${HOME-/default}/config')
// Returns: '${HOME}/config'

stripEnvFallback('${FOO:-fallback}')
// Returns: '${FOO}'
```
14 changes: 13 additions & 1 deletion config/env-replace/env-replace.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { envReplace } from './env-replace';
import { envReplace, stripEnvFallback } from './env-replace';

const ENV = {
foo: 'foo_value',
Expand All @@ -25,3 +25,15 @@ test('fail when the env variable is not found', () => {
expect(() => envReplace('${foo:-}', ENV)).toThrow(`Failed to replace env in config: \${foo:-}`);
})

test.each([
['-${foo}-${bar}', '-${foo}-${bar}'],
['-${foo-fallback-value}-${bar:-fallback-value}', '-${foo}-${bar}'],
['-${qar-fallback-value}-${zoo:-fallback-for-empty-value}', '-${qar}-${zoo}'],
['\\${foo}', '${foo}'],
['\\\\${foo}', '\\${foo}'],
['${foo}', '${foo}'],
])('stripEnvFallback %s => %s', (settingValue, expected) => {
const actual = stripEnvFallback(settingValue);
expect(actual).toEqual(expected);
})

19 changes: 19 additions & 0 deletions config/env-replace/env-replace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,22 @@ function getEnvValue (env: NodeJS.ProcessEnv, name: string): string | undefined
}
return fallback
}

export function stripEnvFallback (settingValue: string): string {
return settingValue.replace(ENV_EXPR, replaceEnvMatchForStrip)
}

function replaceEnvMatchForStrip (orig: string, escape: string, name: string): string {
if (escape.length % 2) {
return orig.slice((escape.length + 1) / 2)
}
const strippedName = getStrippedEnvName(name)
return `${escape.slice(escape.length / 2)}\${${strippedName}}`
}

function getStrippedEnvName (name: string): string {
const matched = name.match(ENV_VALUE)
if (!matched) return name
const [, variableName] = matched
return variableName
}
2 changes: 1 addition & 1 deletion config/env-replace/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export { envReplace } from './env-replace';
export { envReplace, stripEnvFallback } from './env-replace';
Loading