summaryrefslogtreecommitdiff
path: root/.local/bin/zypper-wassup
blob: 749052a30428ccd3f5eebadb5212468f1b80f5b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
#!/usr/bin/env python3

from collections import defaultdict, namedtuple
from enum import IntEnum
import re
from subprocess import run


Package = namedtuple('Package', ('package', 'old', 'new'))

ZYPPER_PATTERN = re.compile(
    r' +\| +'.join((
        '^v',
        '[^|]+',
        '(?P<package>[^ ]+)',
        '(?P<old>[^ ]+)',
        '(?P<new>[^ ]+)'
    )),
    re.MULTILINE
)

# Using http://ftp.rpm.org/max-rpm/ch-rpm-file-format.html to make a
# few assumptions, e.g. versions can't contain hyphens.
SOURCERPM_PATTERN = re.compile(
    r'\.'.join((
        '-'.join(('(?P<name>.+)', '(?P<version>[^-]+)', '(?P<release>[^-]+)')),
        '(?:no)?src',
        'rpm'
    ))
)


def execute(command):
    return run(command, check=True, text=True, capture_output=True).stdout


def zypper_list_updates():
    zypp_output = execute(('zypper', 'list-updates'))

    return tuple(
        Package(**match.groupdict())
        for match in ZYPPER_PATTERN.finditer(zypp_output)
    )


def source_package_name(package):
    if (match := SOURCERPM_PATTERN.fullmatch(package)) is None:
        raise Exception(f'{package} does not match "{SOURCERPM_PATTERN}".')

    return match.group('name')


def sort_by_source_package(packages):
    sorted_packages = defaultdict(list)

    for p in packages:
        source_pkgs = execute(
            ('rpm', '--query', '--queryformat', r'%{SOURCERPM}\n', p.package)
        )

        # Some packages, e.g. kernel-default and kernel-devel, may be
        # provided by multiple version of a source package.  Assume
        # the last one is one we want.

        *_, last_source_pkg = source_pkgs.splitlines()
        name = source_package_name(last_source_pkg)

        sorted_packages[name].append(p)

    return sorted_packages


class Sgr(IntEnum):
    RESET = 0
    BOLD = 1
    RED_FG = 31
    GREEN_FG = 32


def colorize(text, *params):
    prefix = '\N{ESCAPE}['
    suffix = 'm'
    reset = f'{prefix}{Sgr.RESET}{suffix}'
    param_list = ';'.join(map(format, params))

    return f'{prefix}{param_list}{suffix}{text}{reset}'


def highlight_diff(old, new):
    for i, (o, n) in enumerate(zip(old, new)):
        if o != n:
            break

    old = old[:i]+colorize(old[i:], Sgr.BOLD, Sgr.RED_FG)
    new = new[:i]+colorize(new[i:], Sgr.BOLD, Sgr.GREEN_FG)

    return old, new


def padding(string, width):
    # Python's str.format does not skip over control sequences when
    # computing how long a string is.  Compute padding manually before
    # adding these sequences
    return ' '*(width-len(string))


COLUMN = ' │ '


def print_header(widths, name):
    if len(name) > widths['package']:
        name = name[:widths['package']-1]+'…'

    print(COLUMN.join((
        colorize(name, Sgr.BOLD)+padding(name, widths['package']),
        ' '*widths['old'],
        ' '*widths['new'],
    )))


def print_footer(i, n, widths):
    if i < n:
        print('─┼─'.join('─'*widths[f] for f in Package._fields))


def main():
    print('Querying zypper list-updates… ', end='', flush=True)
    packages = zypper_list_updates()
    print(f'{len(packages)} updates.')

    if not packages:
        return

    widths = {
        field: max(len(p._asdict()[field]) for p in packages)
        for field in Package._fields
    }

    print('Sorting by source package… ', end='', flush=True)
    packages = sort_by_source_package(packages)
    print('Done')

    for i, src in enumerate(sorted(packages), 1):
        print_header(widths, src)

        for pkg, old, new in sorted(packages[src]):
            old_padding = padding(old, widths['old'])
            new_padding = padding(new, widths['new'])

            old, new = highlight_diff(old, new)

            print(COLUMN.join((
                f'{pkg:<{widths["package"]}}',
                old+old_padding,
                new+new_padding
            )))

        print_footer(i, len(packages), widths)


if __name__ == '__main__':
    main()