Debian Codegraph @

debian/release-update

raw symbols SCIP
1 #!/usr/bin/python3
2 # SPDX-License-Identifier: MIT
3 # Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
4 #
5 # Gather changelog entries for a new upstream release.
6 #
7 # The source package is assembled from two upstream components (see
8 # debian/watch): the hexagon-dsp-binaries release tarball and the 'firmware'
9 # component, which is a filtered copy of linux-firmware. This script walks
10 # the git history of both upstream repositories and turns the commits which
11 # are relevant for this package into debian/changelog entries.
12
13 import importlib.util
14 import os
15 import re
16 import subprocess
17 import sys
18 import textwrap
19
20 CHANGELOG = 'debian/changelog'
21 COPYRIGHT = 'debian/copyright'
22
23 # Heading of the section listing hexagon-dsp-binaries changes. An item which
24 # is already there (possibly reworded, e.g. 'New upstream release, skipping
25 # 20260110.') is located by the prefix and kept.
26 UPSTREAM_INTRO_PREFIX = 'New upstream release'
27 UPSTREAM_INTRO = UPSTREAM_INTRO_PREFIX + ':'
28
29 # Heading of the section listing linux-firmware changes. The version is part
30 # of the heading, so existing headings are located by their prefix.
31 FIRMWARE_INTRO_PREFIX = 'New linux-firmware release'
32 FIRMWARE_INTRO = FIRMWARE_INTRO_PREFIX + ' {}:'
33
34 # Paths in the hexagon-dsp-binaries repository which are not part of the
35 # release tarball (see scripts/dist.sh there), so changes to them are of no
36 # interest for the package.
37 UPSTREAM_EXCLUDE = [
38 '.github',
39 '.gitignore',
40 'README.md',
41 ]
42
43 # WHENCE is listed in Files-Included-firmware, but linux-firmware touches it
44 # for every single firmware file it carries. Commits to it are therefore not
45 # taken from the file list; they are picked by filtering WHENCE the way
46 # debian/rules does before building the packages, and keeping the commits
47 # which change the result. That covers the entries of the files we ship,
48 # the symlinks (Link:) pointing at them and, most importantly, the licence
49 # they are placed under.
50 FIRMWARE_WHENCE = 'WHENCE'
51 WHENCE_FILTER = 'filter-firmware-whence.py'
52
53 # Subject prefixes which carry no information in our changelog
54 STRIP_SUBJECT_RE = re.compile(r'^linux-firmware: *')
55
56 # Header line of a changelog entry
57 CHANGELOG_HEADER_RE = re.compile(
58 r'^(\S+) \((\S+)\) (\S+); urgency=(\S+)\s*$')
59
60
61 def git(repo, *args, check=True):
62 """Run git in REPO and return its output."""
63 proc = subprocess.run(['git', '-C', repo, *args],
64 stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
65 text=True)
66 if check and proc.returncode != 0:
67 sys.exit(f'{repo}: git {" ".join(args)} failed')
68 return proc.stdout if proc.returncode == 0 else None
69
70
71 def git_lines(repo, *args):
72 """Run git in REPO and return its output as a list of lines."""
73 return git(repo, *args).splitlines()
74
75
76 def check_repo(repo, *revs):
77 """Check that REPO is a git repository holding all of REVS."""
78 if not os.path.isdir(repo):
79 sys.exit(f'{repo}: no such directory')
80 for rev in revs:
81 if subprocess.run(['git', '-C', repo, 'rev-parse', '--verify',
82 '--quiet', rev + '^{commit}'],
83 stdout=subprocess.DEVNULL,
84 stderr=subprocess.DEVNULL).returncode != 0:
85 sys.exit(f'{repo}: no such tag or commit: {rev}')
86
87
88 def firmware_includes(copyright_file):
89 """Read Files-Included-firmware from debian/copyright.
90
91 These are the patterns uscan uses to build the firmware component
92 tarball, so they describe exactly the part of linux-firmware which ends
93 up in the source package.
94 """
95 patterns = []
96 field = None
97 with open(copyright_file, encoding='utf-8') as f:
98 for line in f:
99 if line.strip() == '':
100 # Only the first (header) paragraph is of interest
101 if patterns:
102 break
103 field = None
104 elif line[0] not in ' \t':
105 field = line.split(':', 1)[0]
106 value = line.split(':', 1)[1] if ':' in line else ''
107 if field == 'Files-Included-firmware':
108 patterns.extend(value.split())
109 elif field == 'Files-Included-firmware':
110 patterns.extend(line.split())
111
112 if not patterns:
113 sys.exit(f'{copyright_file}: no Files-Included-firmware field')
114
115 return patterns
116
117
118 def load_whence_filter():
119 """Load filter_whence() from debian/filter-firmware-whence.py.
120
121 The very filter debian/rules applies to the WHENCE of the firmware
122 component, so that this script looks at exactly what gets shipped.
123 """
124 path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
125 WHENCE_FILTER)
126 spec = importlib.util.spec_from_file_location('filter_firmware_whence',
127 path)
128 # Don't drop a __pycache__ into the packaging directory
129 sys.dont_write_bytecode = True
130 module = importlib.util.module_from_spec(spec)
131 spec.loader.exec_module(module)
132 return module.filter_whence
133
134
135 def format_subjects(lines):
136 """Normalise, sort and de-duplicate a list of commit subjects."""
137 subjects = [STRIP_SUBJECT_RE.sub('', line).strip()
138 for line in lines if line.strip()]
139 return sorted(set(subjects), key=str.casefold)
140
141
142 def upstream_log(repo, cur_ver, new_ver):
143 """List hexagon-dsp-binaries changes between the two releases."""
144 check_repo(repo, cur_ver, new_ver)
145 return format_subjects(
146 git_lines(repo, 'log', '--no-merges', '--pretty=%s',
147 f'{cur_ver}..{new_ver}', '--',
148 *(f':(exclude){path}' for path in UPSTREAM_EXCLUDE)))
149
150
151 def whence_log(repo, rev_range):
152 """List linux-firmware changes to the WHENCE entries we ship.
153
154 linux-firmware rewrites WHENCE for every firmware file it carries, so
155 the commits touching it are of interest only when they change the part
156 of it which ends up in our packages: the entries of the files we ship,
157 the symlinks pointing at them, their versions and the licence they are
158 placed under. Those entries are what debian/copyright has to follow, so
159 they are worth a changelog item even when no file changes.
160 """
161 filter_whence = load_whence_filter()
162 filtered = {}
163
164 def filtered_whence(rev):
165 if rev not in filtered:
166 whence = git(repo, 'show', f'{rev}:{FIRMWARE_WHENCE}', check=False)
167 filtered[rev] = None if whence is None else \
168 ''.join(filter_whence(whence.splitlines(keepends=True)))
169 return filtered[rev]
170
171 lines = []
172 for line in git_lines(repo, 'log', '--no-merges', '--pretty=%H %s',
173 rev_range, '--', FIRMWARE_WHENCE):
174 rev, _, subject = line.partition(' ')
175 if filtered_whence(rev) != filtered_whence(rev + '^'):
176 lines.append(subject)
177
178 return lines
179
180
181 def firmware_log(repo, cur_ver, new_ver, patterns):
182 """List linux-firmware changes affecting the files we ship."""
183 check_repo(repo, cur_ver, new_ver)
184 rev_range = f'{cur_ver}..{new_ver}'
185
186 # Commits touching the files included in the firmware component. The
187 # 'glob' pathspec magic makes '**/' match any number of directories,
188 # including none, just like the copyright-format globs do.
189 pathspecs = [f':(glob){pattern}' for pattern in patterns
190 if pattern != FIRMWARE_WHENCE]
191 lines = git_lines(repo, 'log', '--no-merges', '--pretty=%s', rev_range,
192 '--', *pathspecs)
193
194 lines += whence_log(repo, rev_range)
195
196 return format_subjects(lines)
197
198
199 def format_section(intro, subjects):
200 lines = [line + '\n'
201 for line in textwrap.wrap(intro, width=79,
202 initial_indent=' * ',
203 subsequent_indent=' ',
204 break_long_words=False,
205 break_on_hyphens=False)]
206 for subject in subjects:
207 lines += [line + '\n'
208 for line in textwrap.wrap(subject, width=79,
209 initial_indent=' - ',
210 subsequent_indent=' ',
211 break_long_words=False,
212 break_on_hyphens=False)]
213 return lines
214
215
216 def parse_section(lines):
217 """Turn the items of a section back into a list of subjects.
218
219 Returns the subjects and the number of lines they occupy, so that long
220 items wrapped over several lines are handled as one.
221 """
222 subjects = []
223 for count, line in enumerate(lines):
224 if line.startswith(' - '):
225 subjects.append(line[len(' - '):].strip())
226 elif subjects and line.startswith(' ') and line.strip():
227 subjects[-1] += ' ' + line.strip()
228 else:
229 return subjects, count
230 return subjects, len(lines)
231
232
233 def parse_changelog(lines):
234 """Split the topmost changelog entry into header, body and the rest."""
235 match = CHANGELOG_HEADER_RE.match(lines[0]) if lines else None
236 if not match:
237 sys.exit('debian/changelog: cannot parse the topmost entry')
238
239 for end, line in enumerate(lines):
240 if line.startswith(' -- '):
241 break
242 else:
243 sys.exit('debian/changelog: unterminated topmost entry')
244
245 return match.groups(), lines[1:end], lines[end:]
246
247
248 def uploaded_version(lines, default):
249 """Version of the topmost entry which has been uploaded already.
250
251 The entry being worked on collects everything since that version, so it
252 is where the changelog of a new release starts.
253 """
254 for line in lines:
255 match = CHANGELOG_HEADER_RE.match(line)
256 if match and match.group(3) != 'UNRELEASED':
257 return match.group(2)
258 return default
259
260
261 def entry_start(body):
262 """Index of the first item of a changelog entry."""
263 return 1 if body and body[0].strip() == '' else 0
264
265
266 def merge_section(body, intro, prefix, subjects, pos, keep_intro=False):
267 """Insert (or refresh) a section of the changelog entry.
268
269 A section which is already there (because the script has been run for a
270 yet unreleased version before, or because the item has been added by
271 hand) is extended instead of duplicated. POS is where a new section is
272 added; the index just past the section is returned, so that the sections
273 keep the order they are given in. KEEP_INTRO preserves the wording of an
274 item which is already there.
275 """
276 for start, line in enumerate(body):
277 if line.startswith(f' * {prefix}'):
278 break
279 else:
280 section = format_section(intro, subjects)
281 body[pos:pos] = section
282 return pos + len(section)
283
284 # Skip over the continuation lines of the item itself
285 end = start + 1
286 heading = body[start][len(' * '):].strip()
287 while end < len(body) and body[end].startswith(' ') \
288 and not body[end].startswith(' - '):
289 heading += ' ' + body[end].strip()
290 end += 1
291
292 if keep_intro:
293 intro = heading.rstrip('.')
294 if not intro.endswith(':'):
295 intro += ':'
296
297 old, count = parse_section(body[end:])
298 section = format_section(intro, format_subjects(old + subjects))
299 body[start:end + count] = section
300 return start + len(section)
301
302
303 def main(repo, firmware_repo, version):
304 if not os.path.exists(CHANGELOG):
305 sys.exit(f'{CHANGELOG}: no such file, run this script from the top'
306 ' of the source package')
307
308 # Both upstreams release under the same YYYYMMDD tag
309 new_ver = version.removeprefix('0~')
310
311 lines = open(CHANGELOG, encoding='utf-8').readlines()
312 source, top_pkg_ver, distribution, urgency = parse_changelog(lines)[0]
313
314 # An entry which has not been uploaded yet describes the changes since
315 # the last upload, no matter how often its version has been bumped in
316 # the meantime.
317 cur_pkg_ver = uploaded_version(lines, top_pkg_ver)
318 cur_ver = cur_pkg_ver.rsplit('-', 1)[0].removeprefix('0~')
319
320 if cur_ver == new_ver:
321 print(f'Nothing to update, already at {new_ver}', file=sys.stderr)
322 return
323
324 upstream = upstream_log(repo, cur_ver, new_ver)
325 firmware = firmware_log(firmware_repo, cur_ver, new_ver,
326 firmware_includes(COPYRIGHT))
327
328 if not upstream and not firmware:
329 print(f'Nothing to update ({cur_ver} -> {new_ver})', file=sys.stderr)
330 return
331
332 sections = []
333 if upstream:
334 sections.append((UPSTREAM_INTRO, UPSTREAM_INTRO_PREFIX, upstream,
335 True))
336 if firmware:
337 # The heading carries the version, so it is always regenerated
338 sections.append((FIRMWARE_INTRO.format(new_ver),
339 FIRMWARE_INTRO_PREFIX, firmware, False))
340
341 new_pkg_ver = f'0~{new_ver}-1'
342
343 if distribution != 'UNRELEASED':
344 # The current version has been released, so start a new entry. dch
345 # takes care of the maintainer name and the timestamp; the item it
346 # inserts is only a placeholder for our sections.
347 placeholder = 'RELEASE-UPDATE-PLACEHOLDER'
348 subprocess.check_call(['dch', '-v', new_pkg_ver, '-D', 'UNRELEASED',
349 '--', placeholder])
350 header, body, tail = \
351 parse_changelog(open(CHANGELOG, encoding='utf-8')
352 .readlines())
353 body = [line for line in body if placeholder not in line]
354 header_line = (f'{header[0]} ({header[1]}) {header[2]};'
355 f' urgency={header[3]}\n')
356 else:
357 # The current version has not been released yet, so only its version
358 # string changes.
359 header, body, tail = \
360 parse_changelog(open(CHANGELOG, encoding='utf-8')
361 .readlines())
362 header_line = (f'{source} ({new_pkg_ver}) {distribution};'
363 f' urgency={urgency}\n')
364
365 pos = entry_start(body)
366 for intro, prefix, subjects, keep_intro in sections:
367 pos = merge_section(body, intro, prefix, subjects, pos, keep_intro)
368
369 with open(CHANGELOG + '.new', 'w', encoding='utf-8') as new_log:
370 new_log.write(header_line)
371 new_log.writelines(body)
372 new_log.writelines(tail)
373
374 os.rename(CHANGELOG + '.new', CHANGELOG)
375
376
377 if __name__ == '__main__':
378 if len(sys.argv) != 4:
379 print('''\
380 Usage: {} REPO FIRMWARE_REPO VERSION
381 REPO is the hexagon-dsp-binaries git repository
382 FIRMWARE_REPO is the linux-firmware git repository
383 VERSION is the upstream version, which both upstreams release under'''
384 .format(sys.argv[0]),
385 file=sys.stderr)
386 sys.exit(2)
387 main(*sys.argv[1:])