UNPKG

14.4 kBJavaScriptView Raw
1import * as ejs from 'ejs';
2import { EOL } from 'node:os';
3import * as util from 'node:util';
4export default class PowerShellComp {
5 config;
6 _coTopics;
7 commands;
8 topics;
9 constructor(config) {
10 this.config = config;
11 this.topics = this.getTopics();
12 this.commands = this.getCommands();
13 }
14 generate() {
15 const genNode = (partialId) => {
16 const node = {};
17 const nextArgs = [];
18 const depth = partialId.split(':').length;
19 for (const t of this.topics) {
20 const topicNameSplit = t.name.split(':');
21 if (t.name.startsWith(partialId + ':') && topicNameSplit.length === depth + 1) {
22 nextArgs.push(topicNameSplit[depth]);
23 node[topicNameSplit[depth]] = this.coTopics.includes(t.name)
24 ? {
25 ...genNode(`${partialId}:${topicNameSplit[depth]}`),
26 }
27 : {
28 _summary: t.description,
29 ...genNode(`${partialId}:${topicNameSplit[depth]}`),
30 };
31 }
32 }
33 for (const c of this.commands) {
34 const cmdIdSplit = c.id.split(':');
35 if (partialId === c.id && this.coTopics.includes(c.id)) {
36 node._command = c.id;
37 }
38 if (c.id.startsWith(partialId + ':') &&
39 cmdIdSplit.length === depth + 1 &&
40 !nextArgs.includes(cmdIdSplit[depth])) {
41 node[cmdIdSplit[depth]] = {
42 _command: c.id,
43 };
44 }
45 }
46 return node;
47 };
48 const commandTree = {};
49 const topLevelArgs = [];
50 // Collect top-level topics and generate a cmd tree node for each one of them.
51 for (const t of this.topics) {
52 if (!t.name.includes(':')) {
53 commandTree[t.name] = this.coTopics.includes(t.name)
54 ? {
55 ...genNode(t.name),
56 }
57 : {
58 _summary: t.description,
59 ...genNode(t.name),
60 };
61 topLevelArgs.push(t.name);
62 }
63 }
64 // Collect top-level commands and add a cmd tree node with the command ID.
65 for (const c of this.commands) {
66 if (!c.id.includes(':') && !this.coTopics.includes(c.id)) {
67 commandTree[c.id] = {
68 _command: c.id,
69 };
70 topLevelArgs.push(c.id);
71 }
72 }
73 const hashtables = [];
74 for (const topLevelArg of topLevelArgs) {
75 // Generate all the hashtables for each child node of a top-level arg.
76 hashtables.push(this.genHashtable(topLevelArg, commandTree));
77 }
78 const commandsHashtable = `
79@{
80${hashtables.join('\n')}
81}`;
82 const compRegister = `
83using namespace System.Management.Automation
84using namespace System.Management.Automation.Language
85
86$scriptblock = {
87 param($WordToComplete, $CommandAst, $CursorPosition)
88
89 $Commands =${commandsHashtable}
90
91 # Get the current mode
92 $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function
93
94 # Everything in the current line except the CLI executable name.
95 $CurrentLine = $commandAst.CommandElements[1..$commandAst.CommandElements.Count] -split " "
96
97 # Remove $WordToComplete from the current line.
98 if ($WordToComplete -ne "") {
99 if ($CurrentLine.Count -eq 1) {
100 $CurrentLine = @()
101 } else {
102 $CurrentLine = $CurrentLine[0..$CurrentLine.Count]
103 }
104 }
105
106 # Save flags in current line without the \`--\` prefix.
107 $Flags = $CurrentLine | Where-Object {
108 $_ -Match "^-{1,2}(\\w+)"
109 } | ForEach-Object {
110 $_.trim("-")
111 }
112 # Set $flags to an empty hashtable if there are no flags in the current line.
113 if ($Flags -eq $null) {
114 $Flags = @{}
115 }
116
117 # No command in the current line, suggest top-level args.
118 if ($CurrentLine.Count -eq 0) {
119 $Commands.GetEnumerator() | Where-Object {
120 $_.Key.StartsWith("$WordToComplete")
121 } | Sort-Object -Property key | ForEach-Object {
122 New-Object -Type CompletionResult -ArgumentList \`
123 $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"),
124 $_.Key,
125 "ParameterValue",
126 "$($_.Value._summary ?? $_.Value._command.summary ?? " ")"
127 }
128 } else {
129 # Start completing command/topic/coTopic
130
131 $NextArg = $null
132 $PrevNode = $null
133
134 # Iterate over the current line to find the command/topic/coTopic hashtable
135 $CurrentLine | ForEach-Object {
136 if ($NextArg -eq $null) {
137 $NextArg = $Commands[$_]
138 } elseif ($PrevNode[$_] -ne $null) {
139 $NextArg = $PrevNode[$_]
140 } elseif ($_.StartsWith('-')) {
141 return
142 } else {
143 $NextArg = $PrevNode
144 }
145
146 $PrevNode = $NextArg
147 }
148
149 # Start completing command.
150 if ($NextArg._command -ne $null) {
151 # Complete flags
152 # \`cli config list -<TAB>\`
153 if ($WordToComplete -like '-*') {
154 $NextArg._command.flags.GetEnumerator() | Sort-Object -Property key
155 | Where-Object {
156 # Filter out already used flags (unless \`flag.multiple = true\`).
157 $_.Key.StartsWith("$($WordToComplete.Trim("-"))") -and ($_.Value.multiple -eq $true -or !$flags.Contains($_.Key))
158 }
159 | ForEach-Object {
160 New-Object -Type CompletionResult -ArgumentList \`
161 $($Mode -eq "MenuComplete" ? "--$($_.Key) " : "--$($_.Key)"),
162 $_.Key,
163 "ParameterValue",
164 "$($NextArg._command.flags[$_.Key].summary ?? " ")"
165 }
166 } else {
167 # This could be a coTopic. We remove the "_command" hashtable
168 # from $NextArg and check if there's a command under the current partial ID.
169 $NextArg.remove("_command")
170
171 if ($NextArg.keys -gt 0) {
172 $NextArg.GetEnumerator() | Where-Object {
173 $_.Key.StartsWith("$WordToComplete")
174 } | Sort-Object -Property key | ForEach-Object {
175 New-Object -Type CompletionResult -ArgumentList \`
176 $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"),
177 $_.Key,
178 "ParameterValue",
179 "$($NextArg[$_.Key]._summary ?? " ")"
180 }
181 }
182 }
183 } else {
184 # Start completing topic.
185
186 # Topic summary is stored as "_summary" in the hashtable.
187 # At this stage it is no longer needed so we remove it
188 # so that $NextArg contains only commands/topics hashtables
189
190 $NextArg.remove("_summary")
191
192 $NextArg.GetEnumerator() | Where-Object {
193 $_.Key.StartsWith("$WordToComplete")
194 } | Sort-Object -Property key | ForEach-Object {
195 New-Object -Type CompletionResult -ArgumentList \`
196 $($Mode -eq "MenuComplete" ? "$($_.Key) " : "$($_.Key)"),
197 $_.Key,
198 "ParameterValue",
199 "$($NextArg[$_.Key]._summary ?? $NextArg[$_.Key]._command.summary ?? " ")"
200 }
201 }
202 }
203}
204Register-ArgumentCompleter -Native -CommandName ${this.config.binAliases
205 ? `@(${[...this.config.binAliases, this.config.bin].map((alias) => `"${alias}"`).join(',')})`
206 : this.config.bin} -ScriptBlock $scriptblock
207`;
208 return compRegister;
209 }
210 get coTopics() {
211 if (this._coTopics)
212 return this._coTopics;
213 const coTopics = [];
214 for (const topic of this.topics) {
215 for (const cmd of this.commands) {
216 if (topic.name === cmd.id) {
217 coTopics.push(topic.name);
218 }
219 }
220 }
221 this._coTopics = coTopics;
222 return this._coTopics;
223 }
224 genCmdHashtable(cmd) {
225 const flaghHashtables = [];
226 const flagNames = Object.keys(cmd.flags);
227 // Add comp for the global `--help` flag.
228 if (!flagNames.includes('help')) {
229 flaghHashtables.push(' "help" = @{ "summary" = "Show help for command" }');
230 }
231 if (flagNames.length > 0) {
232 for (const flagName of flagNames) {
233 const f = cmd.flags[flagName];
234 // skip hidden flags
235 if (f.hidden)
236 continue;
237 const flagSummary = this.sanitizeSummary(f.summary ?? f.description);
238 if (f.type === 'option' && f.multiple) {
239 flaghHashtables.push(` "${f.name}" = @{
240 "summary" = "${flagSummary}"
241 "multiple" = $true
242}`);
243 }
244 else {
245 flaghHashtables.push(` "${f.name}" = @{ "summary" = "${flagSummary}" }`);
246 }
247 }
248 }
249 const cmdHashtable = `@{
250 "summary" = "${cmd.summary}"
251 "flags" = @{
252${flaghHashtables.join('\n')}
253 }
254}`;
255 return cmdHashtable;
256 }
257 genHashtable(key, node, leafTpl) {
258 if (!leafTpl) {
259 leafTpl = `"${key}" = @{
260%s
261}
262`;
263 }
264 const nodeKeys = Object.keys(node[key]);
265 // this is a topic
266 if (nodeKeys.includes('_summary')) {
267 let childTpl = `"_summary" = "${node[key]._summary}"\n%s`;
268 const newKeys = nodeKeys.filter((k) => k !== '_summary');
269 if (newKeys.length > 0) {
270 const childNodes = [];
271 for (const newKey of newKeys) {
272 childNodes.push(this.genHashtable(newKey, node[key]));
273 }
274 childTpl = util.format(childTpl, childNodes.join('\n'));
275 return util.format(leafTpl, childTpl);
276 }
277 // last node
278 return util.format(leafTpl, childTpl);
279 }
280 const childNodes = [];
281 for (const k of nodeKeys) {
282 if (k === '_command') {
283 const cmd = this.commands.find((c) => c.id === node[key][k]);
284 if (!cmd)
285 throw new Error('no command');
286 childNodes.push(util.format('"_command" = %s', this.genCmdHashtable(cmd)));
287 }
288 else if (node[key][k]._command) {
289 const cmd = this.commands.find((c) => c.id === node[key][k]._command);
290 if (!cmd)
291 throw new Error('no command');
292 childNodes.push(util.format(`"${k}" = @{\n"_command" = %s\n}`, this.genCmdHashtable(cmd)));
293 }
294 else {
295 const childTpl = `"summary" = "${node[key][k]._summary}"\n"${k}" = @{ \n %s\n }`;
296 childNodes.push(this.genHashtable(k, node[key], childTpl));
297 }
298 }
299 if (childNodes.length > 0) {
300 return util.format(leafTpl, childNodes.join('\n'));
301 }
302 return leafTpl;
303 }
304 getCommands() {
305 const cmds = [];
306 for (const p of this.config.getPluginsList()) {
307 for (const c of p.commands) {
308 if (c.hidden)
309 continue;
310 const summary = this.sanitizeSummary(c.summary ?? c.description);
311 const { flags } = c;
312 cmds.push({
313 flags,
314 id: c.id,
315 summary,
316 });
317 for (const a of c.aliases) {
318 cmds.push({
319 flags,
320 id: a,
321 summary,
322 });
323 const split = a.split(':');
324 let topic = split[0];
325 // Completion funcs are generated from topics:
326 // `force` -> `force:org` -> `force:org:open|list`
327 //
328 // but aliases aren't guaranteed to follow the plugin command tree
329 // so we need to add any missing topic between the starting point and the alias.
330 for (let i = 0; i < split.length - 1; i++) {
331 if (!this.topics.some((t) => t.name === topic)) {
332 this.topics.push({
333 description: `${topic.replaceAll(':', ' ')} commands`,
334 name: topic,
335 });
336 }
337 topic += `:${split[i + 1]}`;
338 }
339 }
340 }
341 }
342 return cmds;
343 }
344 getTopics() {
345 const topics = this.config.topics
346 .filter((topic) => {
347 // it is assumed a topic has a child if it has children
348 const hasChild = this.config.topics.some((subTopic) => subTopic.name.includes(`${topic.name}:`));
349 return hasChild;
350 })
351 .sort((a, b) => {
352 if (a.name < b.name) {
353 return -1;
354 }
355 if (a.name > b.name) {
356 return 1;
357 }
358 return 0;
359 })
360 .map((t) => {
361 const description = t.description
362 ? this.sanitizeSummary(t.description)
363 : `${t.name.replaceAll(':', ' ')} commands`;
364 return {
365 description,
366 name: t.name,
367 };
368 });
369 return topics;
370 }
371 sanitizeSummary(summary) {
372 if (summary === undefined) {
373 // PowerShell:
374 // [System.Management.Automation.CompletionResult] will error out if will error out if you pass in an empty string for the summary.
375 return ' ';
376 }
377 return ejs
378 .render(summary, { config: this.config })
379 .replaceAll('"', '""') // escape double quotes.
380 .replaceAll('`', '``') // escape backticks.
381 .split(EOL)[0]; // only use the first line
382 }
383}