specialK.psm1

<#
    Code in this file will be added to the beginning of the .psm1. For example,
    you should place any using statements here.
#>

function ConvertFrom-KubectlTable {
    <#
        Turns the text lines of a kubectl table into objects stamped with a format type name.
        Column starts come from the header: a column begins at a word that follows two or more spaces,
        because values can be empty in the data lines. Data lines shorter than the header are padded,
        never dropped, so a missing trailing value is an empty property.
        Columns listed in ConvertTo-KubectlValue become typed values that still print as kubectl printed them.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string[]]$Lines,
        [Parameter(Mandatory)][string]$TypeName
    )
    $header = $Lines[0]
    $positions = @([regex]::Matches($header, ' \S') | ForEach-Object { $_.Index + 2 } | Sort-Object -Descending)
    $rows = foreach ($line in $Lines) {
        $line = $line.PadRight($header.Length)
        foreach ($position in $positions) {
            $line = $line.Insert($position, ';')
        }
        $line
    }
    $rows -replace ' +;', ';' | ForEach-Object { $_.Trim() } | ConvertFrom-Csv -Delimiter ';' | ForEach-Object {
        $_.PSObject.TypeNames.Insert(0, $TypeName)
        foreach ($property in $_.PSObject.Properties) {
            $property.Value = ConvertTo-KubectlValue -Text $property.Value -Column $property.Name
        }
        $_
    }
}
# Every spelling kubectl accepts for a resource (plural, singular, short name) mapped to one canonical
# name. The canonical names are the ones in formats.json, so they double as format view names.
# `events` is canonical in the plural because that is how formats.json and the views spell it.
# An explicit table on purpose: guessing at plurals by trimming a trailing "s" turns `ingress` into `ingres`.
$script:KubectlResourceAliases = @{
    'pod'                    = 'pod'
    'pods'                   = 'pod'
    'po'                     = 'pod'
    'deployment'             = 'deployment'
    'deployments'            = 'deployment'
    'deploy'                 = 'deployment'
    'service'                = 'service'
    'services'               = 'service'
    'svc'                    = 'service'
    'namespace'              = 'namespace'
    'namespaces'             = 'namespace'
    'ns'                     = 'namespace'
    'node'                   = 'node'
    'nodes'                  = 'node'
    'no'                     = 'node'
    'event'                  = 'events'
    'events'                 = 'events'
    'ev'                     = 'events'
    'configmap'              = 'configmap'
    'configmaps'             = 'configmap'
    'cm'                     = 'configmap'
    'secret'                 = 'secret'
    'secrets'                = 'secret'
    'ingress'                = 'ingress'
    'ingresses'              = 'ingress'
    'ing'                    = 'ingress'
    'persistentvolumeclaim'  = 'persistentvolumeclaim'
    'persistentvolumeclaims' = 'persistentvolumeclaim'
    'pvc'                    = 'persistentvolumeclaim'
    'persistentvolume'       = 'persistentvolume'
    'persistentvolumes'      = 'persistentvolume'
    'pv'                     = 'persistentvolume'
    'statefulset'            = 'statefulset'
    'statefulsets'           = 'statefulset'
    'sts'                    = 'statefulset'
    'daemonset'              = 'daemonset'
    'daemonsets'             = 'daemonset'
    'ds'                     = 'daemonset'
    'replicaset'             = 'replicaset'
    'replicasets'            = 'replicaset'
    'rs'                     = 'replicaset'
    'job'                    = 'job'
    'jobs'                   = 'job'
    'cronjob'                = 'cronjob'
    'cronjobs'               = 'cronjob'
    'cj'                     = 'cronjob'
    'serviceaccount'         = 'serviceaccount'
    'serviceaccounts'        = 'serviceaccount'
    'sa'                     = 'serviceaccount'
    'endpoints'              = 'endpoints'
    'ep'                     = 'endpoints'
}

function ConvertTo-KubectlResourceName {
    <#
        Turns what the user typed after the verb into a canonical resource name.
        Handles short and plural names (po, deploy, svc), `type/name` (pod/web) and
        `type.group` (deployments.apps). Names it does not know come back lowercased and otherwise
        untouched, which keeps config sub-commands such as get-contexts working.
        Returns $null for nothing, and for a comma-separated list (pods,svc), which is several resources.
    #>

    [CmdletBinding()]
    param(
        [AllowNull()][AllowEmptyString()][string]$Name
    )
    if ([string]::IsNullOrWhiteSpace($Name) -or $Name.Contains(',')) { return $null }
    $resource = $Name.ToLowerInvariant()
    $slash = $resource.IndexOf('/')
    if ($slash -ge 0) { $resource = $resource.Substring(0, $slash) }
    if ($script:KubectlResourceAliases.ContainsKey($resource)) { return $script:KubectlResourceAliases[$resource] }
    # type.group, e.g. deployments.apps or deployments.v1.apps
    $dot = $resource.IndexOf('.')
    if ($dot -gt 0) {
        $kind = $resource.Substring(0, $dot)
        if ($script:KubectlResourceAliases.ContainsKey($kind)) { return $script:KubectlResourceAliases[$kind] }
    }
    $resource
}
# Which table columns carry a typed value, and how to read them. Keyed by the column header exactly as kubectl
# prints it; the same column means the same thing in every view (get/top, namespaced or not, wide or not).
# An explicit map on purpose: a column is typed because it is listed here, never because a value looks numeric.
# restarts '3' or '3 (5m ago)' -> [long] 3
# duration '45s' '5m12s' '3d13h' '2y45d' -> [TimeSpan]
# ready '1/2' -> [double] 0.5 (ready divided by total; 0/0 counts as 1)
# count '12' -> [long]
# cpu '250m' or '2' (cores) -> [long] millicores
# memory '128Mi' '1Gi' '1000' -> [long] bytes
# percent '26%' -> [long] 26
$script:KubectlColumnKinds = @{
    'RESTARTS'      = 'restarts'
    'AGE'           = 'duration'
    'LAST SEEN'     = 'duration'
    'DURATION'      = 'duration'
    'READY'         = 'ready'
    'COMPLETIONS'   = 'ready'
    'UP-TO-DATE'    = 'count'
    'AVAILABLE'     = 'count'
    'DATA'          = 'count'
    'CPU(cores)'    = 'cpu'
    'MEMORY(bytes)' = 'memory'
    'CPU(%)'        = 'percent'
    'MEMORY(%)'     = 'percent'
    'CAPACITY'      = 'memory'
}

# Cells kubectl prints when it has no value. They keep their text and have no Value.
$script:KubectlEmptyCells = @('<unknown>', '<invalid>', '<none>', '<nil>')

$script:KubectlMemoryUnits = @{
    'Ki' = [math]::Pow(1024, 1); 'Mi' = [math]::Pow(1024, 2); 'Gi' = [math]::Pow(1024, 3)
    'Ti' = [math]::Pow(1024, 4); 'Pi' = [math]::Pow(1024, 5); 'Ei' = [math]::Pow(1024, 6)
    'k'  = 1e3; 'M' = 1e6; 'G' = 1e9; 'T' = 1e12; 'P' = 1e15; 'E' = 1e18
}

function ConvertTo-KubectlValue {
    <#
        Turns one table cell into a [KubectlValue] when its column is typed (see $script:KubectlColumnKinds)
        and the text parses; otherwise returns the text unchanged. Never throws: a cell it does not
        understand (a future kubectl format, an empty cell) stays the plain string kubectl printed.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][AllowEmptyString()][AllowNull()][string]$Text,
        [Parameter(Mandatory)][string]$Column
    )
    $kind = $script:KubectlColumnKinds[$Column]
    if (-not $kind -or [string]::IsNullOrEmpty($Text)) { return $Text }
    if ($script:KubectlEmptyCells -contains $Text) { return [KubectlValue]::new($null, $Text) }

    $inv = [System.Globalization.CultureInfo]::InvariantCulture
    switch ($kind) {
        'restarts' {
            if ($Text -match '^(\d+)( \(.+ ago\))?$') { return [KubectlValue]::new([long]$Matches[1], $Text) }
        }
        'count' {
            if ($Text -match '^\d+$') { return [KubectlValue]::new([long]$Text, $Text) }
        }
        'percent' {
            if ($Text -match '^(\d+)%$') { return [KubectlValue]::new([long]$Matches[1], $Text) }
        }
        'ready' {
            if ($Text -match '^(\d+)/(\d+)$') {
                $total = [long]$Matches[2]
                $ratio = if ($total -eq 0) { 1.0 } else { [long]$Matches[1] / $total }
                return [KubectlValue]::new([double]$ratio, $Text)
            }
        }
        'duration' {
            # kubectl's duration: up to two adjacent units from y d h m s (a year is 365 days), as in 2y45d, 3d13h, 5m12s
            if ($Text -match '^(?:(\d+)y)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$') {
                $part = { param($i) if ($Matches[$i]) { [double]$Matches[$i] } else { 0.0 } }
                $span = [timespan]::FromSeconds(
                    (& $part 1) * 365 * 86400 + (& $part 2) * 86400 + (& $part 3) * 3600 + (& $part 4) * 60 + (& $part 5))
                return [KubectlValue]::new($span, $Text)
            }
        }
        'cpu' {
            if ($Text -match '^(\d+)m$') { return [KubectlValue]::new([long]$Matches[1], $Text) }
            if ($Text -match '^(\d+(\.\d+)?)$') { return [KubectlValue]::new([long]([double]::Parse($Matches[1], $inv) * 1000), $Text) }
        }
        'memory' {
            if ($Text -match '^(\d+(?:\.\d+)?)(Ki|Mi|Gi|Ti|Pi|Ei|k|M|G|T|P|E)?$') {
                $multiplier = if ($Matches[2]) { $script:KubectlMemoryUnits[$Matches[2]] } else { 1 }
                return [KubectlValue]::new([long]([double]::Parse($Matches[1], $inv) * $multiplier), $Text)
            }
        }
    }
    $Text
}
# Flags that take a value as the NEXT argument (`-n demo`, `--context foo`). The `--flag=value` and
# `-oVALUE` forms carry their value inside one argument and never need this list. Any other flag that
# starts with a dash is treated as a boolean. A value flag missing from here only matters when it
# appears before the verb or resource, where its value would be mistaken for one.
$script:KubectlValueFlags = @(
    '--namespace', '--context', '--cluster', '--user', '--kubeconfig', '--server', '--token',
    '--as', '--as-group', '--as-uid', '--request-timeout', '--selector', '--field-selector',
    '--output', '--sort-by', '--label-columns', '--filename', '--kustomize', '--chunk-size',
    '--template', '--cache-dir', '--certificate-authority', '--client-certificate', '--client-key',
    '--tls-server-name', '--username', '--password', '--container', '--profile', '--profile-output',
    '--v', '--vmodule', '--log-flush-frequency', '--subresource', '--field-manager'
)
# Single-letter equivalents of the above. `-n demo`, `-ndemo` and `-n=demo` are all valid.
$script:KubectlValueShortFlags = @('n', 's', 'l', 'o', 'L', 'f', 'k', 'c', 'v')

function Get-KubectlArgumentInfo {
    <#
        Finds out what a kubectl command line means without running it.
        Returns Verb (first positional), Positionals (the positionals after the verb, flags and their
        values removed), Output (the -o/--output value or $null), Watch, NoHeaders and AllNamespaces.
        Everything after a literal `--` is positional, as for kubectl.
    #>

    [CmdletBinding()]
    param(
        [AllowEmptyCollection()][AllowNull()][string[]]$Arguments = @()
    )
    $positionals = [System.Collections.Generic.List[string]]::new()
    $info = [ordered]@{
        Verb          = $null
        Positionals   = @()
        Output        = $null
        Watch         = $false
        NoHeaders     = $false
        AllNamespaces = $false
    }

    $list = @($Arguments | Where-Object { $null -ne $_ })
    $i = 0
    while ($i -lt $list.Count) {
        $arg = $list[$i]
        $i++
        if ($arg -ceq '--') {
            while ($i -lt $list.Count) { $positionals.Add($list[$i]); $i++ }
            break
        }

        if ($arg -match '^--(?<name>[^=]+)(=(?<value>.*))?$') {
            $name = $Matches.name
            $hasValue = $Matches.ContainsKey('value')
            $value = if ($hasValue) { $Matches.value } else { $null }
            if (-not $hasValue -and ($script:KubectlValueFlags -contains "--$name")) {
                if ($i -lt $list.Count) { $value = $list[$i]; $i++ }
                $hasValue = $true
            }
            # boolean flags may carry an explicit value: --watch=false
            $isOn = -not ($hasValue -and $value -eq 'false')
            switch ($name) {
                'output' { $info.Output = $value }
                'watch' { if ($isOn) { $info.Watch = $true } }
                'watch-only' { if ($isOn) { $info.Watch = $true } }
                'no-headers' { if ($isOn) { $info.NoHeaders = $true } }
                'all-namespaces' { if ($isOn) { $info.AllNamespaces = $true } }
            }
            continue
        }

        if ($arg -match '^-(?<letters>[^-].*)$') {
            # a bundle of short flags (-Aw); the first value-taking letter ends it
            # and the rest of the argument is its value (-oyaml, -n=demo, -ndemo)
            $letters = $Matches.letters
            for ($c = 0; $c -lt $letters.Length; $c++) {
                $letter = [string]$letters[$c]
                if ($script:KubectlValueShortFlags -ccontains $letter) {
                    $value = $letters.Substring($c + 1)
                    if ($value.StartsWith('=')) { $value = $value.Substring(1) }
                    if ($value.Length -eq 0 -and $c -eq $letters.Length - 1) {
                        if ($i -lt $list.Count) { $value = $list[$i]; $i++ } else { $value = $null }
                    }
                    if ($letter -ceq 'o') { $info.Output = $value }
                    break
                }
                switch -CaseSensitive ($letter) {
                    'w' { $info.Watch = $true }
                    'A' { $info.AllNamespaces = $true }
                }
            }
            continue
        }

        $positionals.Add($arg)
    }

    if ($positionals.Count -gt 0) {
        $info.Verb = $positionals[0]
        $info.Positionals = @($positionals | Select-Object -Skip 1)
    }
    [pscustomobject]$info
}
# One cell of a kubectl table that has a typed value but must keep printing exactly as kubectl printed it.
#
# Text the cell as kubectl printed it ('2 (3h15m ago)', '3d13h', '250m'). ToString() returns it, so the
# default table, Format-List, Export-Csv, string interpolation and -match see the original text.
# Value what the cell means: [long] (counts, millicores, bytes, percent), [double] (ready ratio) or
# [TimeSpan] (ages). $null for a cell kubectl could not fill in ('<unknown>', '<none>').
#
# It compares by Value (IComparable), so Sort-Object, Group-Object and -lt/-gt/-eq work. PowerShell converts the
# right-hand operand to the type of the left-hand one before comparing, which is why there is one constructor
# per type a user would compare against (number, [TimeSpan], string). A cell with no Value sorts after everything,
# which keeps -lt filters from matching it. IConvertible is there so Measure-Object -Sum/-Average works on
# numeric cells (CPU, MEMORY, RESTARTS). Any other class member is deliberately absent: keep it small.
class KubectlValue : System.IComparable, System.IConvertible {
    [object]$Value
    [string]$Text

    KubectlValue([object]$value, [string]$text) {
        $this.Value = $value
        $this.Text = $text
    }
    KubectlValue([long]$value) {
        $this.Value = $value
        $this.Text = "$value"
    }
    KubectlValue([double]$value) {
        $this.Value = $value
        $this.Text = "$value"
    }
    KubectlValue([timespan]$value) {
        $this.Value = $value
        $this.Text = "$value"
    }
    # A plain string on the right of a comparison ('-gt "3"'): numbers and durations are read, anything else has no Value.
    KubectlValue([string]$text) {
        $this.Text = $text
        $number = 0.0
        $span = [timespan]::Zero
        if ([double]::TryParse($text, [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$number)) {
            $this.Value = $number
        } elseif ($text -match '^(?=\d)(?:(\d+)y)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$') {
            # a kubectl-style duration, so AGE -lt '1h' reads the way kubectl prints ages
            $seconds = 0.0
            $unit = @((365 * 86400), 86400, 3600, 60, 1)
            for ($i = 1; $i -le 5; $i++) { if ($Matches[$i]) { $seconds += [double]$Matches[$i] * $unit[$i - 1] } }
            $this.Value = [timespan]::FromSeconds($seconds)
        } elseif ([timespan]::TryParse($text, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$span)) {
            $this.Value = $span
        }
    }

    [string] ToString() {
        return $this.Text
    }

    # Numbers compare as numbers, durations as durations. Anything else (a number against a duration) is
    # ordered after, never an error: a bad comparison must not break a pipeline. The text only decides when a
    # side has no Value to compare: two cells without one are equal when they print the same, and ordered by
    # their text otherwise. A cell with a Value sorts before one without.
    [int] CompareTo([object]$other) {
        # a plain string is read the same way as on the right of -lt/-gt ('1h', '3')
        if ($other -is [string]) { $other = [KubectlValue]::new([string]$other) }
        $theirs = if ($other -is [KubectlValue]) { $other.Value } else { $other }
        $theirText = if ($other -is [KubectlValue]) { $other.Text } else { "$other" }
        $mine = $this.Value
        if ($null -eq $mine -or $null -eq $theirs) {
            $byText = [string]::Compare($this.Text, $theirText, [System.StringComparison]::OrdinalIgnoreCase)
            if ($byText -eq 0) { return 0 }
            if ($null -eq $mine -and $null -eq $theirs) { return [Math]::Sign($byText) }
            if ($null -eq $mine) { return 1 }
            return -1
        }
        if ($mine -is [timespan] -and $theirs -is [timespan]) { return $mine.CompareTo($theirs) }
        # a number against a duration can't be ordered, but the same text is still the same cell: CPU -eq '250m'
        # reads '250m' as 250 minutes, and must still match the cell kubectl printed as 250m
        if ($mine -is [timespan] -or $theirs -is [timespan]) {
            if ([string]::Equals($this.Text, $theirText, [System.StringComparison]::OrdinalIgnoreCase)) { return 0 }
            return 1
        }
        $a = 0.0
        $b = 0.0
        if ([double]::TryParse("$mine", [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$a) -and
            [double]::TryParse("$theirs", [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$b)) {
            return $a.CompareTo($b)
        }
        return 1
    }

    [bool] Equals([object]$other) {
        if ($null -eq $other) { return $false }
        return $this.CompareTo($other) -eq 0
    }

    # Must agree with Equals: numbers hash as doubles (1000 and 1000.0 are equal), cells without a Value by their
    # text, ignoring case.
    [int] GetHashCode() {
        if ($null -eq $this.Value) { return $this.Text.ToUpperInvariant().GetHashCode() }
        if ($this.Value -is [timespan]) { return $this.Value.GetHashCode() }
        $number = 0.0
        if ([double]::TryParse("$($this.Value)", [System.Globalization.NumberStyles]::Float, [System.Globalization.CultureInfo]::InvariantCulture, [ref]$number)) { return $number.GetHashCode() }
        return $this.Value.GetHashCode()
    }

    # IConvertible: only the numeric conversions mean something.
    [double] AsDouble() {
        if ($this.Value -is [timespan]) { return $this.Value.TotalSeconds }
        if ($null -eq $this.Value) { throw [System.InvalidCastException]::new("'$($this.Text)' has no numeric value") }
        return [double]$this.Value
    }
    [System.TypeCode] GetTypeCode() { return [System.TypeCode]::Object }
    [double] ToDouble([System.IFormatProvider]$provider) { return $this.AsDouble() }
    [decimal] ToDecimal([System.IFormatProvider]$provider) { return [decimal]$this.AsDouble() }
    [long] ToInt64([System.IFormatProvider]$provider) { return [long]$this.AsDouble() }
    [int] ToInt32([System.IFormatProvider]$provider) { return [int]$this.AsDouble() }
    [int16] ToInt16([System.IFormatProvider]$provider) { return [int16]$this.AsDouble() }
    [float] ToSingle([System.IFormatProvider]$provider) { return [float]$this.AsDouble() }
    [string] ToString([System.IFormatProvider]$provider) { return $this.Text }
    [bool] ToBoolean([System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
    [byte] ToByte([System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
    [char] ToChar([System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
    [datetime] ToDateTime([System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
    [sbyte] ToSByte([System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
    [uint16] ToUInt16([System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
    [uint32] ToUInt32([System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
    [uint64] ToUInt64([System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
    [object] ToType([type]$conversionType, [System.IFormatProvider]$provider) { throw [System.InvalidCastException]::new() }
}
function Write-KubectlExitError {
    <#
        Reports a failed kubectl call as a PowerShell error. It is non-terminating: it lands in $Error and
        on the error stream, and $ErrorActionPreference = 'Stop' turns it into an exception. $LASTEXITCODE is
        not touched, and is the reliable failure signal: `$?` stays true after any script function returns,
        whatever it wrote to the error stream. kubectl's own message already went to stderr.
        The message and TargetObject name only the verb and the first positional after it, never the whole
        argument list, which can hold --token, --password or --from-literal values.
    #>

    [CmdletBinding()]
    param(
        [AllowNull()][object]$ExitCode,
        [string[]]$Arguments
    )
    if ($null -eq $ExitCode -or $ExitCode -eq 0) { return }
    $info = Get-KubectlArgumentInfo -Arguments $Arguments
    $what = @($info.Verb, ($info.Positionals | Select-Object -First 1)) | Where-Object { $_ }
    $target = (@('kubectl') + $what) -join ' '
    $message = "$target failed with exit code $ExitCode"
    $record = [System.Management.Automation.ErrorRecord]::new(
        [System.InvalidOperationException]::new($message),
        'KubectlFailed',
        [System.Management.Automation.ErrorCategory]::NotSpecified,
        $target
    )
    # No -ErrorAction here on purpose: a module function sees $ErrorActionPreference from the global
    # scope only, not from the caller's script or function scope. Set globally (as in a profile or an
    # interactive session) it turns this into a terminating error; a plain `k` call just reports it.
    Write-Error -ErrorRecord $record
}
# https://kubernetes.io/docs/tasks/tools/included/optional-kubectl-configs-pwsh/
# but we are going to switch the completer to 'k' from 'kubectl'
Function Add-specialKAutoCompletion {
    # The completer script comes from 'kubectl completion powershell' and has to be evaluated to register it.
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingInvokeExpression', '', Justification = 'Registers the completer script generated by kubectl itself')]
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [switch]$ToProfile,
        [string]$ProfilePath = $PROFILE.CurrentUserCurrentHost
    )
    $toReplace = "-CommandName 'kubectl'"
    $argCompleter = (kubectl completion powershell) -replace $toReplace, "-CommandName 'k'"
    if ($argCompleter -like 'error*') {
        throw $argCompleter
    }

    if ($null -ne $argCompleter -and $PSCmdlet.ShouldProcess('k', 'Register the kubectl argument completer')) {
        $argCompleter | Out-String | Invoke-Expression
    }

    if ($ToProfile.IsPresent) {
        $beginMarker = '# >>> specialK completion >>>'
        $endMarker = '# <<< specialK completion <<<'
        $existing = if (Test-Path -LiteralPath $ProfilePath) { Get-Content -LiteralPath $ProfilePath -Raw } else { '' }
        if ($null -eq $existing) { $existing = '' }

        # Older versions appended a static snapshot of the completer. It is never edited here, only reported.
        if ($existing -match "Register-ArgumentCompleter[^\r\n]*-CommandName\s+'k'") {
            Write-Warning "$ProfilePath contains a static copy of the completer from an older specialK. It goes stale when kubectl updates. To remove it, delete the Register-ArgumentCompleter block for -CommandName 'k' (and the script block it uses) from that file by hand."
        }

        if ($existing.Contains($beginMarker)) {
            Write-Verbose "$ProfilePath already has the specialK completion block; nothing to do."
            return
        }

        $block = @(
            $beginMarker
            'if (Get-Command kubectl -ErrorAction SilentlyContinue) {'
            ' Add-specialKAutoCompletion'
            '}'
            $endMarker
        ) -join [Environment]::NewLine

        if ($PSCmdlet.ShouldProcess($ProfilePath, 'Add the specialK completion block')) {
            $folder = Split-Path -Path $ProfilePath -Parent
            if ($folder -and -not (Test-Path -LiteralPath $folder)) {
                New-Item -Path $folder -ItemType Directory -Force | Out-Null
            }
            $prefix = if ($existing.Length -gt 0 -and -not $existing.EndsWith("`n")) { [Environment]::NewLine } else { '' }
            Add-Content -LiteralPath $ProfilePath -Value ($prefix + $block)
        }
    }
}
function k {
    # Behaves like kubectl for everything except the commands listed in formats.json, and only when
    # the output is the default table or -o wide. Those are captured and turned into objects; anything
    # else (watching, -o yaml, exec, edit, unknown verbs) goes straight to kubectl with nothing captured,
    # so it streams and keeps the terminal.
    $info = Get-KubectlArgumentInfo -Arguments $args
    $resource = $null
    if ($info.Verb) {
        $resource = ConvertTo-KubectlResourceName -Name ($info.Positionals | Select-Object -First 1)
        # `get pod/web service/web` mixes tables with different columns: convert only when every type/name
        # argument is the same resource, otherwise hand the call to kubectl untouched
        $resources = @($info.Positionals | Where-Object { $_.Contains('/') } | ForEach-Object { ConvertTo-KubectlResourceName -Name $_ } | Select-Object -Unique)
        if ($resources.Count -gt 1 -or ($resources.Count -eq 1 -and $resources[0] -ne $resource)) {
            $resource = $null
        }
    }
    $convert = $resource -and
        ($objectCommands[$info.Verb] -contains $resource) -and
        -not $info.Watch -and
        -not $info.NoHeaders -and
        ($null -eq $info.Output -or $info.Output -ceq 'wide')

    if (-not $convert) {
        & kubectl @args
        Write-KubectlExitError -ExitCode $LASTEXITCODE -Arguments $args
        return
    }

    # @() keeps a one-line result an array, so $out[0] is a line and not its first character
    $out = @(& kubectl @args)
    $exitCode = $LASTEXITCODE
    # kubectl's default tables start with one of these headers
    if ($exitCode -eq 0 -and $out -and ($out[0] -match '^(NAME( |$)|NAMESPACE |CURRENT |LAST SEEN )')) {
        $typeName = "$($info.Verb)-$resource"
        if ($out[0] -match '^NAMESPACE ') { $typeName += '-ns' }
        if ($info.Output -ceq 'wide') { $typeName += '-wide' }
        ConvertFrom-KubectlTable -Lines @($out) -TypeName $typeName
    } else {
        $out
    }
    Write-KubectlExitError -ExitCode $exitCode -Arguments $args
}
<#
    Code in this file will be added to the end of the .psm1. For example,
    you should set variables or other environment settings here.
#>

$script:objectCommands = Get-Content $PSScriptRoot\formats.json | ConvertFrom-Json -AsHashtable

# An alias beats a function in PowerShell's command resolution, so an existing alias named k hides the k function.
$existingAlias = Get-Alias -Name k -ErrorAction Ignore
if ($existingAlias -and $existingAlias.Definition -ne 'k') {
    Write-Warning "An alias 'k' for '$($existingAlias.Definition)' exists, and PowerShell prefers aliases over functions, so typing k runs '$($existingAlias.Definition)' and not specialK's k. Remove the alias to use specialK: Remove-Item Alias:k (and delete the Set-Alias line from your profile)."
}
Remove-Variable existingAlias