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
163
164
165
166
167
168
169
170
171
172
173
174
175
|
#!/usr/bin/env python3
from collections import defaultdict, namedtuple
from collections.abc import Iterable
from enum import IntEnum
import re
from subprocess import run
Update = namedtuple('Update', ('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(
Update(**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(updates):
sorted_updates = defaultdict(list)
for u in updates:
source_pkgs = execute(
('rpm', '--query', '--queryformat', r'%{SOURCERPM}\n', u.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_updates[name].append(u)
return sorted_updates
class Sgr(IntEnum):
RESET = 0
BOLD = 1
RED_FG = 31
GREEN_FG = 32
def colorize(text: str, params: Iterable[Sgr]) -> str:
prefix = '\N{ESCAPE}['
suffix = 'm'
reset = f'{prefix}{Sgr.RESET}{suffix}'
param_list = ';'.join(map(str, params))
return f'{prefix}{param_list}{suffix}{text}{reset}'
def highlight_diff_part(old: str, new: str, codes: Iterable[Sgr]=()) -> (str, str):
for i, (o, n) in enumerate(zip(old, new)):
if o != n:
break
else:
# old == new, or new == old + suffix.
i += 1
old = old[:i]+colorize(old[i:], (Sgr.RED_FG,)+tuple(codes))
new = new[:i]+colorize(new[i:], (Sgr.GREEN_FG,)+tuple(codes))
return old, new
def highlight_diff(old: str, new: str) -> (str, str):
old_pkgv, old_distv = old.split("-", maxsplit=1)
new_pkgv, new_distv = new.split("-", maxsplit=1)
old_pkgv, new_pkgv = highlight_diff_part(old_pkgv, new_pkgv, (Sgr.BOLD,))
old_distv, new_distv = highlight_diff_part(old_distv, new_distv)
return f"{old_pkgv}-{old_distv}", f"{new_pkgv}-{new_distv}"
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 Update._fields))
def main():
print('Querying zypper list-updates… ', end='', flush=True)
updates = zypper_list_updates()
print(f'{len(updates)} updates.')
if not updates:
return
widths = {
field: max(len(u._asdict()[field]) for u in updates)
for field in Update._fields
}
print('Sorting by source package… ', end='', flush=True)
updates = sort_by_source_package(updates)
print('Done')
for i, src in enumerate(sorted(updates), 1):
print_header(widths, src)
for pkg, old, new in sorted(updates[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(updates), widths)
if __name__ == '__main__':
main()
|