Debian Codegraph @

crazy_complete/zsh_helpers.py

raw
1 # SPDX-License-Identifier: GPL-3.0-or-later
2 # Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]>
3
4 '''This module contains helper functions for Zsh.'''
5
6 from .helpers import GeneralHelpers, ShellFunction
7
8
9 _QUERY = ShellFunction('query', r'''
10 # ===========================================================================
11 #
12 # This function is for querying the command line.
13 #
14 # COMMANDS
15 # init <OPTIONS> <ARGS...>
16 # This is the first call you have to make, otherwise the other commands
17 # won't (successfully) work.
18 #
19 # It parses <ARGS> according to <OPTIONS> and stores results in the
20 # variables POSITIONALS, HAVING_OPTIONS and OPTION_VALUES.
21 #
22 # The first argument is a comma-separated list of options that the parser
23 # should know about. Short options (-o), long options (--option), and
24 # old-style options (-option) are supported.
25 #
26 # If an option takes an argument, it is suffixed by '='.
27 # If an option takes an optional argument, it is suffixed by '=?'.
28 #
29 # get_positional <NUM>
30 # Prints out the positional argument number NUM (starting from 1)
31 #
32 # has_option [WITH_INCOMPLETE] <OPTIONS...>
33 # Checks if an option given in OPTIONS is passed on commandline.
34 # If an option requires an argument, this command returns true only if the
35 # option includes an argument. If 'WITH_INCOMPLETE' is specified, it also
36 # returns true for options missing their arguments.
37 #
38 # option_is [-a] [-i] -- <OPTIONS...> -- <VALUES...>
39 # Checks if one option in OPTIONS has a value of VALUES.
40 #
41 # EXAMPLE
42 # local POSITIONALS HAVING_OPTIONS OPTION_VALUES
43 # query init '-f,-a=,-optional=?' program_name -f -optional -a foo bar
44 # query has_option -f
45 # query option_is -- -a -- foo
46 #
47 # Here, -f is a flag, -a takes an argument, and -optional takes an optional
48 # argument.
49 #
50 # Both queries return true.
51 #
52 # ===========================================================================
53
54 local cmd="$1"; shift
55
56 case "$cmd" in
57 #ifdef get_positional
58 get_positional)
59 #ifdef DEBUG
60 if (( $# != 1 )); then
61 echo "%FUNCNAME%: get_positional: takes exactly one argument" >&2
62 return 1
63 fi
64
65 if test "$1" -eq 0; then
66 echo "%FUNCNAME%: get_positional: positionals start at 1, not 0!" >&2
67 return 1
68 fi
69
70 #endif
71 printf "%s" "${POSITIONALS[$1]}"
72 return 0;;
73 #endif
74 #ifdef get_option
75 get_option)
76 local i=0
77
78 #ifdef DEBUG
79 if (( $# == 0 )); then
80 echo "%FUNCNAME%: get_option: arguments required" >&2
81 return 1
82 fi
83
84 #endif
85 for (( i=0; i <= ${#HAVING_OPTIONS[@]}; ++i )); do
86 local option="${HAVING_OPTIONS[$i]}"
87 if array_contains "$option" "$@"; then
88 printf "%s\n" "${OPTION_VALUES[$i]}"
89 fi
90 done
91
92 return 0;;
93 #endif
94 #ifdef has_option
95 has_option)
96 #ifdef with_incomplete
97 local option='' with_incomplete=0
98 [[ "$1" == 'WITH_INCOMPLETE' ]] && { with_incomplete=1; shift; }
99 #else
100 local option=''
101 #endif
102
103 #ifdef DEBUG
104 if (( $# == 0 )); then
105 echo "%FUNCNAME%: has_option: arguments required" >&2
106 return 1
107 fi
108
109 #endif
110 for option in "${HAVING_OPTIONS[@]}"; do
111 array_contains "$option" "$@" && return 0
112 done
113
114 #ifdef with_incomplete
115 (( with_incomplete )) && \
116 array_contains "$INCOMPLETE_OPTION" "$@" && return 0
117
118 #endif
119 return 1;;
120 #endif
121 #ifdef option_is
122 option_is)
123 local i=0 dash_dash_pos=0 cmd_option_is_options=() cmd_option_is_values=()
124 local nocase=0 any=0
125
126 while (( $# )); do
127 #ifdef any
128 [[ "$1" == "-a" ]] && { any=1; shift; continue; }
129 #endif
130 #ifdef nocase
131 [[ "$1" == "-i" ]] && { nocase=1; shift; continue; }
132 #endif
133 [[ "$1" == "--" ]] && { shift; break; }
134 done
135
136 dash_dash_pos=${@[(i)--]}
137 cmd_option_is_options=("${@:1:$((dash_dash_pos - 1))}")
138 cmd_option_is_values=("${@:$((dash_dash_pos + 1))}")
139 #ifdef nocase
140 (( nocase )) && cmd_option_is_values=("${(L)cmd_option_is_values[@]}")
141 #endif
142
143 #ifdef DEBUG
144 if (( ${#cmd_option_is_options[@]} == 0 )); then
145 echo "%FUNCNAME%: option_is: missing options" >&2
146 return 1
147 fi
148
149 if (( ${#cmd_option_is_values[@]} == 0 )); then
150 echo "%FUNCNAME%: option_is: missing values" >&2
151 return 1
152 fi
153
154 #endif
155 for (( i=${#HAVING_OPTIONS[@]}; i > 0; --i )); do
156 if array_contains "${HAVING_OPTIONS[$i]}" "${cmd_option_is_options[@]}"; then
157 local value="${OPTION_VALUES[$i]}"
158 #ifdef nocase
159 (( nocase )) && value="${(L)value}"
160 #endif
161 array_contains "$value" "${cmd_option_is_values[@]}" && return 0
162 #ifdef any
163 (( any )) || return 1
164 #else
165 return 1
166 #endif
167 fi
168 done
169
170 return 1;;
171 #endif
172 init)
173 local -a options=(${=1})
174 shift;;
175 *)
176 echo "%FUNCNAME%: argv[1]: invalid command" >&2
177 return 1;;
178 esac
179
180 # continuing init...
181
182 # ===========================================================================
183 # Parsing of available options
184 # ===========================================================================
185
186 #ifdef old_options
187 local old_opts_with_arg=() old_opts_with_optional_arg=() old_opts_without_arg=()
188 #endif
189 #ifdef long_options
190 local long_opts_with_arg=() long_opts_with_optional_arg=() long_opts_without_arg=()
191 #endif
192 #ifdef short_options
193 local short_opts_with_arg=() short_opts_with_optional_arg=() short_opts_without_arg=()
194 #endif
195
196 local option=''
197 for option in "${options[@]}"; do
198 case "$option" in
199 #ifdef long_options
200 --?*=) long_opts_with_arg+=("${option%=}");;
201 --?*=\?) long_opts_with_optional_arg+=("${option%=?}");;
202 --?*) long_opts_without_arg+=("$option");;
203 #endif
204 #ifdef short_options
205 -?=) short_opts_with_arg+=("${option%=}");;
206 -?=\?) short_opts_with_optional_arg+=("${option%=?}");;
207 -?) short_opts_without_arg+=("$option");;
208 #endif
209 #ifdef old_options
210 -??*=) old_opts_with_arg+=("${option%=}");;
211 -??*=\?) old_opts_with_optional_arg+=("${option%=?}");;
212 -??*) old_opts_without_arg+=("$option");;
213 #endif
214 #ifdef DEBUG
215 *) echo "%FUNCNAME%: $option: not a valid short, long or oldstyle option" >&2; return 1;;
216 #endif
217 esac
218 done
219
220 # ===========================================================================
221 # Parsing of command line options
222 # ===========================================================================
223
224 POSITIONALS=()
225 HAVING_OPTIONS=()
226 OPTION_VALUES=()
227 INCOMPLETE_OPTION=''
228
229 local args=("${(Q)@}")
230 local argi=2 # argi[1] is program name
231 for ((; argi <= ${#args[@]}; ++argi)); do
232 local arg="${args[$argi]}"
233 local have_trailing_arg=$(test $argi -lt $# && echo true || echo false)
234
235 case "$arg" in
236 --)
237 POSITIONALS+=("${@:$((argi + 1))}")
238 break;;
239 --*=*)
240 HAVING_OPTIONS+=("${arg%%=*}")
241 OPTION_VALUES+=("${arg#*=}");;
242 --*)
243 #ifdef long_options
244 if array_contains "$arg" "${long_opts_with_arg[@]}"; then
245 if $have_trailing_arg; then
246 HAVING_OPTIONS+=("$arg")
247 OPTION_VALUES+=("${args[$((++argi))]}")
248 #ifdef with_incomplete
249 else
250 INCOMPLETE_OPTION="$arg"
251 #endif
252 fi
253 else
254 HAVING_OPTIONS+=("$arg")
255 OPTION_VALUES+=("")
256 fi
257 #endif
258 ;;
259 -?*) # ignore '-'
260 #ifdef old_options
261 if [[ "$arg" == *=* ]]; then
262 local option="${arg%%=*}" value="${arg#*=}"
263 if array_contains "$option" "${old_opts_with_arg[@]}" "${old_opts_with_optional_arg[@]}"; then
264 HAVING_OPTIONS+=("$option")
265 OPTION_VALUES+=("$value")
266 continue
267 fi
268 elif array_contains "$arg" "${old_opts_with_arg[@]}"; then
269 if $have_trailing_arg; then
270 HAVING_OPTIONS+=("$arg")
271 OPTION_VALUES+=("${args[$((++argi))]}")
272 #ifdef with_incomplete
273 else
274 INCOMPLETE_OPTION="$arg"
275 #endif
276 fi
277 continue
278 elif array_contains "$arg" "${old_opts_without_arg[@]}" "${old_opts_with_optional_arg[@]}"; then
279 HAVING_OPTIONS+=("$arg")
280 OPTION_VALUES+=("")
281 continue
282 fi
283 #endif
284
285 #ifdef short_options
286 local i=1 arg_length=${#arg}
287 for ((; i < arg_length; ++i)); do
288 local option="-${arg:$i:1}"
289 local trailing_chars="${arg:$((i+1))}"
290
291 if array_contains "$option" "${short_opts_without_arg[@]}"; then
292 HAVING_OPTIONS+=("$option")
293 OPTION_VALUES+=("")
294 elif array_contains "$option" "${short_opts_with_arg[@]}"; then
295 if [[ -n "$trailing_chars" ]]; then
296 HAVING_OPTIONS+=("$option")
297 OPTION_VALUES+=("$trailing_chars")
298 elif $have_trailing_arg; then
299 HAVING_OPTIONS+=("$option")
300 OPTION_VALUES+=("${args[$((++argi))]}")
301 #ifdef with_incomplete
302 else
303 INCOMPLETE_OPTION="$option"
304 #endif
305 fi
306
307 continue 2
308 elif array_contains "$option" "${short_opts_with_optional_arg[@]}"; then
309 HAVING_OPTIONS+=("$option")
310 OPTION_VALUES+=("$trailing_chars") # may be empty
311 continue 2
312 fi
313 done
314 #endif
315 ;;
316 *)
317 POSITIONALS+=("$arg");;
318 esac
319 done
320 ''', ['array_contains'])
321
322 _ARRAY_CONTAINS = ShellFunction('array_contains', r'''
323 local arg='' key="$1"; shift
324 for arg; do [[ "$key" == "$arg" ]] && return 0; done
325 return 1
326 ''')
327
328 _OPTION_MATCH = ShellFunction('option_match', r'''
329 local i=0 dash_dash_pos=0 options=() regex='' nocase=0 any=0
330
331 while (( $# )); do
332 #ifdef any
333 [[ "$1" == '-a' ]] && { any=1; shift; continue; }
334 #endif
335 #ifdef nocase
336 [[ "$1" == '-i' ]] && { nocase=1; shift; continue; }
337 #endif
338 [[ "$1" == '--' ]] && { shift; break; }
339 done
340
341 dash_dash_pos=${@[(i)--]}
342 options=("${@:1:$((dash_dash_pos - 1))}")
343 regex="${@:$((dash_dash_pos + 1)):1}"
344
345 #ifdef DEBUG
346 if (( ${#options[@]} == 0 )); then
347 echo "%FUNCNAME%: missing options" >&2
348 return 1
349 fi
350
351 if (( ${#regex} == 0 )); then
352 echo "%FUNCNAME%: missing regex" >&2
353 return 1
354 fi
355
356 #endif
357 for (( i=${#HAVING_OPTIONS[@]}; i > 0; --i )); do
358 if array_contains "${HAVING_OPTIONS[$i]}" "${options[@]}"; then
359 #ifdef nocase
360 if (( nocase ));
361 then [[ "${(L)OPTION_VALUES[$i]}" =~ "${(L)regex}" ]] && return 0
362 else [[ "${OPTION_VALUES[$i]}" =~ "${regex}" ]] && return 0
363 fi
364 #else
365 [[ "${OPTION_VALUES[$i]}" =~ "${regex}" ]] && return 0
366 #endif
367 #ifdef any
368 (( any )) || return 1
369 #else
370 return 1
371 #endif
372 fi
373 done
374
375 return 1
376 ''', ['array_contains'])
377
378 _PREFIX = ShellFunction('prefix', r'''
379 if [[ "$PREFIX" == "$1"* ]]; then
380 PREFIX="${PREFIX#"$1"}"
381 IPREFIX="$IPREFIX$1"
382 $2
383 else
384 compadd -S '' -- "$1"
385 fi
386 ''')
387
388 _EXEC = ShellFunction('exec', r'''
389 local item='' desc='' describe=()
390
391 while IFS=$'\t' read -r item desc; do
392 item="${item//\\/\\\\}"
393 item="${item//:/\\:}"
394 desc="${desc//\\/\\\\}"
395 [[ -n "$desc" ]] && describe+=("$item:$desc") || describe+=("$item")
396 done < <(eval "$1")
397
398 _describe '' describe
399 ''')
400
401 _KEY_VALUE_PAIR_EXEC = ShellFunction('key_value_pair_exec', r'''
402 local sep="$1"
403 local func="$2"
404 local key='' desc=''
405 local -a args=()
406
407 while IFS=$'\t' read -r key desc; do
408 desc="${desc//\\/\\\\}"
409 desc="${desc//:/\\:}"
410 desc="${desc//\[/\\[}"
411 desc="${desc//\]/\\]}"
412
413 if [[ "${key[-1]}" == '=' ]]; then
414 key="${key:0:-1}"
415 args+=("${key}[$desc]:::{exec '$func $key'}")
416 else
417 args+=("${key}[$desc]")
418 fi
419 done < <(eval "$func")
420
421 _values -S "$sep" '' "${args[@]}"
422 ''', ['exec'])
423
424 _KEY_VALUE_LIST_EXEC = ShellFunction('key_value_list_exec', r'''
425 local sep1="$1"
426 local sep2="$2"
427 local func="$3"
428 local key='' desc='' excludes=''
429 local -a args=()
430
431 while IFS=$'\t' read -r key desc excludes; do
432 desc="${desc//\\/\\\\}"
433 desc="${desc//:/\\:}"
434 desc="${desc//\[/\\[}"
435 desc="${desc//\]/\\]}"
436
437 [[ -n "$excludes" ]] && excludes="($excludes)"
438
439 if [[ "${key: -1:1}" == '=' ]]; then
440 key="${key:0:-1}"
441 args+=("${excludes}${key}[$desc]: :{exec '$func $key'}")
442 elif [[ "${key: -2:2}" == '=?' ]]; then
443 key="${key:0:-2}"
444 args+=("${excludes}${key}[$desc]:: :{exec '$func $key'}")
445 else
446 args+=("${excludes}${key}[$desc]")
447 fi
448 done < <(eval "$func")
449
450 _values -s "$sep1" -S "$sep2" '' "${args[@]}"
451 ''', ['exec'])
452
453 _HISTORY = ShellFunction('history', r'''
454 [[ -f "$HISTFILE" ]] || return
455
456 local match=''
457
458 command grep -E -o -- "$1" "$HISTFILE" | while read -r match; do
459 compadd -- "$match"
460 done
461 ''')
462
463 _MIME_FILE = ShellFunction('mime_file', r'''
464 local line='' file='' mime='' i_opt=''
465
466 if command file -i /dev/null &>/dev/null; then
467 i_opt="-i"
468 elif command file -I /dev/null &>/dev/null; then
469 i_opt="-I"
470 else
471 compadd -- "$PREFIX"*
472 return
473 fi
474
475 command file -L $i_opt -- "$PREFIX"* 2>/dev/null | while read -r line; do
476 mime="${line##*:}"
477
478 if [[ "$mime" == *inode/directory* ]] || command grep -q -E -- "$1" <<< "$mime"; then
479 file="${line%:*}"
480
481 if [[ "$file" == *\\* ]]; then
482 file="$(command perl -pe 's/\\([0-7]{3})/chr(oct($1))/ge' <<< "$file")"
483 fi
484
485 if [[ "$mime" == *inode/directory* ]]; then
486 compadd -- "$file/"
487 else
488 compadd -- "$file"
489 fi
490 fi
491 done
492 ''')
493
494 _UID_LIST = ShellFunction('uid_list', r'''
495 local items=($(command getent passwd | command awk -F: '{printf "%s:%s\n", $3, $1}'))
496 _describe 'users' items
497 ''')
498
499 _GID_LIST = ShellFunction('gid_list', r'''
500 local items=($(command getent group | command awk -F: '{printf "%s:%s\n", $3, $1}'))
501 _describe 'groups' items
502 ''')
503
504 _CHARSET_LIST = ShellFunction('charset_list', r'''
505 local items=($(command locale -m))
506 _describe 'charsets' items
507 ''')
508
509 _PATH_FILES_RELATIVE = ShellFunction('path_files_relative', r'''
510 local DIR="$1"; shift
511 _path_files -W "$PWD/$DIR" "$@"
512 ''')
513
514 # =============================================================================
515 # Bonus
516 # =============================================================================
517
518 _MOUNTPOINT = ShellFunction('mountpoint', r'''
519 local item=''
520
521 command findmnt -lno TARGET | while read -r item; do
522 compadd -- "$item"
523 done
524 ''')
525
526 _ALSA_COMPLETE_CARDS = ShellFunction('alsa_complete_cards', r'''
527 local card='' cards=()
528 command aplay -l \
529 | command grep -Eo '^card [0-9]+: [^,]+' \
530 | command uniq \
531 | while builtin read card; do
532 card="${card#card }"
533 local id="${card%%: *}"
534 local name="${card#*: }"
535 cards+=("$id:$name")
536 done
537
538 _describe 'ALSA card' cards
539 ''')
540
541 _ALSA_COMPLETE_DEVICES = ShellFunction('alsa_complete_devices', r'''
542 local card='' id='' name='' devices=()
543 command aplay -l \
544 | command grep -Eo '^card [0-9]+: [^,]+' \
545 | command uniq \
546 | while builtin read card; do
547 card="${card#card }"
548 id="${card%%: *}"
549 name="${card#*: }"
550 devices+=("hw\\:$id:$name")
551 done
552
553 _describe 'ALSA device' devices
554 ''')
555
556
557 class ZshHelpers(GeneralHelpers):
558 '''Class holding helper functions for Zsh.'''
559
560 def __init__(self, config, function_prefix):
561 super().__init__(config, function_prefix, ShellFunction)
562 self.add_function(_ARRAY_CONTAINS)
563 self.add_function(_QUERY)
564 self.add_function(_OPTION_MATCH)
565 self.add_function(_EXEC)
566 self.add_function(_KEY_VALUE_PAIR_EXEC)
567 self.add_function(_KEY_VALUE_LIST_EXEC)
568 self.add_function(_PREFIX)
569 self.add_function(_HISTORY)
570 self.add_function(_PATH_FILES_RELATIVE)
571 self.add_function(_MIME_FILE)
572 self.add_function(_UID_LIST)
573 self.add_function(_GID_LIST)
574 self.add_function(_CHARSET_LIST)
575 self.add_function(_MOUNTPOINT)
576 self.add_function(_ALSA_COMPLETE_CARDS)
577 self.add_function(_ALSA_COMPLETE_DEVICES)