completers/mktemp_completer/mktemp_completer.ps1

# mktemp tab completion for PowerShell
# Static option completion for mktemp.exe and mktemp.

Set-StrictMode -Version 2.0

function Get-MktempCompletionOptions {
    $cache = Get-Variable -Name 'MktempCompletionOptions' -Scope Script -ErrorAction Ignore
    if ($null -ne $cache -and $null -ne $cache.Value) {
        return $cache.Value
    }

    $fallbackOptions = @('-d', '--directory', '-u', '--dry-run', '-q', '--quiet', '--suffix', '-p', '--tmpdir', '-t', '-h', '--help', '-V', '--version')
    $commandCandidates = @('mktemp.exe', 'mktemp')
    foreach ($candidate in $commandCandidates) {
        $command = Get-Command -Name $candidate -ErrorAction Ignore
        if ($null -eq $command) {
            continue
        }

        try {
            $helpOutput = $null | & $command.Source --help 2>&1 | ForEach-Object { $_ -replace '\e\[[0-9;?]*[ -/]*[@-~]', '' } | Out-String
        } catch {
            continue
        }

        if ([string]::IsNullOrWhiteSpace($helpOutput)) {
            continue
        }

        $options = [System.Collections.Generic.HashSet[string]]::new([System.StringComparer]::Ordinal)
        $descriptions = [System.Collections.Hashtable]::new([System.StringComparer]::Ordinal)
        foreach ($line in ([regex]::Split($helpOutput, '\r?\n'))) {
            foreach ($match in [regex]::Matches($line, '(?<!\S)(--?[A-Za-z0-9][A-Za-z0-9-]*)(?=(\s|,|=|\[|$))')) {
                $rawOption = $match.Groups[1].Value
                $normalized = $rawOption.Trim()
                if ($normalized.StartsWith('--')) {
                    $normalized = $normalized -replace '\[.*$', ''
                    $normalized = $normalized -replace '=.*$', ''
                }
                if ($normalized -match '^-{1,2}[A-Za-z0-9][A-Za-z0-9-]*$') {
                    [void]$options.Add($normalized)
                if (-not $descriptions.ContainsKey($normalized)) {
                    $description = ($line -replace '^\s*(?:-{1,2}[A-Za-z0-9][A-Za-z0-9-]*(?:[=\[]\S*)?[,\s]+)+', '').Trim()
                    if ($description -and $description -ne $line.Trim()) {
                        $descriptions[$normalized] = $description
                    }
                }
                }
            }
        }

        if ($options.Count -gt 0) {
            Set-Variable -Name 'MktempCompletionOptions' -Value (@($options | Sort-Object)) -Scope Script
            Set-Variable -Name 'MktempCompletionDescriptions' -Value $descriptions -Scope Script
            return (Get-Variable -Name 'MktempCompletionOptions' -Scope Script).Value
        }
    }

    Set-Variable -Name 'MktempCompletionOptions' -Value $fallbackOptions -Scope Script
    return (Get-Variable -Name 'MktempCompletionOptions' -Scope Script).Value
}


function New-MktempCompletionResult {
    param(
        [string]$CompletionText,
        [string]$ResultType,
        [string]$ToolTip,
        [string]$ListItemText
    )

    if ([string]::IsNullOrWhiteSpace($ListItemText)) {
        $ListItemText = $CompletionText
    }

    if ([string]::IsNullOrWhiteSpace($ToolTip)) {
        $ToolTip = $CompletionText
    }

    [System.Management.Automation.CompletionResult]::new(
        $CompletionText,
        $ListItemText,
        $ResultType,
        $ToolTip
    )
}

function ConvertFrom-MktempTypedWord {
    # The value of a typed word. A word opened with a quote (ASCII or typographic) is read by
    # the PowerShell tokenizer, which drops the quotes and undoes that quote style's escapes.
    param([string]$Value)

    if ($Value -notmatch '^[''"\u2018-\u201E]') {
        return $Value
    }

    $tokens = $null
    $parseErrors = $null
    [void][System.Management.Automation.Language.Parser]::ParseInput($Value, [ref]$tokens, [ref]$parseErrors)
    $tokens[0].Value
}

function ConvertTo-MktempQuotedValue {
    # Renders a value as one PowerShell argument: bare when safe and no quote was typed,
    # otherwise in the quote the user typed (single by default). PowerShell reads ' and
    # U+2018-U+201B as single quotes and " and U+201C-U+201E as double quotes.
    param(
        [string]$Value,
        [string]$QuoteChar = ''
    )

    if ([string]::IsNullOrEmpty($Value)) {
        return $Value
    }

    if (-not $QuoteChar) {
        if ($Value -notmatch '[\s{}();,|&<>''"`$@#\u2018-\u201E]' -and $Value -notmatch '^[-\u2013-\u2015]') {
            return $Value
        }

        $QuoteChar = "'"
    }

    if ($QuoteChar -match '^[''\u2018-\u201B]$') {
        return $QuoteChar + ($Value -replace '([''\u2018-\u201B])', '$1$1') + $QuoteChar
    }

    $QuoteChar + ($Value -replace '([`"$\u201C-\u201E])', '`$1') + $QuoteChar
}

function Get-MktempCurrentToken {
    param(
        [System.Management.Automation.Language.CommandAst]$CommandAst,
        [int]$CursorPosition
    )

    # The parser keeps an unterminated quoted word as one element running to the cursor.
    foreach ($element in ($CommandAst.CommandElements | Select-Object -Skip 1)) {
        $extent = $element.Extent
        if ($extent.StartOffset -lt $CursorPosition -and $CursorPosition -le $extent.EndOffset) {
            return $extent.Text.Substring(0, $CursorPosition - $extent.StartOffset)
        }
    }

    ''
}

function Get-MktempPathCompletions {
    param(
        [string]$InputPath,
        [switch]$DirectoriesOnly
    )

    $cleanInput = ConvertFrom-MktempTypedWord -Value $InputPath
    $quoteChar = if ($InputPath -match '^[''"\u2018-\u201E]') { $InputPath.Substring(0, 1) } else { '' }

    # The directory part is kept exactly as typed ('.\', '../', 'C:\x/'), so no typed text is lost.
    $separatorIndex = $cleanInput.LastIndexOfAny([char[]]@('\', '/'))
    $typedDirectory = $cleanInput.Substring(0, $separatorIndex + 1)
    $leaf = $cleanInput.Substring($separatorIndex + 1)
    $parent = if ($typedDirectory) { $typedDirectory } else { '.' }

    if (-not (Test-Path -LiteralPath $parent -PathType Container -ErrorAction Ignore)) {
        return @()
    }

    $items = @(Get-ChildItem -LiteralPath $parent -ErrorAction Ignore)
    $items = $items | Where-Object { $_.Name -like ([System.Management.Automation.WildcardPattern]::Escape($leaf) + '*') -and (-not $DirectoriesOnly -or $_.PSIsContainer) } | Sort-Object -Property Name

    foreach ($item in $items) {
        $pathText = $typedDirectory + $item.Name
        # A bare word led by a dash parses as a parameter; lead it with '.\' as PowerShell does.
        if (-not $typedDirectory -and $pathText -match '^[-\u2013-\u2015]') {
            $pathText = '.' + [System.IO.Path]::DirectorySeparatorChar + $pathText
        }

        if ($item.PSIsContainer -and -not $pathText.EndsWith([System.IO.Path]::DirectorySeparatorChar)) {
            $pathText += [System.IO.Path]::DirectorySeparatorChar
        }

        $quotedPath = ConvertTo-MktempQuotedValue -Value $pathText -QuoteChar $quoteChar
        if ($item.PSIsContainer) {
            New-MktempCompletionResult -CompletionText $quotedPath -ListItemText $pathText -ResultType 'ProviderContainer' -ToolTip $item.FullName
        } else {
            New-MktempCompletionResult -CompletionText $quotedPath -ListItemText $pathText -ResultType 'ProviderItem' -ToolTip $item.FullName
        }
    }
}

function Complete-MktempTemplate {
    param([string]$Prefix)

    # TEMPLATE names a file that does not exist yet and must end in at least three X's, so the
    # operand slot offers template shapes (and extends a typed prefix) rather than existing files.
    $templates = @(
        @{ Text = 'tmp.XXXXXXXXXX'; Tip = 'The default template used when none is given.' }
        @{ Text = 'XXXXXXXXXX'; Tip = 'Ten random characters in the current directory.' }
        @{ Text = '<prefix>XXXXXX'; Tip = 'TEMPLATE must contain at least 3 consecutive X''s in its last component.' }
    )

    # A quoted or half-quoted prefix is extended on its bare text and re-quoted the same way.
    $quote = if ($Prefix -match '^[''"\u2018-\u201E]') { $Prefix.Substring(0, 1) } else { '' }
    $bare = ConvertFrom-MktempTypedWord -Value $Prefix

    $results = [System.Collections.Generic.List[object]]::new()
    if (-not [string]::IsNullOrEmpty($bare) -and $bare -notmatch 'X$') {
        $extended = $bare + 'XXXXXX'
        $results.Add((New-MktempCompletionResult -CompletionText (ConvertTo-MktempQuotedValue -Value $extended -QuoteChar $quote) -ListItemText $extended -ResultType 'ParameterValue' -ToolTip 'Typed prefix extended with the six X''s mktemp replaces.'))
    }

    foreach ($template in $templates) {
        if ($template.Text.StartsWith($bare, [System.StringComparison]::Ordinal)) {
            $results.Add((New-MktempCompletionResult -CompletionText ($quote + $template.Text + $quote) -ListItemText $template.Text -ResultType 'ParameterValue' -ToolTip $template.Tip))
        }
    }

    # A template may carry a directory part ('--tmpdir' allows slashes), so complete that part.
    if ($Prefix -match '[\\/]') {
        foreach ($result in Get-MktempPathCompletions -InputPath $Prefix -DirectoriesOnly) {
            $results.Add($result)
        }
    }

    @($results.ToArray())
}

function Get-MktempOptionValueCompletions {
    param(
        [System.Management.Automation.Language.CommandAst]$commandAst,
        [string]$CurrentWord
    )

    $option = $null
    $prefix = $CurrentWord
    $attached = ''
    if ($CurrentWord -match '^(?<option>--?[A-Za-z0-9][A-Za-z0-9-]*)=(?<value>.*)$') {
        $option = $Matches['option']
        $prefix = $Matches['value']
        $attached = $option + '='
    } elseif ($CurrentWord -cmatch '^(?<option>-p)(?<value>.+)$') {
        # getopt accepts the DIR directly appended to -p ('-pC:\Temp').
        $option = $Matches['option']
        $prefix = $Matches['value']
        $attached = $option
    } elseif (-not $CurrentWord.StartsWith('-')) {
        $elements = @($commandAst.CommandElements | ForEach-Object { $_.Extent.Text })
        if ([string]::IsNullOrEmpty($CurrentWord)) {
            if ($elements.Count -gt 1) {
                $option = $elements[-1]
            }
        } elseif ($elements.Count -gt 2 -and $elements[-1] -eq $CurrentWord) {
            $option = $elements[-2]
        }

        # --tmpdir[=DIR] takes its DIR only attached, so the word after a bare --tmpdir is the
        # TEMPLATE operand; only -p and --suffix own the next word.
        if ($option -cnotin @('-p', '--suffix')) {
            $option = $null
        }
    }

    $table = [System.Collections.Hashtable]::new([System.StringComparer]::Ordinal)
    $table['--suffix'] = @(
        @{ Text = '<suffix>'; Tip = 'Suffix appended to the template.' }
    )
    $table['-p'] = 'path'
    $table['--tmpdir'] = 'path'
    if ([string]::IsNullOrEmpty($option) -or -not $table.ContainsKey($option)) {
        return @()
    }

    $spec = $table[$option]
    if ($spec -is [string] -and $spec -eq 'path') {
        # -p DIR / --tmpdir[=DIR] take a directory, so files are filtered out and the container
        # result type is kept.
        return @(
            foreach ($result in Get-MktempPathCompletions -InputPath $prefix -DirectoriesOnly) {
                New-MktempCompletionResult -CompletionText ($attached + $result.CompletionText) -ListItemText $result.ListItemText -ResultType $result.ResultType -ToolTip $result.ToolTip
            }
        )
    }

    $values = if ($spec -is [scriptblock]) { @(& $spec) } else { @($spec) }
    @(
        foreach ($entry in $values) {
            if ($entry.Text.StartsWith($prefix, [System.StringComparison]::Ordinal)) {
                New-MktempCompletionResult -CompletionText ($attached + $entry.Text) -ListItemText $entry.Text -ResultType 'ParameterValue' -ToolTip $entry.Tip
            }
        }
    )
}

function Get-MktempOptionDescription {
    param([string]$Option)

    $cache = Get-Variable -Name 'MktempCompletionDescriptions' -Scope Script -ErrorAction Ignore
    if ($null -ne $cache -and $null -ne $cache.Value -and $cache.Value.ContainsKey($Option)) {
        return $cache.Value[$Option]
    }

    'Option for mktemp.'
}

function Complete-Mktemp {
    param(
        [string]$wordToComplete,
        [System.Management.Automation.Language.CommandAst]$commandAst,
        [int]$cursorPosition
    )

    $currentWord = Get-MktempCurrentToken -CommandAst $commandAst -CursorPosition $cursorPosition

    $optionValues = @(Get-MktempOptionValueCompletions -commandAst $commandAst -CurrentWord $currentWord)
    if ($optionValues.Count -gt 0) {
        # PowerShell splits '-pC:\Temp' at the colon and only replaces the text after '-pC:', so
        # when its word is a suffix of the token this completer derived, the part it will not
        # replace is trimmed from every result.
        if (-not [string]::IsNullOrEmpty($wordToComplete) -and $currentWord.Length -gt $wordToComplete.Length -and $currentWord.EndsWith($wordToComplete, [System.StringComparison]::Ordinal)) {
            $head = $currentWord.Substring(0, $currentWord.Length - $wordToComplete.Length)
            $optionValues = @(
                foreach ($result in $optionValues) {
                    if ($result.CompletionText.StartsWith($head, [System.StringComparison]::OrdinalIgnoreCase)) {
                        New-MktempCompletionResult -CompletionText $result.CompletionText.Substring($head.Length) -ListItemText $result.ListItemText -ResultType $result.ResultType -ToolTip $result.ToolTip
                    }
                }
            )
        }

        return $optionValues
    }

    # A value slot with no match ('mktemp -p sub' with no such directory) stays a value slot;
    # it must not fall through to the TEMPLATE shapes.
    $previousToken = $null
    foreach ($element in ($commandAst.CommandElements | Select-Object -Skip 1)) {
        if ($element.Extent.EndOffset -lt $cursorPosition) {
            $previousToken = $element.Extent.Text
        }
    }

    if ($currentWord -match '^(?:--?[A-Za-z0-9][A-Za-z0-9-]*=|-p.)' -or ((-not $currentWord.StartsWith('-')) -and $previousToken -cin @('-p', '--suffix'))) {
        return @()
    }

    if (-not [string]::IsNullOrEmpty($currentWord) -and $currentWord.StartsWith('-')) {
        return @(
            foreach ($option in Get-MktempCompletionOptions) {
                if ($option.StartsWith($currentWord, [System.StringComparison]::Ordinal)) {
                    New-MktempCompletionResult -CompletionText $option -ListItemText $option -ResultType 'ParameterName' -ToolTip (Get-MktempOptionDescription -Option $option)
                }
            }
        )
    }

    Complete-MktempTemplate -Prefix $currentWord
}

Register-ArgumentCompleter -Native -CommandName 'mktemp', 'mktemp.exe' -ScriptBlock {
    param($wordToComplete, $commandAst, $cursorPosition)

    Complete-Mktemp -wordToComplete $wordToComplete -commandAst $commandAst -cursorPosition $cursorPosition
}