chiark / gitweb /
b62b6df946fcfb0b0b22e6bba42fd707e188cea9
[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                 '--help[Prints a short help text and exits.]' \
253                 '*::files:_files'
254         ;;
255         systemd-tty-ask-password-agent)
256             _arguments \
257                 {-h,--help}'[Prints a short help text and exits.]' \
258                 '--version[Prints a short version string and exits.]' \
259                 '--list[Lists all currently pending system password requests.]' \
260                 '--query[Process all currently pending system password requests by querying the user on the calling TTY.]' \
261                 '--watch[Continuously process password requests.]' \
262                 '--wall[Forward password requests to wall(1).]' \
263                 '--plymouth[Ask question with plymouth(8).]' \
264                 '--console[Ask question on /dev/console.]'
265         ;;
266         machinectl)
267             _arguments \
268                 {-h,--help}'[Prints a short help text and exits.]' \
269                 '--version[Prints a short version string and exits.]' \
270                 {-p,--property=}'[Limit output to specified property.]:property:(Name Id Timestamp TimestampMonotonic Service Scope Leader Class State RootDirectory)' \
271                 {-a,--all}'[Show all proerties]' \
272                 (-l,--full)'[Do not ellipsize cgroup members]' \
273                 '--no-pager[Do not pipe output into a pager]' \
274                 '--no-ask-password[Do not ask for system passwords]' \
275                 '--kill-who=[Who to send signal to]:killwho:(leader all)' \
276                 {-s,--signal=}'[Which signal to send]:signal:_signals' \
277                 {-H,--host=}'[Show information for remote host]:userathost:_hosts_or_user_at_host' \
278                 {-P,--privileged}'[Acquire privileges before execution]' \
279                 '*::machinectl command:_machinectl_command'
280         ;;
281         *) _message 'eh?' ;;
282     esac
283 }
284
285 _systemd-nspawn(){
286     local -a _caps
287     _caps=( CAP_CHOWN CAP_DAC_OVERRIDE CAP_DAC_READ_SEARCH
288             CAP_FOWNER CAP_FSETID CAP_IPC_OWNER CAP_KILL CAP_LEASE CAP_LINUX_IMMUTABLE
289             CAP_NET_BIND_SERVICE CAP_NET_BROADCAST CAP_NET_RAW CAP_SETGID CAP_SETFCAP CAP_SETPCAP
290             CAP_SETUID CAP_SYS_ADMIN CAP_SYS_CHROOT CAP_SYS_NICE CAP_SYS_PTRACE CAP_SYS_TTY_CONFIG
291             CAP_SYS_RESOURCE CAP_SYS_BOOT )
292     _values -s , 'capabilities' "$_caps[@]"
293 }
294
295 _systemd_inhibit_command(){
296     if (( CURRENT == 1 )); then
297         compset -q
298         _normal
299     else
300         local n=${words[(b:2:i)[^-]*]}
301         if (( n <= CURRENT )); then
302             compset -n $n
303             _alternative \
304                 'files:file:_files' \
305                 'commands:command:_normal' && return 0
306         fi
307         _default
308     fi
309
310 }
311
312 _systemd_analyze_command(){
313     local -a _systemd_analyze_cmds
314     # Descriptions taken from systemd-analyze --help.
315     _systemd_analyze_cmds=(
316         'time:Print time spent in the kernel before reaching userspace'
317         'blame:Print list of running units ordered by time to init'
318         'critical-chain:Print a tree of the time critical chain of units'
319         'plot:Output SVG graphic showing service initialization'
320         'dot:Dump dependency graph (in dot(1) format)'
321     )
322
323     if (( CURRENT == 1 )); then
324         _describe "options" _systemd_analyze_cmds
325     else
326         _message "no more options"
327     fi
328 }
329
330 _hosts_or_user_at_host()
331 {
332   _alternative \
333     'users-hosts:: _user_at_host' \
334     'hosts:: _hosts'
335 }
336
337 _outputmodes() {
338     local -a _output_opts
339     _output_opts=(short short-monotonic verbose export json json-pretty json-see cat)
340     _describe -t output 'output mode' _output_opts || compadd "$@"
341 }
342
343
344 (( $+functions[_systemctl_command] )) || _systemctl_command()
345 {
346   local -a _systemctl_cmds
347   _systemctl_cmds=(
348     "list-units:List units"
349     "start:Start (activate) one or more units"
350     "stop:Stop (deactivate) one or more units"
351     "reload:Reload one or more units"
352     "restart:Start or restart one or more units"
353     "condrestart:Restart one or more units if active"
354     "try-restart:Restart one or more units if active"
355     "reload-or-restart:Reload one or more units if possible, otherwise start or restart"
356     "force-reload:Reload one or more units if possible, otherwise restart if active"
357     "hibernate:Hibernate the system"
358     "hybrid-sleep:Hibernate and suspend the system"
359     "reload-or-try-restart:Reload one or more units if possible, otherwise restart if active"
360     "isolate:Start one unit and stop all others"
361     "kill:Send signal to processes of a unit"
362     "is-active:Check whether units are active"
363     "is-failed:Check whether units are failed"
364     "status:Show runtime status of one or more units"
365     "show:Show properties of one or more units/jobs or the manager"
366     "reset-failed:Reset failed state for all, one, or more units"
367     "load:Load one or more units"
368     "list-unit-files:List installed unit files"
369     "enable:Enable one or more unit files"
370     "disable:Disable one or more unit files"
371     "reenable:Reenable one or more unit files"
372     "preset:Enable/disable one or more unit files based on preset configuration"
373     "help:Show documentation for specified units"
374     "list-dependencies:Show unit dependency tree"
375     "mask:Mask one or more units"
376     "unmask:Unmask one or more units"
377     "link:Link one or more units files into the search path"
378     "is-enabled:Check whether unit files are enabled"
379     "list-jobs:List jobs"
380     "cancel:Cancel all, one, or more jobs"
381     "dump:Dump server status"
382     "snapshot:Create a snapshot"
383     "delete:Remove one or more snapshots"
384     "show-environment:Dump environment"
385     "set-environment:Set one or more environment variables"
386     "unset-environment:Unset one or more environment variables"
387     "daemon-reload:Reload systemd manager configuration"
388     "daemon-reexec:Reexecute systemd manager"
389     "default:Enter system default mode"
390     "rescue:Enter system rescue mode"
391     "emergency:Enter system emergency mode"
392     "halt:Shut down and halt the system"
393     "suspend:Suspend the system"
394     "poweroff:Shut down and power-off the system"
395     "reboot:Shut down and reboot the system"
396     "kexec:Shut down and reboot the system with kexec"
397     "exit:Ask for user instance termination"
398   )
399
400   if (( CURRENT == 1 )); then
401     _describe -t commands 'systemctl command' _systemctl_cmds || compadd "$@"
402   else
403     local curcontext="$curcontext"
404
405     cmd="${${_systemctl_cmds[(r)$words[1]:*]%%:*}}"
406     # Deal with any aliases
407     case $cmd in
408       condrestart) cmd="try-restart";;
409       force-reload) cmd="reload-or-try-restart";;
410     esac
411
412     if (( $#cmd )); then
413       curcontext="${curcontext%:*:*}:systemctl-${cmd}:"
414
415       local update_policy
416       zstyle -s ":completion:${curcontext}:" cache-policy update_policy
417       if [[ -z "$update_policy" ]]; then
418         zstyle ":completion:${curcontext}:" cache-policy _systemctl_caching_policy
419       fi
420
421       _call_function ret _systemctl_$cmd || _message 'no more arguments'
422     else
423       _message "unknown systemctl command: $words[1]"
424     fi
425     return ret
426   fi
427 }
428
429 __systemctl()
430 {
431   local -a _modes
432   _modes=("--user" "--system")
433   systemctl ${words:*_modes} --full --no-legend --no-pager "$@"
434 }
435
436
437 # Fills the unit list
438 _systemctl_all_units()
439 {
440   if ( [[ ${+_sys_all_units} -eq 0 ]] || _cache_invalid SYS_ALL_UNITS ) &&
441     ! _retrieve_cache SYS_ALL_UNITS;
442   then
443     _sys_all_units=( $(__systemctl list-units --all | { while read a b; do echo " $a"; done; }) )
444     _store_cache SYS_ALL_UNITS _sys_all_units
445   fi
446 }
447
448 # Fills the unit list including all file units
449 _systemctl_really_all_units()
450 {
451   local -a all_unit_files;
452   local -a really_all_units;
453   if ( [[ ${+_sys_really_all_units} -eq 0 ]] || _cache_invalid SYS_REALLY_ALL_UNITS ) &&
454     ! _retrieve_cache SYS_REALLY_ALL_UNITS;
455   then
456     all_unit_files=( $(__systemctl list-unit-files | { while read a b; do echo " $a"; done; }) )
457     _systemctl_all_units
458     really_all_units=($_sys_all_units $all_unit_files)
459     _sys_really_all_units=(${(u)really_all_units})
460     _store_cache SYS_REALLY_ALL_UNITS _sys_really_all_units
461   fi
462 }
463
464 _filter_units_by_property() {
465   local property=$1 value=$2 ; shift ; shift
466   local -a units ; units=($*)
467   local prop unit
468   for ((i=1; $i <= ${#units[*]}; i++)); do
469     # FIXME: "Failed to issue method call: Unknown unit" errors are ignored for
470     # now (related to DBUS_ERROR_UNKNOWN_OBJECT). in the future, we need to
471     # revert to calling 'systemctl show' once for all units, which is way
472     # faster
473     unit=${units[i]}
474     prop=${(f)"$(_call_program units "$service show --no-pager --property="$property" ${unit} 2>/dev/null")"}
475     if [[ "${prop}" = "$property=$value" ]]; then
476       echo " ${unit}"
477     fi
478   done
479 }
480
481 _systemctl_active_units()  {_sys_active_units=(  $(__systemctl list-units          | { while read a b; do echo " $a"; done; }) )}
482 _systemctl_inactive_units(){_sys_inactive_units=($(__systemctl list-units --all    | { while read a b c d; do [[ $c == "inactive" || $c == "failed" ]] && echo " $a"; done; }) )}
483 _systemctl_failed_units()  {_sys_failed_units=(  $(__systemctl list-units --failed | { while read a b; do echo " $a"; done; }) )}
484 _systemctl_enabled_units() {_sys_enabled_units=( $(__systemctl list-unit-files     | { while read a b; do [[ $b == "enabled" ]] && echo " $a"; done; }) )}
485 _systemctl_disabled_units(){_sys_disabled_units=($(__systemctl list-unit-files     | { while read a b; do [[ $b == "disabled" ]] && echo " $a"; done; }) )}
486 _systemctl_masked_units()  {_sys_masked_units=(  $(__systemctl list-unit-files     | { while read a b; do [[ $b == "masked" ]] && echo " $a"; done; }) )}
487
488 # Completion functions for ALL_UNITS
489 for fun in is-active is-failed is-enabled status show mask preset help list-dependencies ; do
490   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
491   {
492     _systemctl_really_all_units
493     compadd "$@" -a - _sys_really_all_units
494   }
495 done
496
497 # Completion functions for ENABLED_UNITS
498 for fun in disable reenable ; do
499   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
500   {
501     _systemctl_enabled_units
502     _systemctl_disabled_units
503     compadd "$@" -a - _sys_enabled_units _sys_disabled_units
504   }
505 done
506
507 # Completion functions for DISABLED_UNITS
508 (( $+functions[_systemctl_enable] )) || _systemctl_enable()
509 {
510   _systemctl_disabled_units
511   compadd "$@" -a - _sys_disabled_units
512 }
513
514 # Completion functions for FAILED_UNITS
515 (( $+functions[_systemctl_reset-failed] )) || _systemctl_reset-failed()
516 {
517   _systemctl_failed_units
518   compadd "$@" -a - _sys_failed_units || _message "no failed unit found"
519 }
520
521 # Completion functions for STARTABLE_UNITS
522 (( $+functions[_systemctl_start] )) || _systemctl_start()
523 {
524   _systemctl_inactive_units
525   compadd "$@" -a - _sys_inactive_units
526 }
527
528 # Completion functions for STOPPABLE_UNITS
529 for fun in stop kill try-restart condrestart ; do
530   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
531   {
532     _systemctl_active_units
533     compadd "$@" - $( _filter_units_by_property CanStop yes \
534       ${_sys_active_units[*]} )
535   }
536 done
537
538 # Completion functions for ISOLATABLE_UNITS
539 (( $+functions[_systemctl_isolate] )) || _systemctl_isolate()
540 {
541   _systemctl_all_units
542   compadd "$@" - $( _filter_units_by_property AllowIsolate yes \
543     ${_sys_all_units[*]} )
544 }
545
546 # Completion functions for RELOADABLE_UNITS
547 for fun in reload reload-or-try-restart force-reload ; do
548   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
549   {
550     _systemctl_active_units
551     compadd "$@" - $( _filter_units_by_property CanReload yes \
552       ${_sys_active_units[*]} )
553   }
554 done
555
556 # Completion functions for RESTARTABLE_UNITS
557 for fun in restart reload-or-restart ; do
558   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
559   {
560     _systemctl_all_units
561     compadd "$@" - $( _filter_units_by_property CanStart yes \
562       ${_sys_all_units[*]} | while read line; do \
563       [[ "$line" =~ \.device$ ]] || echo " $line"; \
564       done )
565   }
566 done
567
568 # Completion functions for MASKED_UNITS
569 (( $+functions[_systemctl_unmask] )) || _systemctl_unmask()
570 {
571   _systemctl_masked_units
572   compadd "$@" -a - _sys_masked_units || _message "no masked unit found"
573 }
574
575 # Completion functions for JOBS
576 (( $+functions[_systemctl_cancel] )) || _systemctl_cancel()
577 {
578   compadd "$@" - $(__systemctl list-jobs \
579     | cut -d' ' -f1  2>/dev/null ) || _message "no job found"
580 }
581
582 # Completion functions for SNAPSHOTS
583 (( $+functions[_systemctl_delete] )) || _systemctl_delete()
584 {
585   compadd "$@" - $(__systemctl list-units --type snapshot --all \
586     | cut -d' ' -f1  2>/dev/null ) || _message "no snapshot found"
587 }
588
589 # Completion functions for ENVS
590 for fun in set-environment unset-environment ; do
591   (( $+functions[_systemctl_$fun] )) || _systemctl_$fun()
592   {
593     local fun=$0 ; fun=${fun##_systemctl_}
594     local suf
595     if [[ "${fun}" = "set-environment" ]]; then
596       suf='-S='
597     fi
598
599     compadd "$@" ${suf} - $(systemctl show-environment \
600       | while read line; do echo " ${line%%\=}";done )
601   }
602 done
603
604 (( $+functions[_systemctl_link] )) || _systemctl_link() { _files }
605
606 # no systemctl completion for:
607 #    [STANDALONE]='daemon-reexec daemon-reload default dump
608 #                  emergency exit halt kexec list-jobs list-units
609 #                  list-unit-files poweroff reboot rescue show-environment'
610 #         [NAME]='snapshot load'
611
612 _systemctl_caching_policy()
613 {
614   local _sysunits
615   local -a oldcache
616
617   # rebuild if cache is more than a day old
618   oldcache=( "$1"(mh+1) )
619   (( $#oldcache )) && return 0
620
621   _sysunits=($(__systemctl --all | cut -d' ' -f1))
622
623   if (( $#_sysunits )); then
624     for unit in $_sysunits; do
625       [[ "$unit" -nt "$1" ]] && return 0
626     done
627   fi
628
629   return 1
630 }
631
632 _list_fields() {
633     local -a journal_fields
634     journal_fields=(MESSAGE{,_ID} PRIORITY CODE_{FILE,LINE,FUNC}
635                     ERRNO SYSLOG_{FACILITY,IDENTIFIER,PID}
636                     _{P,U,G}ID _COMM _EXE _CMDLINE
637                     _AUDIT_{SESSION,LOGINUID}
638                     _SYSTEMD_{CGROUP,SESSION,UNIT,OWNER_UID}
639                     _SYSTEMD_USER_UNIT
640                     _SELINUX_CONTEXT _SOURCE_REALTIME_TIMESTAMP
641                     _{BOOT,MACHINE}_ID _HOSTNAME _TRANSPORT
642                     _KERNEL_{DEVICE,SUBSYSTEM}
643                     _UDEV_{SYSNAME,DEVNODE,DEVLINK}
644                     __CURSOR __{REALTIME,MONOTONIC}_TIMESTAMP)
645     _describe 'possible fields' journal_fields
646 }
647
648 _journal_none() {
649     local -a _commands _files
650     _commands=( ${(f)"$(_call_program commands "$service" -F _EXE 2>/dev/null)"} )
651     _alternative : \
652         'files:/dev files:_files -W /dev -P /dev/' \
653         "commands:commands:($_commands[@])" \
654         'fields:fields:_list_fields'
655 }
656
657 _journal_fields() {
658     local -a _fields cmd
659     cmd=("journalctl" "-F ${@[-1]}" "2>/dev/null" )
660     _fields=( ${(f)"$(_call_program fields $cmd[@])"} )
661     typeset -U _fields
662     _describe 'possible values' _fields
663 }
664
665
666 _loginctl_all_sessions(){_sys_all_sessions=($(loginctl list-sessions | { while read a b; do echo " $a"; done; }) )}
667 _loginctl_all_users()   {_sys_all_users=(   $(loginctl list-users    | { while read a b; do echo " $a"; done; }) )}
668 _loginctl_all_seats()   {_sys_all_seats=(   $(loginctl list-seats    | { while read a b; do echo " $a"; done; }) )}
669
670 # Completion functions for SESSIONS
671 for fun in session-status show-session activate lock-session unlock-session terminate-session kill-session ; do
672   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
673   {
674     _loginctl_all_sessions
675     compadd "$@" -a - _sys_all_sessions
676   }
677 done
678
679 # Completion functions for USERS
680 for fun in user-status show-user enable-linger disable-linger terminate-user kill-user ; do
681   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
682   {
683     _loginctl_all_users
684     compadd "$@" -a - _sys_all_users
685   }
686 done
687
688 # Completion functions for SEATS
689 (( $+functions[_loginctl_seats] )) || _loginctl_seats()
690 {
691   _loginctl_all_seats
692   compadd "$@" -a - _sys_all_seats
693 }
694 for fun in seat-status show-seat terminate-seat ; do
695   (( $+functions[_loginctl_$fun] )) || _loginctl_$fun()
696   { _loginctl_seats }
697 done
698
699 # Completion functions for ATTACH
700 (( $+functions[_loginctl_attach] )) || _loginctl_attach()
701 {
702   _loginctl_all_seats
703
704   _arguments -w -C -S -s \
705     ':seat:_loginctl_seats' \
706     '*:device:_files'
707 }
708
709 # no loginctl completion for:
710 # [STANDALONE]='list-sessions list-users list-seats flush-devices'
711
712 (( $+functions[_loginctl_command] )) || _loginctl_command()
713 {
714   local -a _loginctl_cmds
715   _loginctl_cmds=(
716     "list-sessions:List sessions"
717     "session-status:Show session status"
718     "show-session:Show properties of one or more sessions"
719     "activate:Activate a session"
720     "lock-session:Screen lock one or more sessions"
721     "unlock-session:Screen unlock one or more sessions"
722     "terminate-session:Terminate one or more sessions"
723     "kill-session:Send signal to processes of a session"
724     "list-users:List users"
725     "user-status:Show user status"
726     "show-user:Show properties of one or more users"
727     "enable-linger:Enable linger state of one or more users"
728     "disable-linger:Disable linger state of one or more users"
729     "terminate-user:Terminate all sessions of one or more users"
730     "kill-user:Send signal to processes of a user"
731     "list-seats:List seats"
732     "seat-status:Show seat status"
733     "show-seat:Show properties of one or more seats"
734     "attach:Attach one or more devices to a seat"
735     "flush-devices:Flush all device associations"
736     "terminate-seat:Terminate all sessions on one or more seats"
737   )
738
739   if (( CURRENT == 1 )); then
740     _describe -t commands 'loginctl command' _loginctl_cmds || compadd "$@"
741   else
742     local curcontext="$curcontext"
743
744     cmd="${${_loginctl_cmds[(r)$words[1]:*]%%:*}}"
745
746     if (( $#cmd )); then
747       curcontext="${curcontext%:*:*}:loginctl-${cmd}:"
748
749       _call_function ret _loginctl_$cmd || _message 'no more arguments'
750     else
751       _message "unknown loginctl command: $words[1]"
752     fi
753     return ret
754   fi
755 }
756
757 _hostnamectl_command() {
758     local -a _hostnamectl_cmds
759     _hostnamectl_cmds=(
760         "status:Show current hostname settings"
761         "set-hostname:Set system hostname"
762         "set-icon-name:Set icon name for host"
763     )
764     if (( CURRENT == 1 )); then
765         _describe -t commands 'hostnamectl commands' _hostnamectl_cmds || compadd "$@"
766     else
767         local curcontext="$curcontext"
768         cmd="${${_hostnamectl_cmds[(r)$words[1]:*]%%:*}}"
769         if (( $#cmd )); then
770             [[ $cmd == status ]] && msg="no options" || msg="options for $cmd"
771             _message "$msg"
772         else
773             _message "unknown hostnamectl command: $words[1]"
774         fi
775     fi
776 }
777
778 _localectl_set-locale() {
779     local -a _confs _locales
780     local expl suf
781     _locales=( ${(f)"$(_call_program locales "$service" list-locales)"} )
782     _confs=( ${${(f)"$(_call_program confs "locale 2>/dev/null")"}%\=*} )
783     if [[ -prefix 1 *\= ]]; then
784         local conf=${PREFIX%%\=*}
785         compset -P1 '*='
786         _wanted locales expl "locales configs" \
787             _combination localeconfs  confs=$conf locales "$@" -
788     else
789         compadd -S '='  $_confs
790     fi
791 }
792
793 _localectl_set-keymap() {
794     local -a _keymaps
795     _keymaps=( ${(f)"$(_call_program locales "$service" list-keymaps)"} )
796     if (( CURRENT <= 3 )); then
797         _describe keymaps _keymaps
798     else
799         _message "no more options"
800     fi
801 }
802
803 _localectl_set-x11-keymap() {
804     if (( $+commands[pkg-config] )); then
805         local -a _file _layout _model _variant _options
806         local _xorg_lst
807         _xorg_lst=${"$($commands[pkg-config] xkeyboard-config --variable=xkb_base)"}
808         _file=( ${(ps:\n\!:)"$(<$_xorg_lst/rules/xorg.lst)"} )
809         _layout=( ${${${(M)${(f)_file[1]}:#  *}#  }%% *} )
810         _model=( ${${${(M)${(f)_file[2]}:#  *}#  }%% *} )
811         _variant=( ${${${(M)${(f)_file[3]}:#  *}#  }%% *} )
812         _options=( ${${${(M)${(f)_file[4]}:#  *}#  }%% *} )
813         #_layout=( ${(f)"$( echo $_file[1] | awk '/^  / {print $1}' )"} )
814         #_model=( ${(f)"$(echo $_file[2] | awk '/^  / {print $1}')"} )
815         #_variant=( ${(f)"$(echo $_file[3] | awk '/^  / {print $1}')"} )
816         #_options=( ${(f)"$(echo ${_file[4]//:/\\:} | awk '/^  / {print $1}')"} )
817
818         case $CURRENT in
819             2) _describe layouts _layout ;;
820             3) _describe models _model;;
821             4) _describe variants _variant;;
822             5) _describe options _options;;
823             *) _message "no more options"
824         esac
825     fi
826 }
827
828
829 _localectl_command() {
830     local -a _localectl_cmds
831     _localectl_cmds=(
832         'status:Show current locale settings'
833         'set-locale:Set system locale'
834         'list-locales:Show known locales'
835         'set-keymap:Set virtual console keyboard mapping'
836         'list-keymaps:Show known virtual console keyboard mappings'
837         'set-x11-keymap:Set X11 keyboard mapping'
838     )
839     if (( CURRENT == 1 )); then
840         _describe -t commands 'localectl command' _localectl_cmds
841     else
842         local curcontext="$curcontext"
843         cmd="${${_localectl_cmds[(r)$words[1]:*]%%:*}}"
844         if (( $+functions[_localectl_$cmd] )); then
845             _localectl_$cmd
846         else
847             _message "no more options"
848         fi
849     fi
850 }
851
852 _timedatectl_set-timezone(){
853     local -a _timezones
854     _timezones=( ${(f)"$(_call_program timezones "${service}" list-timezones)"} )
855     compadd "$_timezones[@]"
856 }
857
858 _timedatectl_set-time(){
859     _message "YYYY-MM-DD HH:MM:SS"
860 }
861
862 _timedatectl_set-local-rtc(){
863     local -a _options
864     _options=(
865         '0:Maintain RTC in universal time'
866         '1:Maintain RTC in local time'
867     )
868     _describe options _options
869 }
870
871 _timedatectl_set-ntp(){
872     local -a _options
873     _options=(
874         '0:Disable NTP based network time configuration'
875         '1:Enable NTP based network time configuration'
876     )
877     _describe options _options
878 }
879
880 _timedatectl_command(){
881     local -a _timedatectl_cmds
882     _timedatectl_cmds=(
883         'status:Show current time settings'
884         'set-time:Set system time'
885         'set-timezone:Set system timezone'
886         'list-timezones:Show known timezones'
887         'set-local-rtc:Control whether RTC is in local time'
888         'set-ntp:Control whether NTP is enabled'
889     )
890     if (( CURRENT == 1 )); then
891         _describe -t commands 'timedatectl command' _timedatectl_cmds
892     else
893         local curcontext="$curcontext"
894         cmd="${${_timedatectl_cmds[(r)$words[1]:*]%%:*}}"
895         if (( $#cmd )); then
896             if (( $+functions[_timedatectl_$cmd] )); then
897                 _timedatectl_$cmd
898             else
899                 _message "no more options"
900             fi
901         else
902             _message "unknown timedatectl command: $words[1]"
903         fi
904     fi
905 }
906 _systemd-coredumpctl_command(){
907     local -a _systemd_coredumpctl_cmds
908     _systemd_coredumpctl_cmds=(
909             'list:List available coredumps'
910             'dump:Print coredump to std'
911     )
912     if (( CURRENT == 1 )); then
913         _describe -t commands 'systemd-coredumpctl command' _systemd_coredumpctl_cmds
914     else
915         local curcontext="$curcontext"
916         local -a _dumps
917         cmd="${${_systemd_coredumpctl_cmds[(r)$words[1]:*]%%:*}}"
918         if (( $#cmd  )); then
919                         # user can set zstyle ':completion:*:*:systemd-coredumpctl:*' sort no for coredumps to be ordered by date, otherwise they get ordered by pid
920                         _dumps=( "${(foa)$(systemd-coredumpctl list | awk 'BEGIN{OFS=":"} /^\s/ {sub(/[[ \t]+/, ""); print $5,$0}' 2>/dev/null)}" )
921             if [[ -n "$_dumps" ]]; then
922                 _describe -t pids 'coredumps' _dumps
923             else
924                 _message "no coredumps"
925             fi
926         else
927             _message "no more options"
928         fi
929
930     fi
931
932 }
933
934 (( $+functions[_machinectl_command] )) || _machinectl_command()
935 {
936   local -a _machinectl_cmds
937   _machinectl_cmds=(
938     "list:List currently running VMs/containers"
939     "status:Show VM/container status"
940     "show:Show properties of one or more VMs/containers"
941     "terminate:Terminate one or more VMs/containers"
942     "kill:Send signal to process or a VM/container"
943   )
944   if (( CURRENT == 1 )); then
945     _describe -t commands 'machinectl command' _machinectl_cmds || compadd "$@"
946   else
947     local curcontext="$curcontext"
948     cmd="${${_machinectl_cmds[(r)$words[1]:*]%%:*}}"
949     if (( $#cmd )); then
950       case $cmd in
951         list) msg="no options" ;;
952         *)
953           _machines=( "${(foa)$(machinectl list | awk '{print $1}')}" )
954           if [[ -n "$_machines" ]]; then
955             _describe 'machines' _machines
956           else
957             _message 'no machines'
958           fi
959       esac
960     else
961       _message "no more options"
962     fi
963   fi
964 }
965
966 _udevadm_info(){
967     _arguments \
968         '--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)' \
969         '--path=[The devpath of the device to query.]:sys files:_files -P /sys/ -W /sys' \
970         '--name=[The name of the device node or a symlink to query]:device files:_files -P /dev/ -W /dev' \
971         '--root[Print absolute paths in name or symlink query.]' \
972         '--attribute-walk[Print all sysfs properties of the specified device that can be used in udev rules to match the specified device]' \
973         '--export[Print output as key/value pairs.]' \
974         '--export-prefix=[Add a prefix to the key name of exported values.]:prefix' \
975         '--device-id-of-file=[Print major/minor numbers of the underlying device, where the file lives on.]:files:_udevadm_mounts' \
976         '--export-db[Export the content of the udev database.]' \
977         '--cleanup-db[Cleanup the udev database.]'
978 }
979
980 _udevadm_trigger(){
981     _arguments \
982         '--verbose[Print the list of devices which will be triggered.]' \
983         '--dry-run[Do not actually trigger the event.]' \
984         '--type=[Trigger a specific type of devices.]:types:(devices subsystems failed)' \
985         '--action=[Type of event to be triggered.]:actions:(add change remove)' \
986         '--subsystem-match=[Trigger events for devices which belong to a matching subsystem.]' \
987         '--subsystem-nomatch=[Do not trigger events for devices which belong to a matching subsystem.]' \
988         '--attr-match=attribute=[Trigger events for devices with a matching sysfs attribute.]' \
989         '--attr-nomatch=attribute=[Do not trigger events for devices with a matching sysfs attribute.]' \
990         '--property-match=[Trigger events for devices with a matching property value.]' \
991         '--tag-match=property[Trigger events for devices with a matching tag.]' \
992         '--sysname-match=[Trigger events for devices with a matching sys device name.]' \
993         '--parent-match=[Trigger events for all children of a given device.]'
994 }
995
996 _udevadm_settle(){
997     _arguments \
998        '--timeout=[Maximum number of seconds to wait for the event queue to become empty.]' \
999        '--seq-start=[Wait only for events after the given sequence number.]' \
1000        '--seq-end=[Wait only for events before the given sequence number.]' \
1001        '--exit-if-exists=[Stop waiting if file exists.]:files:_files' \
1002        '--quiet[Do not print any output, like the remaining queue entries when reaching the timeout.]' \
1003        '--help[Print help text.]'
1004 }
1005
1006 _udevadm_control(){
1007     _arguments \
1008         '--exit[Signal and wait for systemd-udevd to exit.]' \
1009         '--log-priority=[Set the internal log level of systemd-udevd.]:priorities:(err info debug)' \
1010         '--stop-exec-queue[Signal systemd-udevd to stop executing new events. Incoming events will be queued.]' \
1011         '--start-exec-queue[Signal systemd-udevd to enable the execution of events.]' \
1012         '--reload[Signal systemd-udevd to reload the rules files and other databases like the kernel module index.]' \
1013         '--property=[Set a global property for all events.]' \
1014         '--children-max=[Set the maximum number of events.]' \
1015         '--timeout=[The maximum number of seconds to wait for a reply from systemd-udevd.]' \
1016         '--help[Print help text.]'
1017 }
1018
1019 _udevadm_monitor(){
1020     _arguments \
1021         '--kernel[Print the kernel uevents.]' \
1022         '--udev[Print the udev event after the rule processing.]' \
1023         '--property[Also print the properties of the event.]' \
1024         '--subsystem-match=[Filter events by subsystem/\[devtype\].]' \
1025         '--tag-match=[Filter events by property.]' \
1026         '--help[Print help text.]'
1027 }
1028
1029 _udevadm_test(){
1030     _arguments \
1031         '--action=[The action string.]:actions:(add change remove)' \
1032         '--subsystem=[The subsystem string.]' \
1033         '--help[Print help text.]' \
1034         '*::devpath:_files -P /sys/ -W /sys'
1035 }
1036
1037 _udevadm_test-builtin(){
1038     if (( CURRENT == 2 )); then
1039     _arguments \
1040         '--help[Print help text]' \
1041         '*::builtins:(blkid btrfs hwdb input_id kmod path_id usb_id uaccess)'
1042     elif  (( CURRENT == 3 )); then
1043         _arguments \
1044             '--help[Print help text]' \
1045             '*::syspath:_files -P /sys -W /sys'
1046     else
1047         _arguments \
1048             '--help[Print help text]'
1049     fi
1050 }
1051
1052 _udevadm_mounts(){
1053   local dev_tmp dpath_tmp mp_tmp mline
1054
1055     tmp=( "${(@f)$(< /etc/mtab)}" )
1056     dev_tmp=( "${(@)${(@)tmp%% *}:#none}" )
1057     mp_tmp=( "${(@)${(@)tmp#* }%% *}" )
1058
1059   local MATCH
1060   mp_tmp=("${(@q)mp_tmp//(#m)\\[0-7](#c3)/${(#)$(( 8#${MATCH[2,-1]} ))}}")
1061   dpath_tmp=( "${(@Mq)dev_tmp:#/*}" )
1062   dev_tmp=( "${(@q)dev_tmp:#/*}" )
1063
1064   _alternative \
1065     'device-paths: device path:compadd -a dpath_tmp' \
1066     'directories:mount point:compadd -a mp_tmp'
1067 }
1068
1069
1070 _udevadm_command(){
1071     local -a _udevadm_cmds
1072     _udevadm_cmds=(
1073         'info:query sysfs or the udev database'
1074         'trigger:request events from the kernel'
1075         'settle:wait for the event queue to finish'
1076         'control:control the udev daemon'
1077         'monitor:listen to kernel and udev events'
1078         'test:test an event run'
1079         'test-builtin:test a built-in command'
1080     )
1081
1082     if ((CURRENT == 1)); then
1083         _describe -t commands 'udevadm commands' _udevadm_cmds
1084     else
1085         local curcontext="$curcontext"
1086         cmd="${${_udevadm_cmds[(r)$words[1]:*]%%:*}}"
1087         if (($#cmd)); then
1088             if (( $+functions[_udevadm_$cmd] )); then
1089                 _udevadm_$cmd
1090             else
1091                 _message "no options for $cmd"
1092             fi
1093         else
1094             _message "no more options"
1095         fi
1096     fi
1097 }
1098
1099 _ctls "$@"
1100
1101 #vim: set ft=zsh sw=4 ts=4 et