-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathpowershell.ts
More file actions
477 lines (395 loc) · 13.7 KB
/
powershell.ts
File metadata and controls
477 lines (395 loc) · 13.7 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
import {Command, Config, Interfaces} from '@oclif/core'
import * as ejs from 'ejs'
import {EOL} from 'node:os'
import {format} from 'node:util'
type CommandCompletion = {
flags: CommandFlags
id: string
summary: string
}
type CommandFlags = {
[name: string]: Command.Flag.Cached
}
type Topic = {
description: string
name: string
}
export default class PowerShellComp {
protected config: Config
private _coTopics?: string[]
private commands: CommandCompletion[]
private topics: Topic[]
constructor(config: Config) {
this.config = config
this.topics = this.getTopics()
this.commands = this.getCommands()
}
private get coTopics(): string[] {
if (this._coTopics) return this._coTopics
const coTopics: string[] = []
for (const topic of this.topics) {
for (const cmd of this.commands) {
if (topic.name === cmd.id) {
coTopics.push(topic.name)
}
}
}
this._coTopics = coTopics
return this._coTopics
}
public generate(): string {
const genNode = (partialId: string): Record<string, any> => {
const node: Record<string, any> = {}
const nextArgs: string[] = []
const depth = partialId.split(':').length
for (const t of this.topics) {
const topicNameSplit = t.name.split(':')
if (t.name.startsWith(partialId + ':') && topicNameSplit.length === depth + 1) {
nextArgs.push(topicNameSplit[depth])
node[topicNameSplit[depth]] = this.coTopics.includes(t.name)
? {
...genNode(`${partialId}:${topicNameSplit[depth]}`),
}
: {
_summary: t.description,
...genNode(`${partialId}:${topicNameSplit[depth]}`),
}
}
}
for (const c of this.commands) {
const cmdIdSplit = c.id.split(':')
if (partialId === c.id && this.coTopics.includes(c.id)) {
node._command = c.id
}
if (
c.id.startsWith(partialId + ':') &&
cmdIdSplit.length === depth + 1 &&
!nextArgs.includes(cmdIdSplit[depth])
) {
node[cmdIdSplit[depth]] = {
_command: c.id,
}
}
}
return node
}
const commandTree: Record<string, any> = {}
const topLevelArgs: string[] = []
// Collect top-level topics and generate a cmd tree node for each one of them.
for (const t of this.topics) {
if (!t.name.includes(':')) {
commandTree[t.name] = this.coTopics.includes(t.name)
? {
...genNode(t.name),
}
: {
_summary: t.description,
...genNode(t.name),
}
topLevelArgs.push(t.name)
}
}
// Collect top-level commands and add a cmd tree node with the command ID.
for (const c of this.commands) {
if (!c.id.includes(':') && !this.coTopics.includes(c.id)) {
commandTree[c.id] = {
_command: c.id,
}
topLevelArgs.push(c.id)
}
}
const hashtables: string[] = []
for (const topLevelArg of topLevelArgs) {
// Generate all the hashtables for each child node of a top-level arg.
hashtables.push(this.genHashtable(topLevelArg, commandTree))
}
const commandsHashtable = `
@{
${hashtables.join('\n')}
}`
const compRegister = `
using namespace System.Management.Automation
using namespace System.Management.Automation.Language
$scriptblock = {
param($WordToComplete, $CommandAst, $CursorPosition)
$Commands =${commandsHashtable}
# Get the current mode
$Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function
# Everything in the current line except the CLI executable name.
$CurrentLine = $commandAst.CommandElements[1..$commandAst.CommandElements.Count] -split " "
# Remove $WordToComplete from the current line.
if ($WordToComplete -ne "") {
if ($CurrentLine.Count -eq 1) {
$CurrentLine = @()
} else {
$CurrentLine = $CurrentLine[0..$CurrentLine.Count]
}
}
# Save flags in current line without the \`--\` prefix.
$Flags = $CurrentLine | Where-Object {
$_ -Match "^-{1,2}(\\w+)"
} | ForEach-Object {
$_.trim("-")
}
# Set $flags to an empty hashtable if there are no flags in the current line.
if ($Flags -eq $null) {
$Flags = @{}
}
# No command in the current line, suggest top-level args.
if ($CurrentLine.Count -eq 0) {
$Commands.GetEnumerator() | Where-Object {
$_.Key.StartsWith("$WordToComplete")
} | Sort-Object -Property key | ForEach-Object {
New-Object -Type CompletionResult -ArgumentList \`
$($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"),
$_.Key,
"ParameterValue",
"$($_.Value._summary ?? $_.Value._command.summary ?? " ")"
}
} else {
# Start completing command/topic/coTopic
$NextArg = $null
$PrevNode = $null
# Iterate over the current line to find the command/topic/coTopic hashtable
$CurrentLine | ForEach-Object {
if ($NextArg -eq $null) {
$NextArg = $Commands[$_]
} elseif ($PrevNode[$_] -ne $null) {
$NextArg = $PrevNode[$_]
} elseif ($_.StartsWith('-')) {
return
} else {
$NextArg = $PrevNode
}
$PrevNode = $NextArg
}
# Start completing command.
if ($NextArg._command -ne $null) {
# Complete flags
# \`cli config list -<TAB>\`
if ($WordToComplete -like '-*') {
$NextArg._command.flags.GetEnumerator() | Sort-Object -Property key
| Where-Object {
# Filter out already used flags (unless \`flag.multiple = true\`).
$_.Key.StartsWith("$($WordToComplete.Trim("-"))") -and ($_.Value.multiple -eq $true -or !$flags.Contains($_.Key))
}
| ForEach-Object {
New-Object -Type CompletionResult -ArgumentList \`
$($Mode -eq "MenuComplete" ? "--$($_.Key) " : "--$($_.Key)"),
$_.Key,
"ParameterValue",
"$($NextArg._command.flags[$_.Key].summary ?? " ")"
}
} else {
# This could be a coTopic. We remove the "_command" hashtable
# from $NextArg and check if there's a command under the current partial ID.
$NextArg.remove("_command")
if ($NextArg.keys -gt 0) {
$NextArg.GetEnumerator() | Where-Object {
$_.Key.StartsWith("$WordToComplete")
} | Sort-Object -Property key | ForEach-Object {
New-Object -Type CompletionResult -ArgumentList \`
$($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"),
$_.Key,
"ParameterValue",
"$($NextArg[$_.Key]._summary ?? " ")"
}
}
}
} else {
# Start completing topic.
# Topic summary is stored as "_summary" in the hashtable.
# At this stage it is no longer needed so we remove it
# so that $NextArg contains only commands/topics hashtables
$NextArg.remove("_summary")
$NextArg.GetEnumerator() | Where-Object {
$_.Key.StartsWith("$WordToComplete")
} | Sort-Object -Property key | ForEach-Object {
New-Object -Type CompletionResult -ArgumentList \`
$($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"),
$_.Key,
"ParameterValue",
"$($NextArg[$_.Key]._summary ?? $NextArg[$_.Key]._command.summary ?? " ")"
}
}
}
}
Register-ArgumentCompleter -Native -CommandName ${
this.config.binAliases
? `@(${[...this.config.binAliases, this.config.bin].map((alias) => `"${alias}"`).join(',')})`
: this.config.bin
} -ScriptBlock $scriptblock
`
return compRegister
}
private genCmdHashtable(cmd: CommandCompletion): string {
const flaghHashtables: string[] = []
const flagNames = Object.keys(cmd.flags)
// Add comp for the global `--help` flag.
if (!flagNames.includes('help')) {
flaghHashtables.push(' "help" = @{ "summary" = "Show help for command" }')
}
if (flagNames.length > 0) {
for (const flagName of flagNames) {
const f = cmd.flags[flagName]
// skip hidden flags
if (f.hidden) continue
const flagSummary = this.sanitizeSummary(f.summary ?? f.description)
if (f.type === 'option' && f.multiple) {
flaghHashtables.push(
` "${f.name}" = @{
"summary" = "${flagSummary}"
"multiple" = $true
}`,
)
} else {
flaghHashtables.push(` "${f.name}" = @{ "summary" = "${flagSummary}" }`)
}
// Add flag aliases
const aliases = (f as any).aliases as string[] | undefined
if (aliases && aliases.length > 0) {
for (const alias of aliases) {
if (f.type === 'option' && f.multiple) {
flaghHashtables.push(
` "${alias}" = @{
"summary" = "${flagSummary}"
"multiple" = $true
}`,
)
} else {
flaghHashtables.push(` "${alias}" = @{ "summary" = "${flagSummary}" }`)
}
}
}
}
}
const cmdHashtable = `@{
"summary" = "${cmd.summary}"
"flags" = @{
${flaghHashtables.join('\n')}
}
}`
return cmdHashtable
}
private genHashtable(key: string, node: Record<string, any>, leafTpl?: string): string {
if (!leafTpl) {
leafTpl = `"${key}" = @{
%s
}
`
}
const nodeKeys = Object.keys(node[key])
// this is a topic
if (nodeKeys.includes('_summary')) {
let childTpl = `"_summary" = "${node[key]._summary}"\n%s`
const newKeys = nodeKeys.filter((k) => k !== '_summary')
if (newKeys.length > 0) {
const childNodes: string[] = []
for (const newKey of newKeys) {
childNodes.push(this.genHashtable(newKey, node[key]))
}
childTpl = format(childTpl, childNodes.join('\n'))
return format(leafTpl, childTpl)
}
// last node
return format(leafTpl, childTpl)
}
const childNodes: string[] = []
for (const k of nodeKeys) {
if (k === '_command') {
const cmd = this.commands.find((c) => c.id === node[key][k])
if (!cmd) throw new Error('no command')
childNodes.push(format('"_command" = %s', this.genCmdHashtable(cmd)))
} else if (node[key][k]._command) {
const cmd = this.commands.find((c) => c.id === node[key][k]._command)
if (!cmd) throw new Error('no command')
childNodes.push(format(`"${k}" = @{\n"_command" = %s\n}`, this.genCmdHashtable(cmd)))
} else {
const childTpl = `"summary" = "${node[key][k]._summary}"\n"${k}" = @{ \n %s\n }`
childNodes.push(this.genHashtable(k, node[key], childTpl))
}
}
if (childNodes.length > 0) {
return format(leafTpl, childNodes.join('\n'))
}
return leafTpl
}
private getCommands(): CommandCompletion[] {
const cmds: CommandCompletion[] = []
for (const p of this.config.getPluginsList()) {
for (const c of p.commands) {
if (c.hidden) continue
const summary = this.sanitizeSummary(c.summary ?? c.description)
const {flags} = c
cmds.push({
flags,
id: c.id,
summary,
})
for (const a of c.aliases) {
cmds.push({
flags,
id: a,
summary,
})
const split = a.split(':')
let topic = split[0]
// Completion funcs are generated from topics:
// `force` -> `force:org` -> `force:org:open|list`
//
// but aliases aren't guaranteed to follow the plugin command tree
// so we need to add any missing topic between the starting point and the alias.
for (let i = 0; i < split.length - 1; i++) {
if (!this.topics.some((t) => t.name === topic)) {
this.topics.push({
description: `${topic.replaceAll(':', ' ')} commands`,
name: topic,
})
}
topic += `:${split[i + 1]}`
}
}
}
}
return cmds
}
private getTopics(): Topic[] {
const topics = this.config.topics
.filter((topic: Interfaces.Topic) => {
// it is assumed a topic has a child if it has children
const hasChild = this.config.topics.some((subTopic) => subTopic.name.includes(`${topic.name}:`))
return hasChild
})
.sort((a, b) => {
if (a.name < b.name) {
return -1
}
if (a.name > b.name) {
return 1
}
return 0
})
.map((t) => {
const description = t.description
? this.sanitizeSummary(t.description)
: `${t.name.replaceAll(':', ' ')} commands`
return {
description,
name: t.name,
}
})
return topics
}
private sanitizeSummary(summary?: string): string {
if (summary === undefined) {
// PowerShell:
// [System.Management.Automation.CompletionResult] will error out if will error out if you pass in an empty string for the summary.
return ' '
}
return ejs
.render(summary, {config: this.config})
.replaceAll('"', '""') // escape double quotes.
.replaceAll('`', '``') // escape backticks.
.split(EOL)[0] // only use the first line
}
}