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