@bomb.sh/tab 0.0.1-pre.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1054 @@
1
+ import assert from "node:assert";
2
+
3
+ //#region src/zsh.ts
4
+ function generate$3(name, exec) {
5
+ return `#compdef ${name}
6
+ compdef _${name} ${name}
7
+
8
+ # zsh completion for ${name} -*- shell-script -*-
9
+
10
+ __${name}_debug() {
11
+ local file="$BASH_COMP_DEBUG_FILE"
12
+ if [[ -n \${file} ]]; then
13
+ echo "$*" >> "\${file}"
14
+ fi
15
+ }
16
+
17
+ _${name}() {
18
+ local shellCompDirectiveError=${ShellCompDirective.ShellCompDirectiveError}
19
+ local shellCompDirectiveNoSpace=${ShellCompDirective.ShellCompDirectiveNoSpace}
20
+ local shellCompDirectiveNoFileComp=${ShellCompDirective.ShellCompDirectiveNoFileComp}
21
+ local shellCompDirectiveFilterFileExt=${ShellCompDirective.ShellCompDirectiveFilterFileExt}
22
+ local shellCompDirectiveFilterDirs=${ShellCompDirective.ShellCompDirectiveFilterDirs}
23
+ local shellCompDirectiveKeepOrder=${ShellCompDirective.ShellCompDirectiveKeepOrder}
24
+
25
+ local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder
26
+ local -a completions
27
+
28
+ __${name}_debug "\\n========= starting completion logic =========="
29
+ __${name}_debug "CURRENT: \${CURRENT}, words[*]: \${words[*]}"
30
+
31
+ # The user could have moved the cursor backwards on the command-line.
32
+ # We need to trigger completion from the $CURRENT location, so we need
33
+ # to truncate the command-line ($words) up to the $CURRENT location.
34
+ # (We cannot use $CURSOR as its value does not work when a command is an alias.)
35
+ words=( "\${=words[1,CURRENT]}" )
36
+ __${name}_debug "Truncated words[*]: \${words[*]},"
37
+
38
+ lastParam=\${words[-1]}
39
+ lastChar=\${lastParam[-1]}
40
+ __${name}_debug "lastParam: \${lastParam}, lastChar: \${lastChar}"
41
+
42
+ # For zsh, when completing a flag with an = (e.g., ${name} -n=<TAB>)
43
+ # completions must be prefixed with the flag
44
+ setopt local_options BASH_REMATCH
45
+ if [[ "\${lastParam}" =~ '-.*=' ]]; then
46
+ # We are dealing with a flag with an =
47
+ flagPrefix="-P \${BASH_REMATCH}"
48
+ fi
49
+
50
+ # Prepare the command to obtain completions, ensuring arguments are quoted for eval
51
+ local -a args_to_quote=("\${(@)words[2,-1]}")
52
+ if [ "\${lastChar}" = "" ]; then
53
+ # If the last parameter is complete (there is a space following it)
54
+ # We add an extra empty parameter so we can indicate this to the go completion code.
55
+ __${name}_debug "Adding extra empty parameter"
56
+ args_to_quote+=("")
57
+ fi
58
+
59
+ # Use Zsh's (q) flag to quote each argument safely for eval
60
+ local quoted_args=("\${(@q)args_to_quote}")
61
+
62
+ # Join the main command and the quoted arguments into a single string for eval
63
+ requestComp="${exec} complete -- \${quoted_args[*]}"
64
+
65
+ __${name}_debug "About to call: eval \${requestComp}"
66
+
67
+ # Use eval to handle any environment variables and such
68
+ out=$(eval \${requestComp} 2>/dev/null)
69
+ __${name}_debug "completion output: \${out}"
70
+
71
+ # Extract the directive integer following a : from the last line
72
+ local lastLine
73
+ while IFS='\n' read -r line; do
74
+ lastLine=\${line}
75
+ done < <(printf "%s\n" "\${out[@]}")
76
+ __${name}_debug "last line: \${lastLine}"
77
+
78
+ if [ "\${lastLine[1]}" = : ]; then
79
+ directive=\${lastLine[2,-1]}
80
+ # Remove the directive including the : and the newline
81
+ local suffix
82
+ (( suffix=\${#lastLine}+2))
83
+ out=\${out[1,-$suffix]}
84
+ else
85
+ # There is no directive specified. Leave $out as is.
86
+ __${name}_debug "No directive found. Setting to default"
87
+ directive=0
88
+ fi
89
+
90
+ __${name}_debug "directive: \${directive}"
91
+ __${name}_debug "completions: \${out}"
92
+ __${name}_debug "flagPrefix: \${flagPrefix}"
93
+
94
+ if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then
95
+ __${name}_debug "Completion received error. Ignoring completions."
96
+ return
97
+ fi
98
+
99
+ local activeHelpMarker="%"
100
+ local endIndex=\${#activeHelpMarker}
101
+ local startIndex=$((\${#activeHelpMarker}+1))
102
+ local hasActiveHelp=0
103
+ while IFS='\n' read -r comp; do
104
+ # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)
105
+ if [ "\${comp[1,$endIndex]}" = "$activeHelpMarker" ];then
106
+ __${name}_debug "ActiveHelp found: $comp"
107
+ comp="\${comp[$startIndex,-1]}"
108
+ if [ -n "$comp" ]; then
109
+ compadd -x "\${comp}"
110
+ __${name}_debug "ActiveHelp will need delimiter"
111
+ hasActiveHelp=1
112
+ fi
113
+ continue
114
+ fi
115
+
116
+ if [ -n "$comp" ]; then
117
+ # If requested, completions are returned with a description.
118
+ # The description is preceded by a TAB character.
119
+ # For zsh's _describe, we need to use a : instead of a TAB.
120
+ # We first need to escape any : as part of the completion itself.
121
+ comp=\${comp//:/\\:}
122
+
123
+ local tab="$(printf '\\t')"
124
+ comp=\${comp//$tab/:}
125
+
126
+ __${name}_debug "Adding completion: \${comp}"
127
+ completions+=\${comp}
128
+ lastComp=$comp
129
+ fi
130
+ done < <(printf "%s\n" "\${out[@]}")
131
+
132
+ # Add a delimiter after the activeHelp statements, but only if:
133
+ # - there are completions following the activeHelp statements, or
134
+ # - file completion will be performed (so there will be choices after the activeHelp)
135
+ if [ $hasActiveHelp -eq 1 ]; then
136
+ if [ \${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then
137
+ __${name}_debug "Adding activeHelp delimiter"
138
+ compadd -x "--"
139
+ hasActiveHelp=0
140
+ fi
141
+ fi
142
+
143
+ if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then
144
+ __${name}_debug "Activating nospace."
145
+ noSpace="-S ''"
146
+ fi
147
+
148
+ if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then
149
+ __${name}_debug "Activating keep order."
150
+ keepOrder="-V"
151
+ fi
152
+
153
+ if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then
154
+ # File extension filtering
155
+ local filteringCmd
156
+ filteringCmd='_files'
157
+ for filter in \${completions[@]}; do
158
+ if [ \${filter[1]} != '*' ]; then
159
+ # zsh requires a glob pattern to do file filtering
160
+ filter="\\*.$filter"
161
+ fi
162
+ filteringCmd+=" -g $filter"
163
+ done
164
+ filteringCmd+=" \${flagPrefix}"
165
+
166
+ __${name}_debug "File filtering command: $filteringCmd"
167
+ _arguments '*:filename:'"$filteringCmd"
168
+ elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then
169
+ # File completion for directories only
170
+ local subdir
171
+ subdir="\${completions[1]}"
172
+ if [ -n "$subdir" ]; then
173
+ __${name}_debug "Listing directories in $subdir"
174
+ pushd "\${subdir}" >/dev/null 2>&1
175
+ else
176
+ __${name}_debug "Listing directories in ."
177
+ fi
178
+
179
+ local result
180
+ _arguments '*:dirname:_files -/'" \${flagPrefix}"
181
+ result=$?
182
+ if [ -n "$subdir" ]; then
183
+ popd >/dev/null 2>&1
184
+ fi
185
+ return $result
186
+ else
187
+ __${name}_debug "Calling _describe"
188
+ if eval _describe $keepOrder "completions" completions -Q \${flagPrefix} \${noSpace}; then
189
+ __${name}_debug "_describe found some completions"
190
+
191
+ # Return the success of having called _describe
192
+ return 0
193
+ else
194
+ __${name}_debug "_describe did not find completions."
195
+ __${name}_debug "Checking if we should do file completion."
196
+ if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then
197
+ __${name}_debug "deactivating file completion"
198
+
199
+ # We must return an error code here to let zsh know that there were no
200
+ # completions found by _describe; this is what will trigger other
201
+ # matching algorithms to attempt to find completions.
202
+ # For example zsh can match letters in the middle of words.
203
+ return 1
204
+ else
205
+ # Perform file completion
206
+ __${name}_debug "Activating file completion"
207
+
208
+ # We must return the result of this command, so it must be the
209
+ # last command, or else we must store its result to return it.
210
+ _arguments '*:filename:_files'" \${flagPrefix}"
211
+ fi
212
+ fi
213
+ fi
214
+ }
215
+
216
+ # don't run the completion function when being sourced or eval-ed
217
+ if [ "\${funcstack[1]}" = "_${name}" ]; then
218
+ _${name}
219
+ fi
220
+ `;
221
+ }
222
+
223
+ //#endregion
224
+ //#region src/bash.ts
225
+ function generate$2(name, exec) {
226
+ const nameForVar = name.replace(/[-:]/g, "_");
227
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
228
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
229
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
230
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
231
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
232
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
233
+ return `# bash completion for ${name}
234
+
235
+ # Define shell completion directives
236
+ readonly ShellCompDirectiveError=${ShellCompDirectiveError}
237
+ readonly ShellCompDirectiveNoSpace=${ShellCompDirectiveNoSpace}
238
+ readonly ShellCompDirectiveNoFileComp=${ShellCompDirectiveNoFileComp}
239
+ readonly ShellCompDirectiveFilterFileExt=${ShellCompDirectiveFilterFileExt}
240
+ readonly ShellCompDirectiveFilterDirs=${ShellCompDirectiveFilterDirs}
241
+ readonly ShellCompDirectiveKeepOrder=${ShellCompDirectiveKeepOrder}
242
+
243
+ # Function to debug completion
244
+ __${nameForVar}_debug() {
245
+ if [[ -n \${BASH_COMP_DEBUG_FILE:-} ]]; then
246
+ echo "$*" >> "\${BASH_COMP_DEBUG_FILE}"
247
+ fi
248
+ }
249
+
250
+ # Function to handle completions
251
+ __${nameForVar}_complete() {
252
+ local cur prev words cword
253
+ _get_comp_words_by_ref -n "=:" cur prev words cword
254
+
255
+ local requestComp out directive
256
+
257
+ # Build the command to get completions
258
+ requestComp="${exec} complete -- \${words[@]:1}"
259
+
260
+ # Add an empty parameter if the last parameter is complete
261
+ if [[ -z "$cur" ]]; then
262
+ requestComp="$requestComp ''"
263
+ fi
264
+
265
+ # Get completions from the program
266
+ out=$(eval "$requestComp" 2>/dev/null)
267
+
268
+ # Extract directive if present
269
+ directive=0
270
+ if [[ "$out" == *:* ]]; then
271
+ directive=\${out##*:}
272
+ out=\${out%:*}
273
+ fi
274
+
275
+ # Process completions based on directive
276
+ if [[ $((directive & $ShellCompDirectiveError)) -ne 0 ]]; then
277
+ # Error, no completion
278
+ return
279
+ fi
280
+
281
+ # Apply directives
282
+ if [[ $((directive & $ShellCompDirectiveNoSpace)) -ne 0 ]]; then
283
+ compopt -o nospace
284
+ fi
285
+ if [[ $((directive & $ShellCompDirectiveKeepOrder)) -ne 0 ]]; then
286
+ compopt -o nosort
287
+ fi
288
+ if [[ $((directive & $ShellCompDirectiveNoFileComp)) -ne 0 ]]; then
289
+ compopt +o default
290
+ fi
291
+
292
+ # Handle file extension filtering
293
+ if [[ $((directive & $ShellCompDirectiveFilterFileExt)) -ne 0 ]]; then
294
+ local filter=""
295
+ for ext in $out; do
296
+ filter="$filter|$ext"
297
+ done
298
+ filter="\\.($filter)"
299
+ compopt -o filenames
300
+ COMPREPLY=( $(compgen -f -X "!$filter" -- "$cur") )
301
+ return
302
+ fi
303
+
304
+ # Handle directory filtering
305
+ if [[ $((directive & $ShellCompDirectiveFilterDirs)) -ne 0 ]]; then
306
+ compopt -o dirnames
307
+ COMPREPLY=( $(compgen -d -- "$cur") )
308
+ return
309
+ fi
310
+
311
+ # Process completions
312
+ local IFS=$'\\n'
313
+ local tab=$(printf '\\t')
314
+
315
+ # Parse completions with descriptions
316
+ local completions=()
317
+ while read -r comp; do
318
+ if [[ "$comp" == *$tab* ]]; then
319
+ # Split completion and description
320
+ local value=\${comp%%$tab*}
321
+ local desc=\${comp#*$tab}
322
+ completions+=("$value")
323
+ else
324
+ completions+=("$comp")
325
+ fi
326
+ done <<< "$out"
327
+
328
+ # Return completions
329
+ COMPREPLY=( $(compgen -W "\${completions[*]}" -- "$cur") )
330
+ }
331
+
332
+ # Register completion function
333
+ complete -F __${nameForVar}_complete ${name}
334
+ `;
335
+ }
336
+
337
+ //#endregion
338
+ //#region src/fish.ts
339
+ function generate$1(name, exec) {
340
+ const nameForVar = name.replace(/[-:]/g, "_");
341
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
342
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
343
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
344
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
345
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
346
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
347
+ return `# fish completion for ${name} -*- shell-script -*-
348
+
349
+ # Define shell completion directives
350
+ set -l ShellCompDirectiveError ${ShellCompDirectiveError}
351
+ set -l ShellCompDirectiveNoSpace ${ShellCompDirectiveNoSpace}
352
+ set -l ShellCompDirectiveNoFileComp ${ShellCompDirectiveNoFileComp}
353
+ set -l ShellCompDirectiveFilterFileExt ${ShellCompDirectiveFilterFileExt}
354
+ set -l ShellCompDirectiveFilterDirs ${ShellCompDirectiveFilterDirs}
355
+ set -l ShellCompDirectiveKeepOrder ${ShellCompDirectiveKeepOrder}
356
+
357
+ function __${nameForVar}_debug
358
+ set -l file "$BASH_COMP_DEBUG_FILE"
359
+ if test -n "$file"
360
+ echo "$argv" >> $file
361
+ end
362
+ end
363
+
364
+ function __${nameForVar}_perform_completion
365
+ __${nameForVar}_debug "Starting __${nameForVar}_perform_completion"
366
+
367
+ # Extract all args except the completion flag
368
+ set -l args (string match -v -- "--completion=" (commandline -opc))
369
+
370
+ # Extract the current token being completed
371
+ set -l current_token (commandline -ct)
372
+
373
+ # Check if current token starts with a dash
374
+ set -l flag_prefix ""
375
+ if string match -q -- "-*" $current_token
376
+ set flag_prefix "--flag="
377
+ end
378
+
379
+ __${nameForVar}_debug "Current token: $current_token"
380
+ __${nameForVar}_debug "All args: $args"
381
+
382
+ # Call the completion program and get the results
383
+ set -l requestComp "${exec} complete -- $args"
384
+ __${nameForVar}_debug "Calling $requestComp"
385
+ set -l results (eval $requestComp 2> /dev/null)
386
+
387
+ # Some programs may output extra empty lines after the directive.
388
+ # Let's ignore them or else it will break completion.
389
+ # Ref: https://github.com/spf13/cobra/issues/1279
390
+ for line in $results[-1..1]
391
+ if test (string sub -s 1 -l 1 -- $line) = ":"
392
+ # The directive
393
+ set -l directive (string sub -s 2 -- $line)
394
+ set -l directive_num (math $directive)
395
+ break
396
+ end
397
+ end
398
+
399
+ # No directive specified, use default
400
+ if not set -q directive_num
401
+ set directive_num 0
402
+ end
403
+
404
+ __${nameForVar}_debug "Directive: $directive_num"
405
+
406
+ # Process completions based on directive
407
+ if test $directive_num -eq $ShellCompDirectiveError
408
+ # Error code. No completion.
409
+ __${nameForVar}_debug "Received error directive: aborting."
410
+ return 1
411
+ end
412
+
413
+ # Filter out the directive (last line)
414
+ if test (count $results) -gt 0 -a (string sub -s 1 -l 1 -- $results[-1]) = ":"
415
+ set results $results[1..-2]
416
+ end
417
+
418
+ # No completions, let fish handle file completions unless forbidden
419
+ if test (count $results) -eq 0
420
+ if test $directive_num -ne $ShellCompDirectiveNoFileComp
421
+ __${nameForVar}_debug "No completions, performing file completion"
422
+ return 1
423
+ end
424
+ __${nameForVar}_debug "No completions, but file completion forbidden"
425
+ return 0
426
+ end
427
+
428
+ # Filter file extensions
429
+ if test $directive_num -eq $ShellCompDirectiveFilterFileExt
430
+ __${nameForVar}_debug "File extension filtering"
431
+ set -l file_extensions
432
+ for item in $results
433
+ if test -n "$item" -a (string sub -s 1 -l 1 -- $item) != "-"
434
+ set -a file_extensions "*$item"
435
+ end
436
+ end
437
+ __${nameForVar}_debug "File extensions: $file_extensions"
438
+
439
+ # Use the file extensions as completions
440
+ set -l completions
441
+ for ext in $file_extensions
442
+ # Get all files matching the extension
443
+ set -a completions (string replace -r '^.*/' '' -- $ext)
444
+ end
445
+
446
+ for item in $completions
447
+ echo -e "$item\t"
448
+ end
449
+ return 0
450
+ end
451
+
452
+ # Filter directories
453
+ if test $directive_num -eq $ShellCompDirectiveFilterDirs
454
+ __${nameForVar}_debug "Directory filtering"
455
+ set -l dirs
456
+ for item in $results
457
+ if test -d "$item"
458
+ set -a dirs "$item/"
459
+ end
460
+ end
461
+
462
+ for item in $dirs
463
+ echo -e "$item\t"
464
+ end
465
+ return 0
466
+ end
467
+
468
+ # Process remaining completions
469
+ for item in $results
470
+ if test -n "$item"
471
+ # Check if the item has a description
472
+ if string match -q "*\t*" -- "$item"
473
+ set -l completion_parts (string split \t -- "$item")
474
+ set -l comp $completion_parts[1]
475
+ set -l desc $completion_parts[2]
476
+
477
+ # Add the completion and description
478
+ echo -e "$comp\t$desc"
479
+ else
480
+ # Add just the completion
481
+ echo -e "$item\t"
482
+ end
483
+ end
484
+ end
485
+
486
+ # If directive contains NoSpace, tell fish not to add a space after completion
487
+ if test (math "$directive_num & $ShellCompDirectiveNoSpace") -ne 0
488
+ return 2
489
+ end
490
+
491
+ return 0
492
+ end
493
+
494
+ # Set up the completion for the ${name} command
495
+ complete -c ${name} -f -a "(eval __${nameForVar}_perform_completion)"
496
+ `;
497
+ }
498
+
499
+ //#endregion
500
+ //#region src/powershell.ts
501
+ function generate(name, exec, includeDesc = false) {
502
+ const nameForVar = name.replace(/[-:]/g, "_");
503
+ const ShellCompDirectiveError = ShellCompDirective.ShellCompDirectiveError;
504
+ const ShellCompDirectiveNoSpace = ShellCompDirective.ShellCompDirectiveNoSpace;
505
+ const ShellCompDirectiveNoFileComp = ShellCompDirective.ShellCompDirectiveNoFileComp;
506
+ const ShellCompDirectiveFilterFileExt = ShellCompDirective.ShellCompDirectiveFilterFileExt;
507
+ const ShellCompDirectiveFilterDirs = ShellCompDirective.ShellCompDirectiveFilterDirs;
508
+ const ShellCompDirectiveKeepOrder = ShellCompDirective.ShellCompDirectiveKeepOrder;
509
+ return `# powershell completion for ${name} -*- shell-script -*-
510
+
511
+ [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
512
+ function __${name}_debug {
513
+ if ($env:BASH_COMP_DEBUG_FILE) {
514
+ "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
515
+ }
516
+ }
517
+
518
+ filter __${name}_escapeStringWithSpecialChars {
519
+ $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|"|\\||<|>|&','\`$&'
520
+ }
521
+
522
+ [scriptblock]$__${nameForVar}CompleterBlock = {
523
+ param(
524
+ $WordToComplete,
525
+ $CommandAst,
526
+ $CursorPosition
527
+ )
528
+
529
+ # Get the current command line and convert into a string
530
+ $Command = $CommandAst.CommandElements
531
+ $Command = "$Command"
532
+
533
+ __${name}_debug ""
534
+ __${name}_debug "========= starting completion logic =========="
535
+ __${name}_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"
536
+
537
+ # The user could have moved the cursor backwards on the command-line.
538
+ # We need to trigger completion from the $CursorPosition location, so we need
539
+ # to truncate the command-line ($Command) up to the $CursorPosition location.
540
+ # Make sure the $Command is longer then the $CursorPosition before we truncate.
541
+ # This happens because the $Command does not include the last space.
542
+ if ($Command.Length -gt $CursorPosition) {
543
+ $Command = $Command.Substring(0, $CursorPosition)
544
+ }
545
+ __${name}_debug "Truncated command: $Command"
546
+
547
+ $ShellCompDirectiveError=${ShellCompDirectiveError}
548
+ $ShellCompDirectiveNoSpace=${ShellCompDirectiveNoSpace}
549
+ $ShellCompDirectiveNoFileComp=${ShellCompDirectiveNoFileComp}
550
+ $ShellCompDirectiveFilterFileExt=${ShellCompDirectiveFilterFileExt}
551
+ $ShellCompDirectiveFilterDirs=${ShellCompDirectiveFilterDirs}
552
+ $ShellCompDirectiveKeepOrder=${ShellCompDirectiveKeepOrder}
553
+
554
+ # Prepare the command to request completions for the program.
555
+ # Split the command at the first space to separate the program and arguments.
556
+ $Program, $Arguments = $Command.Split(" ", 2)
557
+
558
+ $RequestComp = "& ${exec} complete -- $Arguments"
559
+ __${name}_debug "RequestComp: $RequestComp"
560
+
561
+ # we cannot use $WordToComplete because it
562
+ # has the wrong values if the cursor was moved
563
+ # so use the last argument
564
+ if ($WordToComplete -ne "" ) {
565
+ $WordToComplete = $Arguments.Split(" ")[-1]
566
+ }
567
+ __${name}_debug "New WordToComplete: $WordToComplete"
568
+
569
+
570
+ # Check for flag with equal sign
571
+ $IsEqualFlag = ($WordToComplete -Like "--*=*" )
572
+ if ( $IsEqualFlag ) {
573
+ __${name}_debug "Completing equal sign flag"
574
+ # Remove the flag part
575
+ $Flag, $WordToComplete = $WordToComplete.Split("=", 2)
576
+ }
577
+
578
+ if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
579
+ # If the last parameter is complete (there is a space following it)
580
+ # We add an extra empty parameter so we can indicate this to the go method.
581
+ __${name}_debug "Adding extra empty parameter"
582
+ # PowerShell 7.2+ changed the way how the arguments are passed to executables,
583
+ # so for pre-7.2 or when Legacy argument passing is enabled we need to use
584
+ if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
585
+ ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
586
+ (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
587
+ $PSNativeCommandArgumentPassing -eq 'Legacy')) {
588
+ $RequestComp="$RequestComp" + ' \`"\`"'
589
+ } else {
590
+ $RequestComp = "$RequestComp" + ' ""'
591
+ }
592
+ }
593
+
594
+ __${name}_debug "Calling $RequestComp"
595
+ # First disable ActiveHelp which is not supported for Powershell
596
+ $env:ActiveHelp = 0
597
+
598
+ # call the command store the output in $out and redirect stderr and stdout to null
599
+ # $Out is an array contains each line per element
600
+ Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
601
+
602
+ # get directive from last line
603
+ [int]$Directive = $Out[-1].TrimStart(':')
604
+ if ($Directive -eq "") {
605
+ # There is no directive specified
606
+ $Directive = 0
607
+ }
608
+ __${name}_debug "The completion directive is: $Directive"
609
+
610
+ # remove directive (last element) from out
611
+ $Out = $Out | Where-Object { $_ -ne $Out[-1] }
612
+ __${name}_debug "The completions are: $Out"
613
+
614
+ if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
615
+ # Error code. No completion.
616
+ __${name}_debug "Received error from custom completion go code"
617
+ return
618
+ }
619
+
620
+ $Longest = 0
621
+ [Array]$Values = $Out | ForEach-Object {
622
+ # Split the output in name and description
623
+ $Name, $Description = $_.Split("\`t", 2)
624
+ __${name}_debug "Name: $Name Description: $Description"
625
+
626
+ # Look for the longest completion so that we can format things nicely
627
+ if ($Longest -lt $Name.Length) {
628
+ $Longest = $Name.Length
629
+ }
630
+
631
+ # Set the description to a one space string if there is none set.
632
+ # This is needed because the CompletionResult does not accept an empty string as argument
633
+ if (-Not $Description) {
634
+ $Description = " "
635
+ }
636
+ @{ Name = "$Name"; Description = "$Description" }
637
+ }
638
+
639
+
640
+ $Space = " "
641
+ if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
642
+ # remove the space here
643
+ __${name}_debug "ShellCompDirectiveNoSpace is called"
644
+ $Space = ""
645
+ }
646
+
647
+ if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
648
+ (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
649
+ __${name}_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
650
+
651
+ # return here to prevent the completion of the extensions
652
+ return
653
+ }
654
+
655
+ $Values = $Values | Where-Object {
656
+ # filter the result
657
+ $_.Name -like "$WordToComplete*"
658
+
659
+ # Join the flag back if we have an equal sign flag
660
+ if ( $IsEqualFlag ) {
661
+ __${name}_debug "Join the equal sign flag back to the completion value"
662
+ $_.Name = $Flag + "=" + $_.Name
663
+ }
664
+ }
665
+
666
+ # we sort the values in ascending order by name if keep order isn't passed
667
+ if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
668
+ $Values = $Values | Sort-Object -Property Name
669
+ }
670
+
671
+ if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
672
+ __${name}_debug "ShellCompDirectiveNoFileComp is called"
673
+
674
+ if ($Values.Length -eq 0) {
675
+ # Just print an empty string here so the
676
+ # shell does not start to complete paths.
677
+ # We cannot use CompletionResult here because
678
+ # it does not accept an empty string as argument.
679
+ ""
680
+ return
681
+ }
682
+ }
683
+
684
+ # Get the current mode
685
+ $Mode = (Get-PSReadLineKeyHandler | Where-Object { $_.Key -eq "Tab" }).Function
686
+ __${name}_debug "Mode: $Mode"
687
+
688
+ $Values | ForEach-Object {
689
+
690
+ # store temporary because switch will overwrite $_
691
+ $comp = $_
692
+
693
+ # PowerShell supports three different completion modes
694
+ # - TabCompleteNext (default windows style - on each key press the next option is displayed)
695
+ # - Complete (works like bash)
696
+ # - MenuComplete (works like zsh)
697
+ # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>
698
+
699
+ # CompletionResult Arguments:
700
+ # 1) CompletionText text to be used as the auto completion result
701
+ # 2) ListItemText text to be displayed in the suggestion list
702
+ # 3) ResultType type of completion result
703
+ # 4) ToolTip text for the tooltip with details about the object
704
+
705
+ switch ($Mode) {
706
+
707
+ # bash like
708
+ "Complete" {
709
+
710
+ if ($Values.Length -eq 1) {
711
+ __${name}_debug "Only one completion left"
712
+
713
+ # insert space after value
714
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
715
+
716
+ } else {
717
+ # Add the proper number of spaces to align the descriptions
718
+ while($comp.Name.Length -lt $Longest) {
719
+ $comp.Name = $comp.Name + " "
720
+ }
721
+
722
+ # Check for empty description and only add parentheses if needed
723
+ if ($($comp.Description) -eq " " ) {
724
+ $Description = ""
725
+ } else {
726
+ $Description = " ($($comp.Description))"
727
+ }
728
+
729
+ [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
730
+ }
731
+ }
732
+
733
+ # zsh like
734
+ "MenuComplete" {
735
+ # insert space after value
736
+ # MenuComplete will automatically show the ToolTip of
737
+ # the highlighted value at the bottom of the suggestions.
738
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
739
+ }
740
+
741
+ # TabCompleteNext and in case we get something unknown
742
+ Default {
743
+ # Like MenuComplete but we don't want to add a space here because
744
+ # the user need to press space anyway to get the completion.
745
+ # Description will not be shown because that's not possible with TabCompleteNext
746
+ [System.Management.Automation.CompletionResult]::new($($comp.Name | __${name}_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
747
+ }
748
+ }
749
+
750
+ }
751
+ }
752
+
753
+ Register-ArgumentCompleter -CommandName '${name}' -ScriptBlock $__${nameForVar}CompleterBlock
754
+ `;
755
+ }
756
+
757
+ //#endregion
758
+ //#region src/t.ts
759
+ const ShellCompDirective = {
760
+ ShellCompDirectiveError: 1,
761
+ ShellCompDirectiveNoSpace: 2,
762
+ ShellCompDirectiveNoFileComp: 4,
763
+ ShellCompDirectiveFilterFileExt: 8,
764
+ ShellCompDirectiveFilterDirs: 16,
765
+ ShellCompDirectiveKeepOrder: 32,
766
+ shellCompDirectiveMaxValue: 64,
767
+ ShellCompDirectiveDefault: 0
768
+ };
769
+ var Argument = class {
770
+ name;
771
+ variadic;
772
+ command;
773
+ handler;
774
+ constructor(command, name, handler, variadic = false) {
775
+ this.command = command;
776
+ this.name = name;
777
+ this.handler = handler;
778
+ this.variadic = variadic;
779
+ }
780
+ };
781
+ var Option = class {
782
+ value;
783
+ description;
784
+ command;
785
+ handler;
786
+ alias;
787
+ isBoolean;
788
+ constructor(command, value, description, handler, alias, isBoolean) {
789
+ this.command = command;
790
+ this.value = value;
791
+ this.description = description;
792
+ this.handler = handler;
793
+ this.alias = alias;
794
+ this.isBoolean = isBoolean;
795
+ }
796
+ };
797
+ var Command = class {
798
+ value;
799
+ description;
800
+ options = new Map();
801
+ arguments = new Map();
802
+ parent;
803
+ constructor(value, description) {
804
+ this.value = value;
805
+ this.description = description;
806
+ }
807
+ option(value, description, handlerOrAlias, alias) {
808
+ let handler;
809
+ let aliasStr;
810
+ let isBoolean;
811
+ if (typeof handlerOrAlias === "function") {
812
+ handler = handlerOrAlias;
813
+ aliasStr = alias;
814
+ isBoolean = false;
815
+ } else if (typeof handlerOrAlias === "string") {
816
+ handler = void 0;
817
+ aliasStr = handlerOrAlias;
818
+ isBoolean = true;
819
+ } else {
820
+ handler = void 0;
821
+ aliasStr = void 0;
822
+ isBoolean = true;
823
+ }
824
+ const option = new Option(this, value, description, handler, aliasStr, isBoolean);
825
+ this.options.set(value, option);
826
+ return this;
827
+ }
828
+ argument(name, handler, variadic = false) {
829
+ const arg = new Argument(this, name, handler, variadic);
830
+ this.arguments.set(name, arg);
831
+ return this;
832
+ }
833
+ };
834
+ var RootCommand = class extends Command {
835
+ commands = new Map();
836
+ completions = [];
837
+ directive = ShellCompDirective.ShellCompDirectiveDefault;
838
+ constructor() {
839
+ super("", "");
840
+ }
841
+ command(value, description) {
842
+ const c = new Command(value, description);
843
+ this.commands.set(value, c);
844
+ return c;
845
+ }
846
+ stripOptions(args) {
847
+ const parts = [];
848
+ let i = 0;
849
+ while (i < args.length) {
850
+ const arg = args[i];
851
+ if (arg.startsWith("-")) {
852
+ i++;
853
+ let isBoolean = false;
854
+ const rootOption = this.findOption(this, arg);
855
+ if (rootOption) isBoolean = rootOption.isBoolean ?? false;
856
+ else for (const [, command] of this.commands) {
857
+ const option = this.findOption(command, arg);
858
+ if (option) {
859
+ isBoolean = option.isBoolean ?? false;
860
+ break;
861
+ }
862
+ }
863
+ if (!isBoolean && i < args.length && !args[i].startsWith("-")) i++;
864
+ } else {
865
+ parts.push(arg);
866
+ i++;
867
+ }
868
+ }
869
+ return parts;
870
+ }
871
+ matchCommand(args) {
872
+ args = this.stripOptions(args);
873
+ const parts = [];
874
+ let remaining = [];
875
+ let matchedCommand = null;
876
+ for (let i = 0; i < args.length; i++) {
877
+ const k = args[i];
878
+ parts.push(k);
879
+ const potential = this.commands.get(parts.join(" "));
880
+ if (potential) matchedCommand = potential;
881
+ else {
882
+ remaining = args.slice(i, args.length);
883
+ break;
884
+ }
885
+ }
886
+ return [matchedCommand || this, remaining];
887
+ }
888
+ shouldCompleteFlags(lastPrevArg, toComplete, endsWithSpace) {
889
+ if (toComplete.startsWith("-")) return true;
890
+ if (lastPrevArg?.startsWith("-")) {
891
+ let option = this.findOption(this, lastPrevArg);
892
+ if (!option) for (const [, command] of this.commands) {
893
+ option = this.findOption(command, lastPrevArg);
894
+ if (option) break;
895
+ }
896
+ if (option && option.isBoolean) return false;
897
+ return true;
898
+ }
899
+ return false;
900
+ }
901
+ shouldCompleteCommands(toComplete, endsWithSpace) {
902
+ return !toComplete.startsWith("-");
903
+ }
904
+ handleFlagCompletion(command, previousArgs, toComplete, endsWithSpace, lastPrevArg) {
905
+ let optionName;
906
+ if (toComplete.includes("=")) {
907
+ const [flag] = toComplete.split("=");
908
+ optionName = flag;
909
+ } else if (lastPrevArg?.startsWith("-")) optionName = lastPrevArg;
910
+ if (optionName) {
911
+ const option = this.findOption(command, optionName);
912
+ if (option?.handler) {
913
+ const suggestions = [];
914
+ option.handler.call(option, (value, description) => suggestions.push({
915
+ value,
916
+ description
917
+ }), command.options);
918
+ this.completions = toComplete.includes("=") ? suggestions.map((s) => ({
919
+ value: `${optionName}=${s.value}`,
920
+ description: s.description
921
+ })) : suggestions;
922
+ }
923
+ return;
924
+ }
925
+ if (toComplete.startsWith("-")) {
926
+ const isShortFlag = toComplete.startsWith("-") && !toComplete.startsWith("--");
927
+ const cleanToComplete = toComplete.replace(/^-+/, "");
928
+ for (const [name, option] of command.options) if (isShortFlag && option.alias && `-${option.alias}`.startsWith(toComplete)) this.completions.push({
929
+ value: `-${option.alias}`,
930
+ description: option.description
931
+ });
932
+ else if (!isShortFlag && name.startsWith(cleanToComplete)) this.completions.push({
933
+ value: `--${name}`,
934
+ description: option.description
935
+ });
936
+ }
937
+ }
938
+ findOption(command, optionName) {
939
+ let option = command.options.get(optionName);
940
+ if (option) return option;
941
+ option = command.options.get(optionName.replace(/^-+/, ""));
942
+ if (option) return option;
943
+ for (const [_name, opt] of command.options) if (opt.alias && `-${opt.alias}` === optionName) return opt;
944
+ return void 0;
945
+ }
946
+ handleCommandCompletion(previousArgs, toComplete) {
947
+ const commandParts = this.stripOptions(previousArgs);
948
+ for (const [k, command] of this.commands) {
949
+ if (k === "") continue;
950
+ const parts = k.split(" ");
951
+ const match = parts.slice(0, commandParts.length).every((part, i) => part === commandParts[i]);
952
+ if (match && parts[commandParts.length]?.startsWith(toComplete)) this.completions.push({
953
+ value: parts[commandParts.length],
954
+ description: command.description
955
+ });
956
+ }
957
+ }
958
+ handlePositionalCompletion(command, previousArgs, toComplete, endsWithSpace) {
959
+ const commandParts = command.value.split(" ").length;
960
+ const currentArgIndex = Math.max(0, previousArgs.length - commandParts);
961
+ const argumentEntries = Array.from(command.arguments.entries());
962
+ if (argumentEntries.length > 0) {
963
+ let targetArgument;
964
+ if (currentArgIndex < argumentEntries.length) {
965
+ const [_argName, argument] = argumentEntries[currentArgIndex];
966
+ targetArgument = argument;
967
+ } else {
968
+ const lastArgument = argumentEntries[argumentEntries.length - 1][1];
969
+ if (lastArgument.variadic) targetArgument = lastArgument;
970
+ }
971
+ if (targetArgument && targetArgument.handler && typeof targetArgument.handler === "function") {
972
+ const suggestions = [];
973
+ targetArgument.handler.call(targetArgument, (value, description) => suggestions.push({
974
+ value,
975
+ description
976
+ }), command.options);
977
+ this.completions.push(...suggestions);
978
+ }
979
+ }
980
+ }
981
+ complete(toComplete) {
982
+ this.directive = ShellCompDirective.ShellCompDirectiveNoFileComp;
983
+ const seen = new Set();
984
+ this.completions.filter((comp) => {
985
+ if (seen.has(comp.value)) return false;
986
+ seen.add(comp.value);
987
+ return true;
988
+ }).filter((comp) => comp.value.startsWith(toComplete)).forEach((comp) => console.log(`${comp.value}\t${comp.description ?? ""}`));
989
+ console.log(`:${this.directive}`);
990
+ }
991
+ parse(args) {
992
+ this.completions = [];
993
+ const endsWithSpace = args[args.length - 1] === "";
994
+ if (endsWithSpace) args.pop();
995
+ let toComplete = args[args.length - 1] || "";
996
+ const previousArgs = args.slice(0, -1);
997
+ if (endsWithSpace) {
998
+ if (toComplete !== "") previousArgs.push(toComplete);
999
+ toComplete = "";
1000
+ }
1001
+ const [matchedCommand] = this.matchCommand(previousArgs);
1002
+ const lastPrevArg = previousArgs[previousArgs.length - 1];
1003
+ if (this.shouldCompleteFlags(lastPrevArg, toComplete, endsWithSpace)) this.handleFlagCompletion(matchedCommand, previousArgs, toComplete, endsWithSpace, lastPrevArg);
1004
+ else {
1005
+ if (lastPrevArg?.startsWith("-") && toComplete === "" && endsWithSpace) {
1006
+ let option = this.findOption(this, lastPrevArg);
1007
+ if (!option) for (const [, command] of this.commands) {
1008
+ option = this.findOption(command, lastPrevArg);
1009
+ if (option) break;
1010
+ }
1011
+ if (option && option.isBoolean) {
1012
+ this.complete(toComplete);
1013
+ return;
1014
+ }
1015
+ }
1016
+ if (this.shouldCompleteCommands(toComplete, endsWithSpace)) this.handleCommandCompletion(previousArgs, toComplete);
1017
+ if (matchedCommand && matchedCommand.arguments.size > 0) this.handlePositionalCompletion(matchedCommand, previousArgs, toComplete, endsWithSpace);
1018
+ }
1019
+ this.complete(toComplete);
1020
+ }
1021
+ setup(name, executable, shell) {
1022
+ assert(shell === "zsh" || shell === "bash" || shell === "fish" || shell === "powershell", "Unsupported shell");
1023
+ switch (shell) {
1024
+ case "zsh": {
1025
+ const script$1 = generate$3(name, executable);
1026
+ console.log(script$1);
1027
+ break;
1028
+ }
1029
+ case "bash": {
1030
+ const script$1 = generate$2(name, executable);
1031
+ console.log(script$1);
1032
+ break;
1033
+ }
1034
+ case "fish": {
1035
+ const script$1 = generate$1(name, executable);
1036
+ console.log(script$1);
1037
+ break;
1038
+ }
1039
+ case "powershell": {
1040
+ const script$1 = generate(name, executable);
1041
+ console.log(script$1);
1042
+ break;
1043
+ }
1044
+ }
1045
+ }
1046
+ };
1047
+ const t = new RootCommand();
1048
+ function script(shell, name, executable) {
1049
+ t.setup(name, executable, shell);
1050
+ }
1051
+ var t_default = t;
1052
+
1053
+ //#endregion
1054
+ export { Argument, Command, Option, RootCommand, ShellCompDirective, generate, generate$1, generate$2, generate$3, script, t_default };