posh-dotnet.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "")] # needed to override tab completion
Param()

$global:DotnetCompletion = @{}
if ($global:DotnetCompletion.Count -eq 0)
{
    $global:DotnetCompletion["commands"] = @{}
    $global:DotnetCompletion["options"] = @()
        
    dotnet --help | ForEach-Object { 
        if ($_ -match "^\s{2,3}(\w+)\s+(.+)")
        {
            # The help includes some documentation that are indented the same way -> do not include them by assuming that commans start with a lower case
            if ($null -ne $Matches[1] -and $Matches[1].Count -gt 0 -and !([Char]::IsUpper($Matches[1][0])))
            {
                $global:DotnetCompletion["commands"][$Matches[1]] = @{}
                
                $currentCommand = $global:DotnetCompletion["commands"][$Matches[1]]
                $currentCommand["options"] = @()
            }
        }
        elseif ($_ -match $flagRegex)
        {
            $global:DotnetCompletion["options"] += $Matches[1]
            if ($null -ne $Matches[2])
            {
                $global:DotnetCompletion["options"] += $Matches[2]
            }
        }
    }
}

$script:flagRegex = "^ (-[^, =]+),? ?(--[^= ]+)?"

function script:Get-AutoCompleteResult
{
    param([Parameter(ValueFromPipeline = $true)] $value)
    
    Process
    {
        New-Object System.Management.Automation.CompletionResult $value
    }
}

filter script:MatchingCommand($commandName)
{
    if ($_.StartsWith($commandName))
    {
        $_
    }
}

# extracts help for dotnet cli v2
function Get-HelpTextV2HashTable
{
    # since commandElements is a strongly typed ast (that has already been parsed), the command injection risk has been mitigated
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingInvokeExpression", "")]
    Param
    (
        [System.Management.Automation.Language.StringConstantExpressionAst[]]$commandElements,
        $completionList
    )

    $help = Invoke-Expression "$([string]::Join(" ", $CommandElements)) --help"
    $commandHelp = @{}
    foreach ($command in $completionList)
    {
        $help | ForEach-Object {
            # a command help ends with ',' or ' '
            if ($_.Length -gt 2 -and $_.StartsWith(" ") -and ( $_.Remove(0, 2).StartsWith("$command ") -or $_.Remove(0, 2).StartsWith("$command,")))
            {
                $helpText =  $_.TrimStart().Remove(0, $Command.Length).TrimStart()
                $commandHelp.Add($command, $helpText)
            }
            elseif ($_.Length -gt 2 -and -not $_.StartsWith(" ") -and  $_.Contains(" $command ")) # dotnet new
            {
                $helpText =  ($_ -split " ")[0]
                $commandHelp.Add($command, $helpText)
            }
        }
    }
    return $commandHelp
}

$completion_Dotnet = {
    param($commandName, $commandAst, $cursorPosition)

    [int]$dotnetMajorVersion = [int]::Parse(((dotnet --version)[0]))
    if ($dotnetMajorVersion -ge 2)
    {
        # Starting from version 2, the dotnet CLI offers a dedicated complete command. See https://github.com/dotnet/cli/blob/master/Documentation/general/tab-completion.md
        $completionList = dotnet complete --position $cursorPosition "$commandAst"
        # the user has not given any details about the next command to be tab completed
        if ([string]::IsNullOrWhiteSpace($commandName))
        {
            [hashtable]$helpList = Get-HelpTextV2HashTable $commandAst.CommandElements $completionList
            $completionList | ForEach-Object { if ($null -eq $helpList[$_]){ $helpList.Add($_,$_)} }
            $completionList | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $helpList[$_])  }
        }
        else
        {
            $completionList = $completionList | Where-Object {
                $_.StartsWith($commandAst.CommandElements[$commandAst.CommandElements.Count-1])
            }
            # do not use last incomplete command
            $commandElementsExceptLastOne = $commandAst.CommandElements | Select-Object -First ($commandAst.CommandElements.Count-1)
            $helpList = Get-HelpTextV2HashTable $commandElementsExceptLastOne $completionList
        }
        $completionList | ForEach-Object { if ($null -eq $helpList[$_]){ $helpList.Add($_,$_)} } # add missing help entries that could not get parsed
        $completionList | Sort-Object | ForEach-Object { [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $helpList[$_])  }   
    }
    else
    {
        $command = $null
        $commandParameters = @{}
        $state = "Unknown"
        $wordToComplete = $commandAst.CommandElements | Where-Object { $_.ToString() -eq $commandName } | Foreach-Object { $commandAst.CommandElements.IndexOf($_) }

        for ($i = 1; $i -lt $commandAst.CommandElements.Count; $i++)
        {
            $p = $commandAst.CommandElements[$i].ToString()

            if ($p.StartsWith("-"))
            {
                if ($state -eq "Unknown" -or $state -eq "Options")
                {
                    $commandParameters[$i] = "Option"
                    $state = "Options"
                }
                else
                {
                    $commandParameters[$i] = "CommandOption"
                    $state = "CommandOptions"
                }
            } 
            else 
            {
                $commandParameters[$i] = "Command"
                $command = $p
                $state = "CommandOptions"
            }
        }
        
        if ($wordToComplete -ne $null)
        {
            $commandToComplete = $commandParameters[$wordToComplete]
        }

        switch ($commandToComplete)
        {
            "Command" { $global:DotnetCompletion["commands"].Keys | MatchingCommand -Command $commandName | Sort-Object | Get-AutoCompleteResult }
            "Option" { $global:DotnetCompletion["options"] | MatchingCommand -Command $commandName | Sort-Object | Get-AutoCompleteResult }
            "CommandOption"
            { 
                $options = $global:DotnetCompletion["commands"][$command]["options"]
                if ($options.Count -eq 0)
                {
                    dotnet $command --help | ForEach-Object {
                        if ($_ -match $flagRegex)
                        {
                            if ($Matches[1].Contains('|'))
                            {
                                $options += $Matches[1].Split('|') 
                            }
                            else
                            {
                                $options += $Matches[1]
                                if ($Matches[2] -ne $null)
                                {
                                    $options += $Matches[2]
                                }
                            }
                        }
                        elseif ($_ -match "^ (-[^, =]+),? ?(-[^= ]+)?") # version 1.0 has -c|--configuration for some options like e.g. dotnet build --help
                        {
                            $options += $Matches[1]
                            if ($Matches[2] -ne $null)
                            {
                                $options += $Matches[2]
                            }
                        }
                    }
                }

                $global:DotnetCompletion["commands"][$command]["options"] = $options
                $options | MatchingCommand -Command $commandName | Sort-Object | Get-AutoCompleteResult
            }
            default { $global:DotnetCompletion["commands"].Keys | MatchingCommand -Command $commandName }
        }
    }
}


if (Get-Command Register-ArgumentCompleter -ea Ignore)
{
    Register-ArgumentCompleter -CommandName 'dotnet' -ScriptBlock $Completion_Dotnet -Native
}
else
{
    # in version 3 and 4 of PS, one needs to install TabExpansionPlusPlus for backcompat. No check for the psversion needed since the manifest does that already.
    throw "Required module TabExpansionPlusPlus is not installed. Please install it using 'Install-Module TabExpansionPlusPlus'"    
}