Repository navigation
Add @generatePwshEnv PowerShell code generator #1314
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jsskeen-utah
wants to merge
2
commits into
dmno-dev:main
Choose a base branch
from
jsskeen-utah:joe/codegen-pwsh
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| varlock: minor | ||
| --- | ||
|
|
||
| Added @generatePwshEnv to generate a typed PowerShell module that loads the injected env blob. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
packages/varlock-website/src/content/docs/integrations/powershell.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| --- | ||
| title: PowerShell | ||
| description: Use varlock with PowerShell via a generated, typed loader function | ||
| --- | ||
|
|
||
| To use varlock with PowerShell, [install the standalone binary](/getting-started/installation/#as-a-standalone-binary) and run your script under [`varlock run`](/reference/cli/load-and-run/#run). It loads and validates your env, then injects it into the process. | ||
|
|
||
| Add [`@generatePwshEnv`](/reference/root-decorators/#generatepwshenv) to your schema to generate a self-contained `.ps1` file: a loader function that parses the injected [`__VARLOCK_ENV`](/reference/reserved-variables/#__varlock_env) blob and returns a typed object, plus a function that lists the sensitive keys. The object is an instance of a small C# class that the file compiles with `Add-Type`. | ||
|
|
||
| ```env-spec title=".env.schema" | ||
| # @generatePwshEnv(path=./Env.ps1) | ||
| ``` | ||
|
|
||
| The file is regenerated automatically on [`varlock load`](/reference/cli/load-and-run/#load) and [`varlock run`](/reference/cli/load-and-run/#run), or explicitly with [`varlock codegen`](/reference/cli/cache-and-codegen/#codegen). Requires **PowerShell 7.4+** (.NET 8; the loader uses `System.Security.Cryptography.AesGcm` and the C# compiler that ships with PowerShell 7.4). Optional `functionName=` sets the loader function name (default: `Get-Env`). It must be a Verb-Noun name, such as `Get-AppEnv`. Property names are PascalCase (`DB_HOST` becomes `DbHost`). | ||
|
|
||
| ## Reading values | ||
|
|
||
| Dot-source the generated file, then call the loader function. The file uses `$PSScriptRoot` in your script to find it, so the path works from any directory: | ||
|
|
||
| ```powershell title="run.ps1" | ||
| . "$PSScriptRoot/Env.ps1" | ||
|
|
||
| $e = Get-Env | ||
| Write-Output "$($e.DbHost):$($e.DbPort)" | ||
| ``` | ||
|
|
||
| ```bash | ||
| varlock run -- pwsh ./run.ps1 | ||
| ``` | ||
|
|
||
| Each property holds the value with the type the schema declares: integers, decimals, and booleans are converted, and optional values that are unset come back as `$null`. Objects, arrays, and records come back as `JsonElement`, so read them with its methods (for example `(Get-Env).Cfg.GetProperty('a').GetInt64()`). The object is a snapshot taken when you call `Get-Env`, so call it again to read values after the environment changes. The first load in a session compiles the class, which takes a moment (about half a second in testing). Later loads of the same schema reuse it. To read a single value, select its property: | ||
|
|
||
| ```powershell | ||
| $dbHost = (Get-Env).DbHost | ||
| Get-Env | Select-Object DbPort | ||
| ``` | ||
|
|
||
| `Get-Env` takes no parameters. Read a value from the object's property, or pipe the object to `Select-Object`. | ||
|
|
||
| The loader throws a clear error if `__VARLOCK_ENV` is missing (for example, if you forgot `varlock run`) or if a required key is absent. | ||
|
|
||
| :::note[Editor completion] | ||
| In the VS Code editor, completion for the generated functions (for example `Get-Env` and its properties) may not appear in a script until the file is dot-sourced in the integrated terminal. The editor doesn't pick up functions from a dot-source that uses `$PSScriptRoot`, which keeps the path portable. Once the file is loaded in the terminal, completion works. This was observed with PowerShell extension 2025.4.0. | ||
| ::: | ||
|
|
||
| ## Sensitive keys | ||
|
|
||
| The generated file also defines `<functionName>SensitiveKeys`, which returns the names of the sensitive items. Use it to build your own redaction or leak-scanning: | ||
|
|
||
| ```powershell | ||
| Get-EnvSensitiveKeys | ||
| ``` | ||
|
|
||
| :::note | ||
| Every key is also injected as a plain environment variable, so you can read any of them with `$env:NAME` (raw strings) if you don't need the typed loader. Keys whose names aren't valid identifiers (they contain `.` or `-`) can't be properties, so read those from the env var directly. See [Other languages](/integrations/other-languages/) for the shared details on the injected blob, raw env vars, and encryption. | ||
| ::: | ||
|
|
||
| ## Help | ||
|
|
||
| `Get-Help Get-Env` lists each property with its type and schema description. `-Examples` shows usage examples, and `-Full` adds the output type and the notes. | ||
|
|
||
| ## Encrypted blobs | ||
|
|
||
| If [`@encryptInjectedEnv`](/reference/root-decorators/#encryptinjectedenv) is set, use `varlock run --inject blob` so the encrypted blob reaches your script. The loader decrypts it with the key in `_VARLOCK_ENV_KEY`, which `varlock run` provides in that mode. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
188 changes: 188 additions & 0 deletions
188
packages/varlock/src/env-graph/lib/type-generation/emitters/pwsh.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| import { createHash } from 'node:crypto'; | ||
|
|
||
| import { getAutogeneratedBanner } from '../banners'; | ||
| import { | ||
| getFieldDocLines, | ||
| getSensitiveKeys, | ||
| type ResolvedFieldType, | ||
| } from '../shared'; | ||
| import { generateCsharpEnvSrc, snakeToPascalCase } from './csharp'; | ||
|
|
||
| /** `Verb-Noun` function name, e.g. `Get-AppEnv` */ | ||
| const PWSH_FUNCTION_NAME = /^[A-Za-z][A-Za-z0-9]*-[A-Za-z][A-Za-z0-9]*$/; | ||
|
|
||
| const PWSH_DOCS_URL = 'https://varlock.dev/integrations/powershell/'; | ||
|
|
||
| /** Single-quoted PowerShell literal. Doubles the quote characters PowerShell accepts as quotes. */ | ||
| function pwshStringLiteral(text: string): string { | ||
| return `'${text.replace(/['\u2018\u2019\u201A\u201B]/g, (ch) => ch + ch)}'`; | ||
| } | ||
|
|
||
| /** | ||
| * The PowerShell name for a generated C# property type. Read from the generated source, so the help | ||
| * can't disagree with the class. `string?` and `object?` are shown without the `?`, as the reference | ||
| * types they are. | ||
| */ | ||
| function psTypeName(csharpType: string): string { | ||
| const nullable = csharpType.endsWith('?'); | ||
| const base = nullable ? csharpType.slice(0, -1) : csharpType; | ||
| if (base === 'string' || base === 'object') return base; | ||
| const names: Record<string, string> = { | ||
| long: 'long', double: 'double', bool: 'bool', JsonElement: 'JsonElement', | ||
| }; | ||
| const name = names[base] ?? base; | ||
| return nullable ? `${name}?` : name; | ||
| } | ||
|
|
||
| /** Each property's C# type, keyed by property name, read from the `{ get; init; }` declarations. */ | ||
| function csharpPropertyTypes(csharpSrc: string): Map<string, string> { | ||
| const types = new Map<string, string>(); | ||
| for (const match of csharpSrc.matchAll(/^\s*public (?:required )?(\S+) ([A-Za-z_][A-Za-z0-9_]*) \{ get; init; \}\s*$/gm)) { | ||
| types.set(match[2], match[1]); | ||
| } | ||
| return types; | ||
| } | ||
|
|
||
|
|
||
| /** | ||
| * Comment-based help for the generated function, with a section per help tier: | ||
| * SYNOPSIS and DESCRIPTION (default), EXAMPLE (-Examples), and INPUTS, OUTPUTS, NOTES, and LINK (-Full). | ||
| * `#>` in generated text is neutralized so it can't end the comment block early. | ||
| */ | ||
| function helpLines( | ||
| functionName: string, | ||
| typeFullName: string, | ||
| properties: Array<{ field: ResolvedFieldType, prop: string, type: string }>, | ||
| ): Array<string> { | ||
| const safeLine = (line: string) => line.replace(/#>/g, '# >'); | ||
| const nameWidth = Math.max(0, ...properties.map(({ prop }) => prop.length)); | ||
| const typeWidth = Math.max(0, ...properties.map(({ type }) => type.length)); | ||
| const propertyLines = properties.map(({ field, prop, type }) => { | ||
| const docs = getFieldDocLines(field).join(' '); | ||
| const sensitive = field.isSensitive ? ' (sensitive)' : ''; | ||
| return safeLine(` ${prop.padEnd(nameWidth)} ${type.padEnd(typeWidth)} ${docs}${sensitive}`.trimEnd()); | ||
| }); | ||
| const [first, second] = properties; | ||
|
|
||
| const examples: Array<string> = [ | ||
| '.EXAMPLE', | ||
| `${functionName}`, | ||
| '', | ||
| 'Returns the whole object, with one property per schema item.', | ||
| '', | ||
| ]; | ||
| if (first) { | ||
| examples.push( | ||
| '.EXAMPLE', | ||
| `(${functionName}).${first.prop}`, | ||
| '', | ||
| 'Reads a single value. The result has the type shown under Properties.', | ||
| '', | ||
| ); | ||
| } | ||
| if (first && second) { | ||
| examples.push( | ||
| '.EXAMPLE', | ||
| `${functionName} | Select-Object ${first.prop}, ${second.prop}`, | ||
| '', | ||
| 'Selects several values from the object.', | ||
| '', | ||
| ); | ||
| } | ||
| examples.push( | ||
| '.EXAMPLE', | ||
| `try { ${functionName} } catch { Write-Error $_.Exception.Message }`, | ||
| '', | ||
| 'Handles a missing __VARLOCK_ENV or a missing required key without stopping the script.', | ||
| '', | ||
| ); | ||
|
|
||
| return [ | ||
| '<#', | ||
| '.SYNOPSIS', | ||
| 'Load the varlock __VARLOCK_ENV blob into a typed object.', | ||
| '', | ||
| '.DESCRIPTION', | ||
| 'Reads the __VARLOCK_ENV environment variable set by `varlock run`, decrypts it if it is a varlock:v1 blob using _VARLOCK_ENV_KEY, and returns the typed object for this project.', | ||
| '', | ||
| 'The object is a snapshot of the values at load time. Each property holds the value with the type shown below, and an optional item that is unset is $null. Composite values are JsonElement. Read a value from its property, or pipe the object to Select-Object. Call the command again to read values after the environment changes.', | ||
| '', | ||
| 'If __VARLOCK_ENV is missing (the script wasn\'t started with varlock run), or a required key is absent, the command throws.', | ||
| '', | ||
| ...(properties.length ? ['Properties:', ...propertyLines, ''] : []), | ||
| ...examples, | ||
| '.INPUTS', | ||
| 'None. This command takes no pipeline input.', | ||
| '', | ||
| '.OUTPUTS', | ||
| typeFullName, | ||
| 'An object with one property for each schema item (see Properties).', | ||
| '', | ||
| '.NOTES', | ||
| 'Requires PowerShell 7.4+ (.NET 8). The typed class is compiled with Add-Type the first time the file is loaded in a session.', | ||
| 'This file is generated by varlock. Regenerate it with varlock codegen instead of editing it by hand.', | ||
| '', | ||
| '.LINK', | ||
| PWSH_DOCS_URL, | ||
| '#>', | ||
| ].map((line, i, all) => (i === 0 || i === all.length - 1 ? line : safeLine(line))); | ||
| } | ||
|
|
||
| export function generatePwshEnvSrc( | ||
| fields: Array<ResolvedFieldType>, | ||
| opts?: { functionName?: unknown }, | ||
| ): string { | ||
| const functionName = opts?.functionName === undefined ? 'Get-Env' : String(opts.functionName); | ||
| if (!PWSH_FUNCTION_NAME.test(functionName)) { | ||
| throw new Error(`@generatePwshEnv - \`function\` must be a Verb-Noun PowerShell function name (got ${JSON.stringify(opts?.functionName)})`); | ||
| } | ||
|
|
||
| // the namespace hashes the generated C#, so a changed schema compiles to a new type | ||
| const probe = generateCsharpEnvSrc(fields, { namespace: 'Varlock.Pwsh', className: 'Env' }); | ||
| const typeId = createHash('sha256').update(probe).digest('hex').slice(0, 12); | ||
| const namespace = `Varlock.Pwsh_${typeId}`; | ||
| const fullName = `${namespace}.Env`; | ||
| const csharpSrc = generateCsharpEnvSrc(fields, { namespace, className: 'Env' }); | ||
|
|
||
| // the properties are the ones the C# class declares, so the help matches the object | ||
| const csharpTypes = csharpPropertyTypes(csharpSrc); | ||
| const properties = fields | ||
| .map((field) => ({ field, prop: snakeToPascalCase(field.key) })) | ||
| .filter(({ prop }) => csharpTypes.has(prop)) | ||
| .map(({ field, prop }) => ({ field, prop, type: psTypeName(csharpTypes.get(prop) ?? 'object') })); | ||
| const sensitiveList = getSensitiveKeys(fields).map(pwshStringLiteral).join(', '); | ||
|
|
||
| const src = [ | ||
| getAutogeneratedBanner('#'), | ||
| '# Requires PowerShell 7.4+ (.NET 8). The C# source uses System.Text.Json and AesGcm, compiled with Add-Type.', | ||
| '', | ||
| 'if ($PSVersionTable.PSVersion -lt [version]\'7.4\') {', | ||
| ' throw \'varlock: this generated module requires PowerShell 7.4 or later\'', | ||
| '}', | ||
| '', | ||
| `if (-not (${pwshStringLiteral(fullName)} -as [type])) {`, | ||
| // `#nullable enable` is needed for the `string?` members, and the define selects the | ||
| // AesGcm constructor that takes a tag size (the other one is obsolete on .NET 8) | ||
| ' Add-Type -CompilerOptions \'/define:NET8_0_OR_GREATER\' -TypeDefinition @\'', | ||
| '#nullable enable', | ||
| ...csharpSrc.split('\n'), | ||
| '\'@', | ||
| '}', | ||
| '', | ||
| `function ${functionName}SensitiveKeys {`, | ||
| ` @(${sensitiveList})`, | ||
| '}', | ||
| '', | ||
| ...helpLines(functionName, fullName, properties), | ||
| `function ${functionName} {`, | ||
| ' [CmdletBinding()]', | ||
| ` [OutputType(${pwshStringLiteral(fullName)})]`, | ||
| ' param()', | ||
| '', | ||
| ` [${fullName}]::Load()`, | ||
| '}', | ||
| '', | ||
| ]; | ||
|
|
||
| return src.join('\n'); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.