-
Notifications
You must be signed in to change notification settings - Fork 8.1k
Open
Labels
Issue-Enhancementthe issue is more of a feature request than a bugthe issue is more of a feature request than a bugNeeds-TriageThe issue is new and needs to be triaged by a work group.The issue is new and needs to be triaged by a work group.WG-Enginecore PowerShell engine, interpreter, and runtimecore PowerShell engine, interpreter, and runtime
Description
Summary of the new feature / enhancement
Motivation
Sometimes I'd like to use same source for both validation attributes and function implementation.
However pwsh doesn't allow to share them as a variable.
For example, to have a function with both tab completion and interactive completion, you have to hard-code the same candidate source twice
(I know this is not a good example but demonstrates the idea)
function foo {
param(
[ValidateSet('foo', 'bar')] # candidates written for the first time
$foo
)
if (-not $foo) {
# hard-coded candidates again
$foo = 'foo', 'bar' | fzf --prompt 'pick one'
}
}So allowing attributes to access a shared storage is needed in such case, and such storage should be readonly.
Proposed technical implementation details (optional)
Solution Proposal
The solution I can think of is to add a new named block readonly, variables declared in readonly block are immutable.
Such variables should be initialized on the first invocation of the function, and should be available for attributes/scriptblock in attributes.
function foo {
param(
[ValidateSet($candidates)] # attributes are aware of readonly variables
[ValidateScript({ $_ -in $candidates })] # or access in scriptblock
[ArgumentCompleter({ & $completer })]
$foo
)
readonly {
$candidates = 'foo', 'bar'
$completer = {
# ...complex logic for parsing completion for native executables
# that you don't want to repeat in every ArgumentCompleter
}
}
begin {
if (-not $foo) {
$foo = $candidates | fzf --prompt 'pick one'
}
}
end {
$candidates = $null # ERROR: can't mutate readonly variables
$candidates[0] = 'baz' # ERROR: can't mutate readonly variables
}
}Potential Problem
- if access the readonly variable within scriptblock for attributes like
ValidateScript, the error messages would be confusing for users:
The " $_ -in $candidates " validation script for the argument with value "baz" did not return a result of True. Determine why the validation script failed, and then try the command again.
- whether to prioritize readonly variables in attribute scriptblock to avoid ambiguity(should we add a
$readonly:scope?)
Metadata
Metadata
Assignees
Labels
Issue-Enhancementthe issue is more of a feature request than a bugthe issue is more of a feature request than a bugNeeds-TriageThe issue is new and needs to be triaged by a work group.The issue is new and needs to be triaged by a work group.WG-Enginecore PowerShell engine, interpreter, and runtimecore PowerShell engine, interpreter, and runtime