chiark / gitweb /
bash-completion: simplify udevadm completion
[elogind.git] / shell-completion / systemd-zsh-completion.zsh
1 #compdef systemctl loginctl journalctl hostnamectl localectl timedatectl systemd-coredumpctl udevadm systemd-analyze systemd-cat systemd-ask-password systemd-cgls systemd-cgtop systemd-delta systemd-detect-virt systemd-inhibit systemd-machine-id-setup systemd-notify systemd-nspawn systemd-tmpfiles systemd-tty-ask-password-agent machinectl
2
3 _ctls()
4 {
5     local curcontext="$curcontext" state lstate line
6     case "$service" in
7         systemctl)
8             # -s for aggregated options like -aP
9             _arguments -s \
10                 {-h,--help}'[Show help]' \
11                 '--version[Show package version]' \
12                 {-t,--type=}'[List only units of a particular type]:unit type:(automount device mount path service snapshot socket swap target timer)' \
13                 \*{-p,--property=}'[Show only properties by specific name]:unit property' \
14                 {-a,--all}'[Show all units/properties, including dead/empty ones]' \
15                 '--reverse[Show reverse dependencies]' \
16                 '--after[Show units ordered after]' \
17                 '--before[Show units ordered before]' \
18                 '--failed[Show only failed units]' \
19                 {-l,--full}"[Don't ellipsize unit names on output]" \
20                 '--fail[When queueing a new job, fail if conflicting jobs are pending]' \
21                 '--ignore-dependencies[When queueing a new job, ignore all its dependencies]' \
22                 '--kill-who=[Who to send signal to]:killwho:(main control all)' \
23                 {-s,--signal=}'[Which signal to send]:signal:_signals' \
24                 {-H,--host=}'[Show information for remote host]:userathost:_hosts_or_user_at_host' \
25                 {-P,--privileged}'[Acquire privileges before execution]' \
26                 {-q,--quiet}'[Suppress output]' \
27                 '--no-block[Do not wait until operation finished]' \
28                 "--no-wall[Don't send wall message before halt/power-off/reboot]" \
29                 "--no-reload[When enabling/disabling unit files, don't reload daemon configuration]" \
30                 '--no-legend[Do not print a legend, i.e. the column headers and the footer with hints]' \
31                 '--no-pager[Do not pipe output into a pager]' \
32                 '--no-ask-password[Do not ask for system passwords]' \
33                 '--system[Connect to system manager]' \
34                 '--user[Connect to user service manager]' \
35                 '--global[Enable/disable unit files globally]' \
36                 {-f,--force}'[When enabling unit files, override existing symlinks. When shutting down, execute action immediately]' \
37                 '--root=[Enable unit files in the specified root directory]:directory:_directories' \
38                 '--runtime[Enable unit files only temporarily until next reboot]' \
39                 {-n,--lines=}'[Journal entries to show]:number of entries' \
40                 {-o,--output=}'[Change journal output mode]:modes:_outputmodes' \
41                 '*::systemctl command:_systemctl_command'
42         ;;
43         loginctl)
44             _arguments -s \
45                 {-h,--help}'[Show help]' \
46                 '--version[Show package version]' \
47                 \*{-p,--property=}'[Show only properties by this name]:unit property' \
48                 {-a,--all}'[Show all properties, including empty ones]' \
49                 '--kill-who=[Who to send signal to]:killwho:(main control all)' \
50                 {-s,--signal=}'[Which signal to send]:signal:_signals' \
51                 '--no-ask-password[Do not ask for system passwords]' \
52                 {-H,--host=}'[Show information for remote host]:userathost:_hosts_or_user_at_host' \
53                 {-P,--privileged}'[Acquire privileges before execution]' \
54                 '--no-pager[Do not pipe output into a pager]' \
55                 '*::loginctl command:_loginctl_command'
56         ;;
57
58         hostnamectl)
59             _arguments -s \
60                 {-h,--help}'[Show this help]' \
61                 '--version[Show package version]' \
62                 '--transient[Only set transient hostname]' \
63                 '--static[Only set static hostname]' \
64                 '--pretty[Only set pretty hostname]' \
65                 '--no-ask-password[Do not prompt for password]' \
66                 {-H,--host=}'[Operate on remote host]:userathost:_hosts_or_user_at_host' \
67                 '*::hostnamectl commands:_hostnamectl_command'
68         ;;
69         journalctl)
70             _arguments -s \
71                 '--since=[Start showing entries newer or of the specified date]:YYYY-MM-DD HH\:MM\:SS' \
72                 '--until=[Stop showing entries older or of the specified date]:YYYY-MM-DD HH\:MM\:SS' \
73                 {-c,--cursor=}'[Start showing entries from specified cursor]:cursors:_journal_fields __CURSORS' \
74                 '--system[Show system and kernel messages]' \
75                 '--user[Show messages from user services]' \
76                 {-b,--this-boot}'[Show data only from current boot]' \
77                 {-u,--unit=}'[Show data only from the specified unit]:units:_journal_fields _SYSTEMD_UNIT' \
78                 '--user-unit[Show data only from the specified user session unit]:units:_journal_fields _SYSTEMD_USER_UNIT' \
79                 {-p,--priority=}'[Show only messages within the specified priority range]:priority:_journal_fields PRIORITY' \
80                 {-f,--follow}'[Follow journal]' \
81                 {-n,--lines=}'[Number of journal entries to show]:integer' \
82                 '--no-tail[Show all lines, even in follow mode]' \
83                 {-o,--output=}'[Change journal output mode]:output modes:_outputmodes' \
84                 {-l,--full}'[Show long fields in full]' \
85                 {-a,--all}'[Show all fields, including long and unprintable]' \
86                 {-q,--quiet}"[Don't show privilege warning]" \
87                 '--no-pager[Do not pipe output into a pager]' \
88                 {-m,--merge}'[Show entries from all available journals]' \
89                 {-D,--directory=}'[Show journal files from directory]:directories:_directories' \
90                 '--interval=[Time interval for changing the FSS sealing key]:time interval' \
91                 '--verify-key=[Specify FSS verification key]:FSS key' \
92                 {-h,--help}'[Show this help]' \
93                 '--version[Show package version]' \
94                 '--new-id128[Generate a new 128 Bit ID]' \
95                 '--header[Show journal header information]' \
96                 '--disk-usage[Show total disk usage]' \
97                 {-F,--field=}'[List all values a certain field takes]:Fields:_list_fields' \
98                 '--setup-keys[Generate new FSS key pair]' \
99                 '--verify[Verify journal file consistency]' \
100                 '--list-catalog[List messages in catalog]' \
101                 '--update-catalog[Update binary catalog database]' \
102                 '*::default: _journal_none'
103         ;;
104         localectl)
105             _arguments \
106                 {-h,--help}'[Show this help]' \
107                 '--version[Show package version]' \
108                 "--no-convert[Don't convert keyboard mappings]" \
109                 '--no-pager[Do not pipe output into a pager]' \
110                 '--no-ask-password[Do not prompt for password]' \
111                 {-H,--host=}'[Operate on remote host]:userathost:_hosts_or_user_at_host' \
112                 '*::localectl commands:_localectl_command'
113         ;;
114         systemd-coredumpctl)
115             _arguments \
116                 {-o,--output=}'[Write output to FILE]:output file:_files' \
117                 '--no-pager[Do not pipe output into a pager]' \
118                 {-h,--help}'[Show this help]' \
119                 '--version[Show package version]' \
120                 '*::systemd-coredumpctl commands:_systemd-coredumpctl_command'
121
122         ;;
123         timedatectl)
124             _arguments -s \
125                 {-h,--help}'[Show this help]' \
126                 '--version[Show package version]' \
127                 '--adjust-system-clock[Adjust system clock when changing local RTC mode]' \
128                 '--no-pager[Do not pipe output into a pager]' \
129                 '--no-ask-password[Do not prompt for password]' \
130                 {-H,--host=}'[Operate on remote host]:userathost:_hosts_or_user_at_host' \
131                 '*::timedatectl commands:_timedatectl_command'
132         ;;
133         udevadm)
134             _arguments \
135                 '--debug[Print debug messages to stderr]' \
136                 '--version[Print version number]' \
137                 '--help[Print help text]' \
138                 '*::udevadm commands:_udevadm_command'
139         ;;
140         systemd-analyze)
141             _arguments \
142                 {-h,--help}'[Show help text.]' \
143                 '--user[Shows performance data of user sessions instead of the system manager.]' \
144                 '--order[When generating graph for dot, show only order]' \
145                 '--require[When generating graph for dot, show only requirement]' \
146                 '*::systemd-analyze commands:_systemd_analyze_command'
147         ;;
148         systemd-ask-password)
149             _arguments \
150                 {-h,--help}'[Show this help]' \
151                 '--icon=[Icon name]' \
152                 '--timeout=[Timeout in sec]' \
153                 '--no-tty[Ask question via agent even on TTY]' \
154                 '--accept-cached[Accept cached passwords]' \
155                 '--multiple[List multiple passwords if available]'
156         ;;
157         systemd-cat)
158             _arguments \
159                 {-h,--help}'[Show this help]' \
160                 '--version[Show package version.]' \
161                 {-t,--identifier=}'[Set syslog identifier.]' \
162                 {-p,--priority=}'[Set priority value.]:value:({0..7})' \
163                 '--level-prefix=[Control whether level prefix shall be parsed.]:boolean:(1 0)' \
164                 ':Message'
165         ;;
166         systemd-cgls)
167             _arguments \
168                 {-h,--help}'[Show this help]' \
169                 '--version[Show package version]' \
170                 '--no-pager[Do not pipe output into a pager]' \
171                 {-a,--all}'[Show all groups, including empty]' \
172                 '-k[Include kernel threads in output]' \
173                 ':cgroups:(cpuset cpu cpuacct memory devices freezer net_cls blkio)'
174         ;;
175         systemd-cgtop)
176             _arguments \
177                 {-h,--help}'[Show this help]' \
178                 '--version[Print version and exit]' \
179                 '(-c -m -i -t)-p[Order by path]' \
180                 '(-c -p -m -i)-t[Order by number of tasks]' \
181                 '(-m -p -i -t)-c[Order by CPU load]' \
182                 '(-c -p -i -t)-m[Order by memory load]' \
183                 '(-c -m -p -t)-i[Order by IO load]' \
184                 {-d,--delay=}'[Specify delay]' \
185                 {-n,--iterations=}'[Run for N iterations before exiting]' \
186                 {-b,--batch}'[Run in batch mode, accepting no input]' \
187                 '--depth=[Maximum traversal depth]'
188         ;;
189         systemd-delta)
190             _arguments \
191                 {-h,--help}'[Show this help]' \
192                 '--version[Show package version]' \
193                 '--no-pager[Do not pipe output into a pager]' \
194                 '--diff=[Show a diff when overridden files differ]:boolean:(1 0)' \
195                 {-t,--type=}'[Only display a selected set of override types]:types:(masked equivalent redirected overridden unchanged)' \
196                 ':SUFFIX:(tmpfiles.d sysctl.d systemd/system)'
197         ;;
198         systemd-detect-virt)
199             _arguments \
200                 {-h,--help}'[Show this help]' \
201                 '--version[Show package version]' \
202                 {-c,--container}'[Only detect whether we are run in a container]' \
203                 {-v,--vm}'[Only detect whether we are run in a VM]' \
204                 {-q,--quiet}"[Don't output anything, just set return value]"
205         ;;
206         systemd-inhibit)
207             _arguments \
208                 {-h,--help}'[Show this help]' \
209                 '--version[Show package version]' \
210                 '--what=[Operations to inhibit]:options:(shutdown sleep idle handle-power-key handle-suspend-key handle-hibernate-key handle-lid-switch)' \
211                 '--who=[A descriptive string who is inhibiting]' \
212                 '--why=[A descriptive string why is being inhibited]' \
213                 '--mode=[One of block or delay]' \
214                 '--list[List active inhibitors]' \
215                 '*:commands:_systemd_inhibit_command'
216         ;;
217         systemd-machine-id-setup)
218             _arguments \
219                 {-h,--help}'[Show this help]' \
220                 '--version[Show package version]'
221         ;;
222         systemd-notify)
223             _arguments \
224                 {-h,--help}'[Show this help]' \
225                 '--version[Show package version]' \
226                 '--ready[Inform the init system about service start-up completion.]' \
227                 '--pid=[Inform the init system about the main PID of the daemon]' \
228                 '--status=[Send a free-form status string for the daemon to the init systemd]' \
229                 '--booted[Returns 0 if the system was booted up with systemd]' \
230                 '--readahead=[Controls disk read-ahead operations]:arguments:(cancel done noreply)'
231         ;;
232         systemd-nspawn)
233             _arguments \
234                 {-h,--help}'[Show this help]' \
235                 {--directory=,-D}'[Directory to use as file system root for the namespace container. If omitted the current directory will be used.]:directories:_directories' \
236                 {--boot,-b}'[Automatically search for an init binary and invoke it instead of a shell or a user supplied program.]' \
237                 {--user=,-u}'[Run the command under specified user, create home directory and cd into it.]' \
238                 '--uuid=[Set the specified uuid for the container.]' \
239                 {--controllers=,-C}'[Makes the container appear in other hierarchies than the name=systemd:/ one. Takes a comma-separated list of controllers.]' \
240                 '--private-network[Turn off networking in the container. This makes all network interfaces unavailable in the container, with the exception of the loopback device.]' \
241                 '--read-only[Mount the root file system read only for the container.]' \
242                 '--capability=[List one or more additional capabilities to grant the container.]:capabilities:_systemd-nspawn' \
243                 "--link-journal=[Control whether the container's journal shall be made visible to the host system.]:options:(no, host, guest, auto)" \
244                 '-j[Equivalent to --link-journal=guest.]'
245         ;;
246         systemd-tmpfiles)
247             _arguments \
248                 '--create[Create, set ownership/permissions based on the config files.]' \
249                 '--clean[Clean up all files and directories with an age parameter configured.]' \
250                 '--remove[All files and directories marked with r, R in the configuration files are removed.]' \
251                 '--prefix=[Only apply rules that apply to paths with the specified prefix.]' \
252                 '--exclude-prefix=[Ignore rules that apply to paths with the specified prefix.]' \
253                 '--help[Prints a short help text and exits.]' \
254                 '*::files:_files'
255         ;;
256         systemd-tty-ask-password-agent)
257             _arguments \
258                 {-h,--help}'[Prints a short help text and exits.]' \
259                 '--version[Prints a short version string and exits.]' \
260                 '--list[Lists all currently pending system password requests.]' \
261                 '--query[Process all currently pending system password requests by querying the user on the calling TTY.]' \
262                 '--watch[Continuously process password requests.]' \
263                 '--wall[Forward password requests to wall(1).]' \
264                 '--plymouth[Ask question with plymouth(8).]' \
265                 '--console[Ask question on /dev/console.]'
266         ;;
267         machinectl)
268             _arguments \
269                 {-h,--help}'[Prints a short help text and exits.]' \
270                 '--version[Prints a short version string and exits.]' \
271                 {-p,--property=}'[Limit output to specified property.]:property:(Name Id Timestamp TimestampMonotonic Service Scope Leader Class State RootDirectory)' \
272                 {-a,--all}'[Show all proerties]' \
273                 (-l,--full)'[Do not ellipsize cgroup members]' \
274                 '--no-pager[Do not pipe output into a pager]' \
275                 '--no-ask-password[Do not ask for system passwords]' \
276                 '--kill-who=[Who to send signal to]:killwho:(leader all)' \
277                 {-s,--signal=}'[Which signal to send]:signal:_signals' \
278                 {-H,--host=}'[Show information for remote host]:userathost:_hosts_or_user_at_host' \
279                 {-P,--privileged}'[Acquire privileges before execution]' \
280                 '*::machinectl command:_machinectl_command'
281         ;;
282         *) _message 'eh?' ;;
283     esac
284 }
285
286 _systemd-nspawn(){
287     local -a _caps
288     _caps=( CAP_CHOWN CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH
289             CAP_FOWNER CAP_FSETID CAP_IPC_OWNER CAP_KILL CAP_LEASE CAP_LINUX_IMMUTABLE
290             CAP_NET_BIND_SERVICE CAP_NET_BROADCAST CAP_NET_RAW CAP_SETGID CAP_SETFCAP CAP_SETPCAP
291             CAP_SETUID CAP_SYS_ADMIN CAP_SYS_CHROOT CAP_SYS_NICE CAP_SYS_PTRACE CAP_SYS_TTY_CONFIG
292             CAP_SYS_RESOURCE CAP_SYS_BOOT )
293     _values -s , 'capabilities' "$_caps[@]"
294 }
295
296 _systemd_inhibit_command(){
297     if (( CURRENT == 1 )); then
298         compset -q
299         _normal
300     else
301         local n=${words[(b:2:i)[^-]*]}
302         if (( n <= CURRENT )); then
303             compset -n $n
304             _alternative \
305                 'files:file:_files' \
306                 'commands:command:_normal' && return 0
307         fi
308         _default
309     fi
310
311 }
312
313 _systemd_analyze_command(){
314     local -a _systemd_analyze_cmds
315     # Descriptions taken from systemd-analyze --help.
316     _systemd_analyze_cmds=(
317         'time:Print time spent in the kernel before reaching userspace'
318         'blame:Print list of running units ordered by time to init'
319         'critical-chain:Print a tree of the time critical chain of units'
320         'plot:Output SVG graphic showing service initialization'
321         'dot:Dump dependency graph (in dot(1) format)'
322     )
323
324     if (( CURRENT == 1 )); then
325         _describe "options" _systemd_analyze_cmds
326     else
327         _message "no more options"
328     fi
329 }
330
331 _hosts_or_user_at_host()
332 {
333   _alternative \
334     'users-hosts:: _user_at_host' \
335     'hosts:: _hosts'
336 }
337
338 _outputmodes() {
339     local -a _output_opts
340     _output_opts=(short short-monotonic verbose export json json-pretty json-see cat)
341     _describe -t output 'output mode' _output_opts || compadd "$@"
342 }
343
344
345 (( $+functions[_systemctl_command] )) || _systemctl_command()
346 {
347   local -a _systemctl_cmds
348   _systemctl_cmds=(
349     "list-units:List units"
350     "start:Start (activate) one or more units"
351     "stop:Stop (deactivate) one or more units"
352     "reload:Reload one or more units"
353     "restart:Start or restart one or more units"
354     "condrestart:Restart one or more units if active"
355     "try-restart:Restart one or more units if active"
356     "reload-or-restart:Reload one or more units if possible, otherwise start or restart"
357     "force-reload:Reload one or more units if possible, otherwise restart if active"
358     "hibernate:Hibernate the system"
359     "hybrid-sleep:Hibernate and suspend the system"
360     "reload-or-try-restart:Reload one or more units if possible, otherwise restart if active"
361     "isolate:Start one unit and stop all others"
362     "kill:Send signal to processes of a unit"
363     "is-active:Check whether units are active"
364     "is-failed:Check whether units are failed"
365     "status:Show runtime status of one or more units"
366     "show:Show properties of one or more units/jobs or the manager"
367     "reset-failed:Reset failed state for all, one, or more units"
368     "load:Load one or more units"
369     "list-unit-files:List installed unit files"
370     "enable:Enable one or more unit files"
371     "disable:Disable one or more unit files"
372     "reenable:Reenable one or more unit files"
373     "preset:Enable/disable one or more unit files based on preset configuration"
374     "help:Show documentation for specified units"
375     "list-dependencies:Show unit dependency tree"
376     "mask:Mask one or more units"
377     "unmask:Unmask one or more units"
378     "link:Link one or more units files into the search path"
379     "is-enabled:Check whether unit files are enabled"
380     "list-jobs:List jobs"
381     "cancel:Cancel all, one, or more jobs"
382     "dump:Dump server status"
383     "snapshot:Create a snapshot"
384     "delete:Remove one or more snapshots"
385     "show-environment:Dump environment"
386     "set-environment:Set one or more environment variables"
387     "unset-environment:Unset one or more environment variables"
388     "daemon-reload:Reload systemd manager configuration"
389     "daemon-reexec:Reexecute systemd manager"
390     "default:Enter system default mode"
391     "rescue:Enter system rescue mode"
392     "emergency:Enter system emergency mode"
393     "halt:Shut down and halt the system"
394     "suspend:Suspend the system"
395     "poweroff:Shut down and power-off the system"
396     "reboot:Shut down and reboot the system"
397     "kexec:Shut down and reboot the system with kexec"
398     "exit:Ask for user instance termination"
399   )
400
401   if (( CURRENT == 1 )); then
402     _describe -t commands 'systemctl command' _systemctl_cmds || compadd "$@"
403   else
404     local curcontext="$curcontext"
405
406     cmd="${${_systemctl_cmds[(r)$words[1]:*]%%:*}}"
407     # Deal with any aliases
408     case $cmd in
409       condrestart) cmd="try-restart";;
410       force-reload) cmd="reload-or-try-restart";;
411     esac
412
413     if (( $#cmd )); then
414       curcontext="${curcontext%:*:*}:systemctl-${cmd}:"
415
416       local update_policy
417       zstyle -s ":completion:${curcontext}:" cache-policy update_policy
418       if [[ -z "$update_policy" ]]; then
419         zstyle ":completion:${curcontext}:" cache-policy _systemctl_caching_policy
420       fi
421
422       _call_function ret _systemctl_$cmd || _message 'no more arguments'
423     else
424       _message "unknown systemctl command: $words[1]"
425     fi
426     return ret
427   fi
428 }
429
430 __systemctl()
431 {
432   local -a _modes
433   _modes=("--user" "--system")
434   systemctl ${words:*_modes} --full --no-legend --no-pager "$@"
435 }
436
437
438 # Fills the unit list
439 _systemctl_all_units()
440 {
441   if ( [[ ${+_sys_all_units} -eq 0 ]] || _cache_invalid SYS_ALL_UNITS ) &&
442     ! _retrieve_cache SYS_ALL_UNITS;
443   then
444     _sys_all_units=( $(__systemctl list-units --all | { while read a b; do echo " $a"; done; }) )
445     _store_cache SYS_ALL_UNITS _sys_all_units
446   fi
447 }
448
449 # Fills the unit list including all file units
450 _systemctl_really_all_units()
451 {
452   local -a all_unit_files;
453   local -a really_all_units;
454   if ( [[ ${+_sys_really_all_units} -eq 0 ]] || _cache_invalid SYS_REALLY_ALL_UNITS ) &&
455     ! _retrieve_cache SYS_REALLY_ALL_UNITS;
456   then
457     all_unit_files=( $(__systemctl list-unit-files | { while read a b; do echo " $a"; done; }) )
458     _systemctl_all_units
459     really_all_units=($_sys_all_units $all_unit_files)
460     _sys_really_all_units=(${(u)really_all_units})
461     _store_cache SYS_REALLY_ALL_UNITS _sys_really_all_units
462   fi
463 }
464
465 _filter_units_by_property() {
466   local property=$1 value=$2 ; shift ; shift
467   local -a units ; units=($*)
468   local prop unit
469   for ((i=1; $i <= ${#units[*]}; i++)); do
470     # FIXME: "Failed to issue method call: Unknown unit" errors are ignored for
471     # now (related to DBUS_ERROR_UNKNOWN_OBJECT). in the future, we need to
472     # revert to calling 'systemctl show' once for all units, which is way
473     # faster
474     unit=${units[i]}
475     prop=${(f)"$(_call_program units "$service show --no-pager --property="$property" ${unit} 2>/dev/null")"}
476     if [[ "${prop}" = "$property=$value" ]]; then
477       echo " ${unit}"
478     fi
479   done
480 }
481
482 _systemctl_active_units()  {_sys_active_units=(  $(__systemctl list-units          | { while read a b; do echo " $a"; done; }) )}
483 _systemctl_inactive_units(){_sys_inactive_units=($(__systemctl list-units --all    | { while read a b c d; do [[ $c == "inactive" || $c == "failed" ]] && echo " $a"; done; }) )}
484 _systemctl_failed_units()  {_sys_failed_units=(  $(__systemctl list-units --failed | { while read a b; do echo " $a"; done; }) )}
485 _systemctl_enabled_units() {_sys_enabled_units=( $(__systemctl list-unit-files     | { while read a b; do [[ $b == "enabled" ]] && echo " $a"; done; }) )}
486 _systemctl_disabled_units(){_sys_disabled_units=($(__systemctl list-unit-files     | { while read a b; do [[ $b == "disabled" ]] && echo " $a"; done; }) )}
487 _systemctl_masked_units()  {_sys_masked_units=(  $(__systemctl list-unit-files     | { while read a b; do [[ $b == "masked" ]] && echo " $a"; done; }) )}
488
489 # Completion functions for ALL_UNITS
490 for fun in is-active is-failed is-enabled status show mask preset help list-dependencies ; do
491   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
492   {
493     _systemctl_really_all_units
494     compadd "$@" -a - _sys_really_all_units
495   }
496 done
497
498 # Completion functions for ENABLED_UNITS
499 for fun in disable reenable ; do
500   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
501   {
502     _systemctl_enabled_units
503     _systemctl_disabled_units
504     compadd "$@" -a - _sys_enabled_units _sys_disabled_units
505   }
506 done
507
508 # Completion functions for DISABLED_UNITS
509 (( $+functions[_systemctl_enable] )) || _systemctl_enable()
510 {
511   _systemctl_disabled_units
512   compadd "$@" -a - _sys_disabled_units
513 }
514
515 # Completion functions for FAILED_UNITS
516 (( $+functions[_systemctl_reset-failed] )) || _systemctl_reset-failed()
517 {
518   _systemctl_failed_units
519   compadd "$@" -a - _sys_failed_units || _message "no failed unit found"
520 }
521
522 # Completion functions for STARTABLE_UNITS
523 (( $+functions[_systemctl_start] )) || _systemctl_start()
524 {
525   _systemctl_inactive_units
526   compadd "$@" -a - _sys_inactive_units
527 }
528
529 # Completion functions for STOPPABLE_UNITS
530 for fun in stop kill try-restart condrestart ; do
531   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
532   {
533     _systemctl_active_units
534     compadd "$@" - $( _filter_units_by_property CanStop yes \
535       ${_sys_active_units[*]} )
536   }
537 done
538
539 # Completion functions for ISOLATABLE_UNITS
540 (( $+functions[_systemctl_isolate] )) || _systemctl_isolate()
541 {
542   _systemctl_all_units
543   compadd "$@" - $( _filter_units_by_property AllowIsolate yes \
544     ${_sys_all_units[*]} )
545 }
546
547 # Completion functions for RELOADABLE_UNITS
548 for fun in reload reload-or-try-restart force-reload ; do
549   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
550   {
551     _systemctl_active_units
552     compadd "$@" - $( _filter_units_by_property CanReload yes \
553       ${_sys_active_units[*]} )
554   }
555 done
556
557 # Completion functions for RESTARTABLE_UNITS
558 for fun in restart reload-or-restart ; do
559   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
560   {
561     _systemctl_all_units
562     compadd "$@" - $( _filter_units_by_property CanStart yes \
563       ${_sys_all_units[*]} | while read line; do \
564       [[ "$line" =~ \.device$ ]] || echo " $line"; \
565       done )
566   }
567 done
568
569 # Completion functions for MASKED_UNITS
570 (( $+functions[_systemctl_unmask] )) || _systemctl_unmask()
571 {
572   _systemctl_masked_units
573   compadd "$@" -a - _sys_masked_units || _message "no masked unit found"
574 }
575
576 # Completion functions for JOBS
577 (( $+functions[_systemctl_cancel] )) || _systemctl_cancel()
578 {
579   compadd "$@" - $(__systemctl list-jobs \
580     | cut -d' ' -f1  2>/dev/null ) || _message "no job found"
581 }
582
583 # Completion functions for SNAPSHOTS
584 (( $+functions[_systemctl_delete] )) || _systemctl_delete()
585 {
586   compadd "$@" - $(__systemctl list-units --type snapshot --all \
587     | cut -d' ' -f1  2>/dev/null ) || _message "no snapshot found"
588 }
589
590 # Completion functions for ENVS
591 for fun in set-environment unset-environment ; do
592   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
593   {
594     local fun=$0 ; fun=${fun##_systemctl_}
595     local suf
596     if [[ "${fun}" = "set-environment" ]]; then
597       suf='-S='
598     fi
599
600     compadd "$@" ${suf} - $(systemctl show-environment \
601       | while read line; do echo " ${line%%\=}";done )
602   }
603 done
604
605 (( $+functions[_systemctl_link] )) || _systemctl_link() { _files }
606
607 # no systemctl completion for:
608 #    [STANDALONE]='daemon-reexec daemon-reload default dump
609 #                  emergency exit halt kexec list-jobs list-units
610 #                  list-unit-files poweroff reboot rescue show-environment'
611 #         [NAME]='snapshot load'
612
613 _systemctl_caching_policy()
614 {
615   local _sysunits
616   local -a oldcache
617
618   # rebuild if cache is more than a day old
619   oldcache=( "$1"(mh+1) )
620   (( $#oldcache )) && return 0
621
622   _sysunits=($(__systemctl --all | cut -d' ' -f1))
623
624   if (( $#_sysunits )); then
625     for unit in $_sysunits; do
626       [[ "$unit" -nt "$1" ]] && return 0
627     done
628   fi
629
630   return 1
631 }
632
633 _list_fields() {
634     local -a journal_fields
635     journal_fields=(MESSAGE{,_ID} PRIORITY CODE_{FILE,LINE,FUNC}
636                     ERRNO SYSLOG_{FACILITY,IDENTIFIER,PID}
637                     _{P,U,G}ID _COMM _EXE _CMDLINE
638                     _AUDIT_{SESSION,LOGINUID}
639                     _SYSTEMD_{CGROUP,SESSION,UNIT,OWNER_UID}
640                     _SYSTEMD_USER_UNIT
641                     _SELINUX_CONTEXT _SOURCE_REALTIME_TIMESTAMP
642                     _{BOOT,MACHINE}_ID _HOSTNAME _TRANSPORT
643                     _KERNEL_{DEVICE,SUBSYSTEM}
644                     _UDEV_{SYSNAME,DEVNODE,DEVLINK}
645                     __CURSOR __{REALTIME,MONOTONIC}_TIMESTAMP)
646     _describe 'possible fields' journal_fields
647 }
648
649 _journal_none() {
650     local -a _commands _files
651     _commands=( ${(f)"$(_call_program commands "$service" -F _EXE 2>/dev/null)"} )
652     _alternative : \
653         'files:/dev files:_files -W /dev -P /dev/' \
654         "commands:commands:($_commands[@])" \
655         'fields:fields:_list_fields'
656 }
657
658 _journal_fields() {
659     local -a _fields cmd
660     cmd=("journalctl" "-F ${@[-1]}" "2>/dev/null" )
661     _fields=( ${(f)"$(_call_program fields $cmd[@])"} )
662     typeset -U _fields
663     _describe 'possible values' _fields
664 }
665
666
667 _loginctl_all_sessions(){_sys_all_sessions=($(loginctl list-sessions | { while read a b; do echo " $a"; done; }) )}
668 _loginctl_all_users()   {_sys_all_users=(   $(loginctl list-users    | { while read a b; do echo " $a"; done; }) )}
669 _loginctl_all_seats()   {_sys_all_seats=(   $(loginctl list-seats    | { while read a b; do echo " $a"; done; }) )}
670
671 # Completion functions for SESSIONS
672 for fun in session-status show-session activate lock-session unlock-session terminate-session kill-session ; do
673   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
674   {
675     _loginctl_all_sessions
676     compadd "$@" -a - _sys_all_sessions
677   }
678 done
679
680 # Completion functions for USERS
681 for fun in user-status show-user enable-linger disable-linger terminate-user kill-user ; do
682   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
683   {
684     _loginctl_all_users
685     compadd "$@" -a - _sys_all_users
686   }
687 done
688
689 # Completion functions for SEATS
690 (( $+functions[_loginctl_seats] )) || _loginctl_seats()
691 {
692   _loginctl_all_seats
693   compadd "$@" -a - _sys_all_seats
694 }
695 for fun in seat-status show-seat terminate-seat ; do
696   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
697   { _loginctl_seats }
698 done
699
700 # Completion functions for ATTACH
701 (( $+functions[_loginctl_attach] )) || _loginctl_attach()
702 {
703   _loginctl_all_seats
704
705   _arguments -w -C -S -s \
706     ':seat:_loginctl_seats' \
707     '*:device:_files'
708 }
709
710 # no loginctl completion for:
711 # [STANDALONE]='list-sessions list-users list-seats flush-devices'
712
713 (( $+functions[_loginctl_command] )) || _loginctl_command()
714 {
715   local -a _loginctl_cmds
716   _loginctl_cmds=(
717     "list-sessions:List sessions"
718     "session-status:Show session status"
719     "show-session:Show properties of one or more sessions"
720     "activate:Activate a session"
721     "lock-session:Screen lock one or more sessions"
722     "unlock-session:Screen unlock one or more sessions"
723     "terminate-session:Terminate one or more sessions"
724     "kill-session:Send signal to processes of a session"
725     "list-users:List users"
726     "user-status:Show user status"
727     "show-user:Show properties of one or more users"
728     "enable-linger:Enable linger state of one or more users"
729     "disable-linger:Disable linger state of one or more users"
730     "terminate-user:Terminate all sessions of one or more users"
731     "kill-user:Send signal to processes of a user"
732     "list-seats:List seats"
733     "seat-status:Show seat status"
734     "show-seat:Show properties of one or more seats"
735     "attach:Attach one or more devices to a seat"
736     "flush-devices:Flush all device associations"
737     "terminate-seat:Terminate all sessions on one or more seats"
738   )
739
740   if (( CURRENT == 1 )); then
741     _describe -t commands 'loginctl command' _loginctl_cmds || compadd "$@"
742   else
743     local curcontext="$curcontext"
744
745     cmd="${${_loginctl_cmds[(r)$words[1]:*]%%:*}}"
746
747     if (( $#cmd )); then
748       curcontext="${curcontext%:*:*}:loginctl-${cmd}:"
749
750       _call_function ret _loginctl_$cmd || _message 'no more arguments'
751     else
752       _message "unknown loginctl command: $words[1]"
753     fi
754     return ret
755   fi
756 }
757
758 _hostnamectl_command() {
759     local -a _hostnamectl_cmds
760     _hostnamectl_cmds=(
761         "status:Show current hostname settings"
762         "set-hostname:Set system hostname"
763         "set-icon-name:Set icon name for host"
764     )
765     if (( CURRENT == 1 )); then
766         _describe -t commands 'hostnamectl commands' _hostnamectl_cmds || compadd "$@"
767     else
768         local curcontext="$curcontext"
769         cmd="${${_hostnamectl_cmds[(r)$words[1]:*]%%:*}}"
770         if (( $#cmd )); then
771             [[ $cmd == status ]] && msg="no options" || msg="options for $cmd"
772             _message "$msg"
773         else
774             _message "unknown hostnamectl command: $words[1]"
775         fi
776     fi
777 }
778
779 _localectl_set-locale() {
780     local -a _confs _locales
781     local expl suf
782     _locales=( ${(f)"$(_call_program locales "$service" list-locales)"} )
783     _confs=( ${${(f)"$(_call_program confs "locale 2>/dev/null")"}%\=*} )
784     if [[ -prefix 1 *\= ]]; then
785         local conf=${PREFIX%%\=*}
786         compset -P1 '*='
787         _wanted locales expl "locales configs" \
788             _combination localeconfs  confs=$conf locales "$@" -
789     else
790         compadd -S '='  $_confs
791     fi
792 }
793
794 _localectl_set-keymap() {
795     local -a _keymaps
796     _keymaps=( ${(f)"$(_call_program locales "$service" list-keymaps)"} )
797     if (( CURRENT <= 3 )); then
798         _describe keymaps _keymaps
799     else
800         _message "no more options"
801     fi
802 }
803
804 _localectl_set-x11-keymap() {
805     if (( $+commands[pkg-config] )); then
806         local -a _file _layout _model _variant _options
807         local _xorg_lst
808         _xorg_lst=${"$($commands[pkg-config] xkeyboard-config --variable=xkb_base)"}
809         _file=( ${(ps:\n\!:)"$(<$_xorg_lst/rules/xorg.lst)"} )
810         _layout=( ${${${(M)${(f)_file[1]}:#  *}#  }%% *} )
811         _model=( ${${${(M)${(f)_file[2]}:#  *}#  }%% *} )
812         _variant=( ${${${(M)${(f)_file[3]}:#  *}#  }%% *} )
813         _options=( ${${${(M)${(f)_file[4]}:#  *}#  }%% *} )
814         #_layout=( ${(f)"$( echo $_file[1] | awk '/^  / {print $1}' )"} )
815         #_model=( ${(f)"$(echo $_file[2] | awk '/^  / {print $1}')"} )
816         #_variant=( ${(f)"$(echo $_file[3] | awk '/^  / {print $1}')"} )
817         #_options=( ${(f)"$(echo ${_file[4]//:/\\:} | awk '/^  / {print $1}')"} )
818
819         case $CURRENT in
820             2) _describe layouts _layout ;;
821             3) _describe models _model;;
822             4) _describe variants _variant;;
823             5) _describe options _options;;
824             *) _message "no more options"
825         esac
826     fi
827 }
828
829
830 _localectl_command() {
831     local -a _localectl_cmds
832     _localectl_cmds=(
833         'status:Show current locale settings'
834         'set-locale:Set system locale'
835         'list-locales:Show known locales'
836         'set-keymap:Set virtual console keyboard mapping'
837         'list-keymaps:Show known virtual console keyboard mappings'
838         'set-x11-keymap:Set X11 keyboard mapping'
839     )
840     if (( CURRENT == 1 )); then
841         _describe -t commands 'localectl command' _localectl_cmds
842     else
843         local curcontext="$curcontext"
844         cmd="${${_localectl_cmds[(r)$words[1]:*]%%:*}}"
845         if (( $+functions[_localectl_$cmd] )); then
846             _localectl_$cmd
847         else
848             _message "no more options"
849         fi
850     fi
851 }
852
853 _timedatectl_set-timezone(){
854     local -a _timezones
855     _timezones=( ${(f)"$(_call_program timezones "${service}" list-timezones)"} )
856     compadd "$_timezones[@]"
857 }
858
859 _timedatectl_set-time(){
860     _message "YYYY-MM-DD HH:MM:SS"
861 }
862
863 _timedatectl_set-local-rtc(){
864     local -a _options
865     _options=(
866         '0:Maintain RTC in universal time'
867         '1:Maintain RTC in local time'
868     )
869     _describe options _options
870 }
871
872 _timedatectl_set-ntp(){
873     local -a _options
874     _options=(
875         '0:Disable NTP based network time configuration'
876         '1:Enable NTP based network time configuration'
877     )
878     _describe options _options
879 }
880
881 _timedatectl_command(){
882     local -a _timedatectl_cmds
883     _timedatectl_cmds=(
884         'status:Show current time settings'
885         'set-time:Set system time'
886         'set-timezone:Set system timezone'
887         'list-timezones:Show known timezones'
888         'set-local-rtc:Control whether RTC is in local time'
889         'set-ntp:Control whether NTP is enabled'
890     )
891     if (( CURRENT == 1 )); then
892         _describe -t commands 'timedatectl command' _timedatectl_cmds
893     else
894         local curcontext="$curcontext"
895         cmd="${${_timedatectl_cmds[(r)$words[1]:*]%%:*}}"
896         if (( $#cmd )); then
897             if (( $+functions[_timedatectl_$cmd] )); then
898                 _timedatectl_$cmd
899             else
900                 _message "no more options"
901             fi
902         else
903             _message "unknown timedatectl command: $words[1]"
904         fi
905     fi
906 }
907 _systemd-coredumpctl_command(){
908     local -a _systemd_coredumpctl_cmds
909     _systemd_coredumpctl_cmds=(
910             'list:List available coredumps'
911             'dump:Print coredump to std'
912     )
913     if (( CURRENT == 1 )); then
914         _describe -t commands 'systemd-coredumpctl command' _systemd_coredumpctl_cmds
915     else
916         local curcontext="$curcontext"
917         local -a _dumps
918         cmd="${${_systemd_coredumpctl_cmds[(r)$words[1]:*]%%:*}}"
919         if (( $#cmd  )); then
920                         # user can set zstyle ':completion:*:*:systemd-coredumpctl:*' sort no for coredumps to be ordered by date, otherwise they get ordered by pid
921                         _dumps=( "${(foa)$(systemd-coredumpctl list | awk 'BEGIN{OFS=":"} /^\s/ {sub(/[[ \t]+/, ""); print $5,$0}' 2>/dev/null)}" )
922             if [[ -n "$_dumps" ]]; then
923                 _describe -t pids 'coredumps' _dumps
924             else
925                 _message "no coredumps"
926             fi
927         else
928             _message "no more options"
929         fi
930
931     fi
932
933 }
934
935 (( $+functions[_machinectl_command] )) || _machinectl_command()
936 {
937   local -a _machinectl_cmds
938   _machinectl_cmds=(
939     "list:List currently running VMs/containers"
940     "status:Show VM/container status"
941     "show:Show properties of one or more VMs/containers"
942     "terminate:Terminate one or more VMs/containers"
943     "kill:Send signal to process or a VM/container"
944   )
945   if (( CURRENT == 1 )); then
946     _describe -t commands 'machinectl command' _machinectl_cmds || compadd "$@"
947   else
948     local curcontext="$curcontext"
949     cmd="${${_machinectl_cmds[(r)$words[1]:*]%%:*}}"
950     if (( $#cmd )); then
951       case $cmd in
952         list) msg="no options" ;;
953         *)
954           _machines=( "${(foa)$(machinectl list | awk '{print $1}')}" )
955           if [[ -n "$_machines" ]]; then
956             _describe 'machines' _machines
957           else
958             _message 'no machines'
959           fi
960       esac
961     else
962       _message "no more options"
963     fi
964   fi
965 }
966
967 _udevadm_info(){
968     _arguments \
969         '--query=[Query the database for specified type of device data. It needs the --path or --name to identify the specified device.]:type:(name symlink path property all)' \
970         '--path=[The devpath of the device to query.]:sys files:_files -P /sys/ -W /sys' \
971         '--name=[The name of the device node or a symlink to query]:device files:_files -P /dev/ -W /dev' \
972         '--root[Print absolute paths in name or symlink query.]' \
973         '--attribute-walk[Print all sysfs properties of the specified device that can be used in udev rules to match the specified device]' \
974         '--export[Print output as key/value pairs.]' \
975         '--export-prefix=[Add a prefix to the key name of exported values.]:prefix' \
976         '--device-id-of-file=[Print major/minor numbers of the underlying device, where the file lives on.]:files:_udevadm_mounts' \
977         '--export-db[Export the content of the udev database.]' \
978         '--cleanup-db[Cleanup the udev database.]'
979 }
980
981 _udevadm_trigger(){
982     _arguments \
983         '--verbose[Print the list of devices which will be triggered.]' \
984         '--dry-run[Do not actually trigger the event.]' \
985         '--type=[Trigger a specific type of devices.]:types:(devices subsystems failed)' \
986         '--action=[Type of event to be triggered.]:actions:(add change remove)' \
987         '--subsystem-match=[Trigger events for devices which belong to a matching subsystem.]' \
988         '--subsystem-nomatch=[Do not trigger events for devices which belong to a matching subsystem.]' \
989         '--attr-match=attribute=[Trigger events for devices with a matching sysfs attribute.]' \
990         '--attr-nomatch=attribute=[Do not trigger events for devices with a matching sysfs attribute.]' \
991         '--property-match=[Trigger events for devices with a matching property value.]' \
992         '--tag-match=property[Trigger events for devices with a matching tag.]' \
993         '--sysname-match=[Trigger events for devices with a matching sys device name.]' \
994         '--parent-match=[Trigger events for all children of a given device.]'
995 }
996
997 _udevadm_settle(){
998     _arguments \
999        '--timeout=[Maximum number of seconds to wait for the event queue to become empty.]' \
1000        '--seq-start=[Wait only for events after the given sequence number.]' \
1001        '--seq-end=[Wait only for events before the given sequence number.]' \
1002        '--exit-if-exists=[Stop waiting if file exists.]:files:_files' \
1003        '--quiet[Do not print any output, like the remaining queue entries when reaching the timeout.]' \
1004        '--help[Print help text.]'
1005 }
1006
1007 _udevadm_control(){
1008     _arguments \
1009         '--exit[Signal and wait for systemd-udevd to exit.]' \
1010         '--log-priority=[Set the internal log level of systemd-udevd.]:priorities:(err info debug)' \
1011         '--stop-exec-queue[Signal systemd-udevd to stop executing new events. Incoming events will be queued.]' \
1012         '--start-exec-queue[Signal systemd-udevd to enable the execution of events.]' \
1013         '--reload[Signal systemd-udevd to reload the rules files and other databases like the kernel module index.]' \
1014         '--property=[Set a global property for all events.]' \
1015         '--children-max=[Set the maximum number of events.]' \
1016         '--timeout=[The maximum number of seconds to wait for a reply from systemd-udevd.]' \
1017         '--help[Print help text.]'
1018 }
1019
1020 _udevadm_monitor(){
1021     _arguments \
1022         '--kernel[Print the kernel uevents.]' \
1023         '--udev[Print the udev event after the rule processing.]' \
1024         '--property[Also print the properties of the event.]' \
1025         '--subsystem-match=[Filter events by subsystem/\[devtype\].]' \
1026         '--tag-match=[Filter events by property.]' \
1027         '--help[Print help text.]'
1028 }
1029
1030 _udevadm_test(){
1031     _arguments \
1032         '--action=[The action string.]:actions:(add change remove)' \
1033         '--subsystem=[The subsystem string.]' \
1034         '--help[Print help text.]' \
1035         '*::devpath:_files -P /sys/ -W /sys'
1036 }
1037
1038 _udevadm_test-builtin(){
1039     if (( CURRENT == 2 )); then
1040     _arguments \
1041         '--help[Print help text]' \
1042         '*::builtins:(blkid btrfs hwdb input_id kmod path_id usb_id uaccess)'
1043     elif  (( CURRENT == 3 )); then
1044         _arguments \
1045             '--help[Print help text]' \
1046             '*::syspath:_files -P /sys -W /sys'
1047     else
1048         _arguments \
1049             '--help[Print help text]'
1050     fi
1051 }
1052
1053 _udevadm_mounts(){
1054   local dev_tmp dpath_tmp mp_tmp mline
1055
1056     tmp=( "${(@f)$(< /etc/mtab)}" )
1057     dev_tmp=( "${(@)${(@)tmp%% *}:#none}" )
1058     mp_tmp=( "${(@)${(@)tmp#* }%% *}" )
1059
1060   local MATCH
1061   mp_tmp=("${(@q)mp_tmp//(#m)\\[0-7](#c3)/${(#)$(( 8#${MATCH[2,-1]} ))}}")
1062   dpath_tmp=( "${(@Mq)dev_tmp:#/*}" )
1063   dev_tmp=( "${(@q)dev_tmp:#/*}" )
1064
1065   _alternative \
1066     'device-paths: device path:compadd -a dpath_tmp' \
1067     'directories:mount point:compadd -a mp_tmp'
1068 }
1069
1070
1071 _udevadm_command(){
1072     local -a _udevadm_cmds
1073     _udevadm_cmds=(
1074         'info:query sysfs or the udev database'
1075         'trigger:request events from the kernel'
1076         'settle:wait for the event queue to finish'
1077         'control:control the udev daemon'
1078         'monitor:listen to kernel and udev events'
1079         'test:test an event run'
1080         'test-builtin:test a built-in command'
1081     )
1082
1083     if ((CURRENT == 1)); then
1084         _describe -t commands 'udevadm commands' _udevadm_cmds
1085     else
1086         local curcontext="$curcontext"
1087         cmd="${${_udevadm_cmds[(r)$words[1]:*]%%:*}}"
1088         if (($#cmd)); then
1089             if (( $+functions[_udevadm_$cmd] )); then
1090                 _udevadm_$cmd
1091             else
1092                 _message "no options for $cmd"
1093             fi
1094         else
1095             _message "no more options"
1096         fi
1097     fi
1098 }
1099
1100 _ctls "$@"
1101
1102 #vim: set ft=zsh sw=4 ts=4 et