1# systemd-cgls(1) completion                  -*- shell-script -*-
2# SPDX-License-Identifier: LGPL-2.1-or-later
3#
4# This file is part of systemd.
5#
6# systemd is free software; you can redistribute it and/or modify it
7# under the terms of the GNU Lesser General Public License as published by
8# the Free Software Foundation; either version 2.1 of the License, or
9# (at your option) any later version.
10#
11# systemd is distributed in the hope that it will be useful, but
12# WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14# General Public License for more details.
15#
16# You should have received a copy of the GNU Lesser General Public License
17# along with systemd; If not, see <http://www.gnu.org/licenses/>.
18
19__contains_word() {
20    local w word=$1; shift
21    for w in "$@"; do
22        [[ $w = "$word" ]] && return
23    done
24}
25
26__get_machines() {
27    local a b
28    machinectl list --full --no-legend --no-pager | { while read a b; do echo " $a"; done; };
29}
30
31__get_units_have_cgroup() {
32    systemctl $1 --full --no-legend --no-pager --plain list-units | {
33        while read -r a b c d; do
34            [[ $c == "active" && ${a##*.} =~ (service|socket|mount|swap|slice|scope) ]] && echo " $a"
35        done
36    };
37}
38
39_systemd_cgls() {
40    local cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]} words cword
41    local i verb comps
42
43    local -A OPTS=(
44        [STANDALONE]='-h --help --version --all -l --full -k --no-pager --xattr=no --cgroup-id=no'
45        [ARG]='-M --machine -u --unit --user-unit'
46    )
47
48    _init_completion || return
49
50    if __contains_word "$prev" ${OPTS[ARG]}; then
51        case $prev in
52            --machine|-M)
53                comps=$( __get_machines )
54                ;;
55            --unit|-u)
56                comps=$( __get_units_have_cgroup --system )
57                ;;
58            --user-unit)
59                comps=$( __get_units_have_cgroup --user )
60                ;;
61        esac
62        COMPREPLY=( $(compgen -W '$comps' -- "$cur") )
63        return 0
64    fi
65
66    COMPREPLY=( $(compgen -W '${OPTS[*]}' -- "$cur") )
67}
68
69complete -F _systemd_cgls systemd-cgls
70