Skip to content

🩹 [Patch]: Prevent ArgumentCompleters from falling back to the default file path completion #514

@MariusStorhaug

Description

@MariusStorhaug

Describe the change

In order to prevent argument completions from falling back to the default of file path completion, we should ensure that all completers have a null value return if there is nothing to return. Like this:

function Test-Function {
    param (
        [string]$param1,
        [int]$param2
    )

    Write-Host "Parameter 1: $param1"
    Write-Host "Parameter 2: $param2"

    return $true
}

Register-ArgumentCompleter -CommandName Test-Function -ParameterName param1 -ScriptBlock {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters)

    $options = <Some function to get options>
    $filteredOptions = $options | Where-Object { $_ -like "$wordToComplete*" }
    if (-not $filteredOptions) {
        return $null
    }
    $filteredOptions | ForEach-Object {
        [System.Management.Automation.CompletionResult]::new($_.Option, $_.Option, 'ParameterValue', $_.Option)
    }
}

The argument completers would in this case not start cycling through folder and file paths in the shells current folder.

Before:

Test-Function -param1 <tab> # Assume the function that gets options returns no options
Test-Function -param1 /readme.md # The file is not actually a valid parameter, so its an invalid completion.

Instead i want this:

Test-Function -param1 <tab> # Again, assume the function that gets options returns no options
Test-Function -param1 | # The pipe (|) being where the cursor is, which is correct if there are no valid completions, no file path or anything, just nothing.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions