Debian Codegraph @

ci/build-tool

raw
1 #!/usr/bin/env python3
2 # ==========================================================================
3 # ____ _ _ _ _____ _
4 # | __ ) _ _(_) | __| | |_ _|__ ___ | |___
5 # | _ \| | | | | |/ _` |_____| |/ _ \ / _ \| / __|
6 # | |_) | |_| | | | (_| |_____| | (_) | (_) | \__ \
7 # |____/ \__,_|_|_|\__,_| |_|\___/ \___/|_|___/
8 #
9 # --- Build-Tools ---
10 # https://www.nntb.no/~dreibh/system-tools/
11 # ==========================================================================
12 #
13 # Unified Build Tool
14 # Copyright (C) 2021-2026 by Thomas Dreibholz
15 #
16 # This program is free software: you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation, either version 3 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
25 #
26 # You should have received a copy of the GNU General Public License
27 # along with this program. If not, see <http://www.gnu.org/licenses/>.
28 #
29 # Contact: [email protected]
30
31 import glob
32 import http.client
33 import os
34 import pprint
35 import random
36 import re
37 import shutil
38 import subprocess
39 import sys
40 import tempfile
41 import time
42 import urllib.error
43 import urllib.request
44
45 if sys.version_info < (3, 9):
46 sys.stderr.write('ERROR: ' + sys.argv[0] + ' requires Python 3.9 or later!\n')
47 sys.exit(1)
48
49 from typing import Any, Final, TextIO, cast
50
51 try:
52 import distro
53 except ImportError:
54 sys.stderr.write('ERROR: ' + sys.argv[0] + ' requires the Python distro package!\n')
55 sys.exit(1)
56
57
58 # ###########################################################################
59 # #### Constants ####
60 # ###########################################################################
61
62 TarballFormats : Final[list[str]] = [ 'xz', 'bz2', 'gz' ]
63 TarOptions : Final[dict[str,str]] = {
64 'xz': 'J',
65 'bz2': 'j',
66 'gz': 'z'
67 }
68
69 Systems : Final[list[list[str]]] = [
70 # Prefix System Name Configuration File
71 [ 'cmake', 'CMake', 'cmake_lists_name' ],
72 [ 'autoconf', 'AutoConf/AutoMake', 'autoconf_config_name' ],
73 [ 'other', 'Version File', 'other_file_name' ],
74 [ 'rpm', 'RPM Spec', 'rpm_spec_name' ],
75 [ 'debian', 'Debian Changelog', 'debian_changelog_name' ],
76 [ 'port', 'Port Makefile', 'port_makefile_name' ]
77 ]
78
79 DebianCodenames : list[str] | None = None # Will be initialised later!
80 UbuntuCodenames : list[str] | None = None # Will be initialised later!
81
82 DebhelperLatestVersion : Final[int] = 13
83 DebhelperCompatFixes : Final[dict[str,int]] = {
84 'precise': 9,
85 'trusty': 9,
86 'xenial': 9,
87 'bionic': 11,
88 'focal': 12
89 }
90
91
92 # ###########################################################################
93 # #### Helper Functions ####
94 # ###########################################################################
95
96
97 # ###### Print section header ###############################################
98 def printSection(title : str) -> None:
99 now : Final[str] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
100 sys.stdout.write('\n\x1b[34m' + (now + ' ====== ' + title + ' ').ljust(132, '=') + '\x1b[0m\n\n')
101
102
103 # ###### Print subsection header ############################################
104 def printSubsection(title : str) -> None:
105 now : Final[str] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
106 sys.stdout.write('\n\x1b[34m' + (now + ' ------ ' + title + ' ').ljust(132, '-') + '\x1b[0m\n')
107
108
109 # ###### Show difference between two files ##################################
110 def showDiff(a : str, b : str) -> None:
111 try:
112 subprocess.run( [ 'diff', '--color=always', a, b ] )
113 except Exception as e:
114 sys.stderr.write('ERROR: Diff run failed: ' + str(e) + '\n')
115 sys.exit(1)
116
117
118 # ###### Read file and return list of lines #################################
119 def readTextFile(inputName : str) -> list[str]:
120
121 inputFile : TextIO = open(inputName, 'r', encoding='utf-8')
122 contents : list[str] = inputFile.readlines()
123 inputFile.close()
124
125 return contents
126
127
128 # ###### Write file by list of lines ########################################
129 def writeTextFile(outputName : str, contents : list[str]) -> None:
130 outputFile = open(outputName, 'w', encoding='utf-8')
131 for line in contents:
132 outputFile.write(line)
133
134
135 # ###### Get system architecture ############################################
136 def getArchitecture() -> str:
137 return os.uname().machine
138
139
140
141 # ###########################################################################
142 # #### Packaging ####
143 # ###########################################################################
144
145
146 # ###### Obtain distribution codenames ######################################
147 def obtainDistributionCodenames() -> None:
148 global DebianCodenames
149 global UbuntuCodenames
150 DebianCodenames = getDistributionCodenames()
151 UbuntuCodenames = getDistributionCodenames('ubuntu')
152
153
154 # ###### Read packaging configuration from packaging.conf ###################
155 def readPackagingConfiguration() -> dict[str,Any]:
156
157 # ====== Initialise ======================================================
158 packageInfo : dict[str,Any] = { }
159 packageInfo['packaging_maintainer'] = None
160 packageInfo['packaging_maintainer_key'] = None
161 packageInfo['packaging_make_dist'] = None
162 packageInfo['packaging_config_name'] = 'packaging.conf'
163
164 # ====== Obtain package configuration ====================================
165 re_package_maintainer : Final[re.Pattern[str]] = re.compile(r'^(MAINTAINER=\")(.*)(\".*$)')
166 re_package_maintainer_key : Final[re.Pattern[str]] = re.compile(r'^(MAINTAINER_KEY=\")(.*)(\".*$)')
167 re_package_makedist : Final[re.Pattern[str]] = re.compile(r'^(MAKE_DIST=\")(.*)(\".*$)')
168 try:
169 packagingConfFile : TextIO = open(packageInfo['packaging_config_name'], 'r', encoding='utf-8')
170 packagingConfFileContents : list[str] = packagingConfFile.readlines()
171 for line in packagingConfFileContents:
172 match : re.Match[str] | None = re_package_maintainer.match(line)
173 if match is not None:
174 packageInfo['packaging_maintainer'] = match.group(2)
175 else:
176 match = re_package_maintainer_key.match(line)
177 if match is not None:
178 packageInfo['packaging_maintainer_key'] = match.group(2)
179 else:
180 match = re_package_makedist.match(line)
181 if match is not None:
182 packageInfo['packaging_make_dist'] = match.group(2)
183 packagingConfFile.close()
184 except Exception as e:
185 sys.stderr.write('ERROR: Unable to read ' + packageInfo['packaging_config_name'] + ': ' + str(e) + '\n')
186 sys.exit(1)
187
188 if packageInfo['packaging_maintainer'] is None:
189 sys.stderr.write('ERROR: Unable to find MAINTAINER in ' + packageInfo['packaging_config_name'] + '!\n')
190 sys.exit(1)
191 elif packageInfo['packaging_make_dist'] is None:
192 sys.stderr.write('ERROR: Unable to find MAKE_DIST in ' + packageInfo['packaging_config_name'] + '!\n')
193 sys.exit(1)
194
195 return packageInfo
196
197
198 # ###### Read CMake packaging information ###################################
199 def readCMakePackagingInformation() -> dict[str,Any]:
200
201 # ====== Initialise ======================================================
202 packageInfo : dict[str,Any] = { }
203
204 # ====== Obtain package configuration ====================================
205 cmakeListsFile = 'CMakeLists.txt'
206 if os.path.isfile(cmakeListsFile):
207 re_cmake_project : Final[re.Pattern[str]] = re.compile(r'[ \t]*[Pp][Rr][Oo][Jj][Ee][Cc][Tt][ \t]*\(([a-zA-Z0-9-+]+)')
208 re_cmakefile_major : Final[re.Pattern[str]] = re.compile(r'^[Ss][Ee][Tt]\((BUILD_MAJOR|PROJECT_MAJOR_VERSION)[ \t]*("|)(\d+)("|)[ \t]*\)')
209 re_cmakefile_minor : Final[re.Pattern[str]] = re.compile(r'^[Ss][Ee][Tt]\((BUILD_MINOR|PROJECT_MINOR_VERSION)[ \t]*("|)(\d+)("|)[ \t]*\)')
210 re_cmakefile_patch : Final[re.Pattern[str]] = re.compile(r'^[Ss][Ee][Tt]\((BUILD_PATCH|PROJECT_PATCH_VERSION)[ \t]*("|)(\d+)(~[a-zA-Z0-9\.+~]+|)("|)[ \t]*\)')
211
212 packageInfo['cmake_lists_name'] = cmakeListsFile
213 try:
214 cmakeFile : TextIO = open(packageInfo['cmake_lists_name'], 'r', encoding='utf-8')
215 cmakeFileContents : Final[list[str]] = cmakeFile.readlines()
216 for line in cmakeFileContents:
217 match = re_cmakefile_major.match(line)
218 if match is not None:
219 packageInfo['cmake_version_major'] = int(match.group(3))
220 else:
221 match = re_cmakefile_minor.match(line)
222 if match is not None:
223 packageInfo['cmake_version_minor'] = int(match.group(3))
224 else:
225 match = re_cmakefile_patch.match(line)
226 if match is not None:
227 packageInfo['cmake_version_patch'] = int(match.group(3))
228 packageInfo['cmake_version_extra'] = match.group(4)
229 else:
230 match = re_cmake_project.match(line)
231 if match is not None:
232 packageInfo['cmake_package_name'] = match.group(1)
233 cmakeFile.close()
234
235 if ('cmake_version_major' in packageInfo) and \
236 ('cmake_version_minor' in packageInfo) and \
237 ('cmake_version_patch' in packageInfo) and \
238 ('cmake_version_extra' in packageInfo):
239 packageInfo['cmake_version_string'] = \
240 str(packageInfo['cmake_version_major']) + '.' + \
241 str(packageInfo['cmake_version_minor']) + '.' + \
242 str(packageInfo['cmake_version_patch']) + packageInfo['cmake_version_extra']
243
244 except Exception as e:
245 sys.stderr.write('ERROR: Unable to read ' + packageInfo['cmake_lists_name'] + ': ' + str(e) + '\n')
246 sys.exit(1)
247
248 # ====== Check whether information is complete ========================
249 if ( ( not 'cmake_package_name' in packageInfo) or
250 ( not 'cmake_version_string' in packageInfo ) ):
251 sys.stderr.write('ERROR: Cannot find required package versioning details in ' + packageInfo['cmake_lists_name'] + '!\n')
252 print(packageInfo)
253 sys.exit(1)
254
255 return packageInfo
256
257
258 # ###### Read AutoConf packaging information ################################
259 def readAutoConfPackagingInformation() -> dict[str,Any]:
260
261 # ====== Initialise ======================================================
262 packageInfo : dict[str,Any] = { }
263
264 # ====== Obtain package configuration ====================================
265 for autoconfConfigName in [ 'configure.ac', 'configure.in' ]:
266 if os.path.isfile(autoconfConfigName):
267 break
268 if os.path.isfile(autoconfConfigName):
269 re_autoconffile_version : Final[re.Pattern[str]] = \
270 re.compile(r'^AC_INIT\([ \t]*\[(.*)\][ \t]*,[ \t]*\[(\d).(\d).(\d+)([~+][a-zA-Z0-9\.+]+|)\][ \t]*,[ \t]*\[(.*)\][ \t]*\)')
271
272 packageInfo['autoconf_config_name'] = autoconfConfigName
273 try:
274 autoconfFile : TextIO = open(packageInfo['autoconf_config_name'], 'r', encoding='utf-8')
275 autoconfFileContents : Final[list[str]] = autoconfFile.readlines()
276 for line in autoconfFileContents:
277 match = re_autoconffile_version.match(line)
278 if match is not None:
279 packageInfo['autoconf_package_name'] = match.group(1)
280 packageInfo['autoconf_version_major'] = int(match.group(2))
281 packageInfo['autoconf_version_minor'] = int(match.group(3))
282 packageInfo['autoconf_version_patch'] = int(match.group(4))
283 packageInfo['autoconf_version_extra'] = match.group(5)
284 packageInfo['autoconf_version_string'] = \
285 str(packageInfo['autoconf_version_major']) + '.' + \
286 str(packageInfo['autoconf_version_minor']) + '.' + \
287 str(packageInfo['autoconf_version_patch']) + packageInfo['autoconf_version_extra']
288 break
289 autoconfFile.close()
290
291 except Exception as e:
292 sys.stderr.write('ERROR: Unable to read ' + packageInfo['autoconf_config_name'] + ': ' + str(e) + '\n')
293 sys.exit(1)
294
295 # ====== Check whether information is complete ========================
296 if ( ( not 'autoconf_package_name' in packageInfo) or
297 ( not 'autoconf_version_string' in packageInfo ) ):
298 sys.stderr.write('ERROR: Cannot find required package versioning details in ' + packageInfo['autoconf_config_name'] + '!\n')
299 sys.exit(1)
300
301 return packageInfo
302
303
304 # ###### Read Debian packaging information ##################################
305 def readDebianPackagingInformation() -> dict[str,Any]:
306
307 # ====== Initialise ======================================================
308 packageInfo : dict[str,Any] = { }
309 debianChangelogName : Final[str] = 'debian/changelog'
310 debianControlName : Final[str] = 'debian/control'
311 debianRulesName : Final[str] = 'debian/rules'
312
313 # ====== Process changelog file ==========================================
314 if ( (os.path.isfile(debianChangelogName)) and
315 (os.path.isfile(debianControlName)) and
316 (os.path.isfile(debianRulesName)) ):
317 re_debian_version : Final[re.Pattern[str]] = re.compile(r'^([a-zA-Z0-9-+]+)[ \t]*\((\d+:|)(\d+)\.(\d+)\.(\d+)([a-zA-Z0-9+~\.]*)(-|)(\d[a-zA-Z0-9-+~]*|)\)[ \t]*([a-zA-Z-+]+)[ \t]*;(.*)$')
318 re_debian_itp1 : Final[re.Pattern[str]] = re.compile(r'^ * .*ITP.*Closes: #([0-9]+).*$')
319 re_debian_itp2 : Final[re.Pattern[str]] = re.compile(r'^ * .*Closes: #([0-9]+).*ITP.*$')
320
321 packageInfo['debian_changelog_name'] = debianChangelogName
322 packageInfo['debian_control_name'] = debianControlName
323 packageInfo['debian_rules_name'] = debianRulesName
324 packageInfo['debian_package_name'] = None
325 packageInfo['debian_version_string'] = None
326 packageInfo['debian_standards_version'] = None
327 packageInfo['debian_codename'] = None
328 packageInfo['debian_itp'] = None
329 packageInfo['debian_status'] = None
330
331 try:
332 debianChangeLogFile : TextIO = open(debianChangelogName, 'r', encoding='utf-8')
333 debianChangeLogFileContents : Final[list[str]] = debianChangeLogFile.readlines()
334 n : int = 0
335 for line in debianChangeLogFileContents:
336 n = n + 1
337 if n == 1:
338 match = re_debian_version.match(line)
339 if match is not None:
340 packageInfo['debian_package_name'] = match.group(1)
341 packageInfo['debian_version_prefix'] = match.group(2)
342 packageInfo['debian_version_major'] = int(match.group(3))
343 packageInfo['debian_version_minor'] = int(match.group(4))
344 packageInfo['debian_version_patch'] = int(match.group(5))
345 packageInfo['debian_version_extra'] = match.group(6)
346 packageInfo['debian_version_packaging'] = match.group(8)
347 packageInfo['debian_codename'] = match.group(9)
348 packageInfo['debian_version_string'] = \
349 str(packageInfo['debian_version_major']) + '.' + \
350 str(packageInfo['debian_version_minor']) + '.' + \
351 str(packageInfo['debian_version_patch']) + packageInfo['debian_version_extra']
352 packageInfo['debian_urgency'] = 'low'
353
354 options : list[str] = match.group(9).split(';')
355 for option in options:
356 optionSplit : list[str] = option.strip().split('=')
357 if len(optionSplit) == 2:
358 if optionSplit[0].strip() == 'urgency':
359 packageInfo['debian_urgency'] = optionSplit[1].strip()
360
361 elif n > 1:
362 match = re_debian_itp1.match(line)
363 if match is None:
364 match = re_debian_itp2.match(line)
365 if match is not None:
366 # print('ITP: ' + line)
367 packageInfo['debian_itp'] = int(match.group(1))
368 break
369 debianChangeLogFile.close()
370
371 except Exception as e:
372 sys.stderr.write('ERROR: Unable to read ' + debianChangelogName + ': ' + str(e) + '\n')
373 sys.exit(1)
374
375 if packageInfo['debian_package_name'] is None:
376 sys.stderr.write('ERROR: Cannot find required package versioning details in ' + debianChangelogName + '!\n')
377 sys.exit(1)
378
379 # ====== Check whether information is complete ========================
380 if not 'debian_package_name' in packageInfo:
381 sys.stderr.write('ERROR: Cannot find required package versioning details in ' + debianChangelogName + '!\n')
382 sys.exit(1)
383
384 # ====== Process control file =========================================
385 re_debian_standards_version : Final[re.Pattern[str]] = re.compile(r'^Standards-Version:[ \t]*([0-9\.]*)[ \t]*$')
386 try:
387 debianControlFile : TextIO = open(debianControlName, 'r', encoding='utf-8')
388 debianControlFileContents : Final[list[str]] = debianControlFile.readlines()
389 for line in debianControlFileContents:
390 match = re_debian_standards_version.match(line)
391 if match is not None:
392 packageInfo['debian_standards_version'] = match.group(1)
393 debianControlFile.close()
394 except Exception as e:
395 sys.stderr.write('ERROR: Unable to read ' + debianControlName + ': ' + str(e) + '\n')
396 sys.exit(1)
397
398 return packageInfo
399
400
401 # ###### Read RPM packaging information #####################################
402 def readRPMPackagingInformation() -> dict[str,Any]:
403
404 # ====== Initialise ======================================================
405 packageInfo : dict[str,Any] = { }
406 rpmSpecNames : Final[list[str]] = glob.glob('rpm/*.spec')
407
408 # ====== Obtain package configuration ====================================
409 if len(rpmSpecNames) == 1:
410 packageInfo['rpm_spec_name'] = rpmSpecNames[0]
411 packageInfo['rpm_packages'] = [ ]
412
413 re_rpm_name : Final[re.Pattern[str]] = re.compile(r'^(Name:[ \t]*)(\S+)')
414 re_rpm_version : Final[re.Pattern[str]] = re.compile(r'^(Version:[ \t]*)(\d+)\.(\d+)\.(\d+)(.*|)')
415 re_rpm_release : Final[re.Pattern[str]] = re.compile(r'^(Release:[ \t]*)(\d+)')
416 re_rpm_package : Final[re.Pattern[str]] = re.compile(r'^(%package[ \t]+)([a-zA-Z0-9+-]+)')
417 try:
418 rpmSpecFile : TextIO = open(packageInfo['rpm_spec_name'], 'r', encoding='utf-8')
419 rpmSpecFileContents : Final[list[str]] = rpmSpecFile.readlines()
420 packageInfo['rpm_version_packaging'] = None
421 for line in rpmSpecFileContents:
422 match : re.Match[str] | None = re_rpm_version.match(line)
423 if match is not None:
424 packageInfo['rpm_version_major'] = int(match.group(2))
425 packageInfo['rpm_version_minor'] = int(match.group(3))
426 packageInfo['rpm_version_patch'] = int(match.group(4))
427 packageInfo['rpm_version_extra'] = match.group(5)
428 packageInfo['rpm_version_string'] = \
429 str(packageInfo['rpm_version_major']) + '.' + \
430 str(packageInfo['rpm_version_minor']) + '.' + \
431 str(packageInfo['rpm_version_patch']) + packageInfo['rpm_version_extra']
432 else:
433 match = re_rpm_release.match(line)
434 if match is not None:
435 packageInfo['rpm_version_packaging'] = int(match.group(2))
436 else:
437 match = re_rpm_name.match(line)
438 if match is not None:
439 packageInfo['rpm_package_name'] = match.group(2)
440 else:
441 match = re_rpm_package.match(line)
442 if match is not None:
443 packageInfo['rpm_packages'].append(
444 packageInfo['rpm_package_name'] + '-' + \
445 match.group(2) + '-' + \
446 packageInfo['rpm_version_string'] + '-' + \
447 str(packageInfo['rpm_version_packaging']))
448
449 rpmSpecFile.close()
450
451 except Exception as e:
452 sys.stderr.write('ERROR: Unable to read ' + packageInfo['rpm_spec_name'] + ': ' + str(e) + '\n')
453 sys.exit(1)
454
455 # ====== Check whether information is complete ========================
456 if ( (not 'rpm_package_name' in packageInfo) or
457 (not 'rpm_version_packaging' in packageInfo) or
458 (not 'rpm_version_string' in packageInfo) ):
459 sys.stderr.write('ERROR: Cannot find required package versioning details in ' + packageInfo['rpm_spec_name'] + '!\n')
460 sys.exit(1)
461 packageInfo['rpm_packages'].append(
462 packageInfo['rpm_package_name'] + '-' +
463 packageInfo['rpm_version_string'] + '-' +
464 str(packageInfo['rpm_version_packaging']))
465 # print(packageInfo['rpm_packages'])
466
467 elif len(rpmSpecNames) > 1:
468 sys.stderr.write('ERROR: More than one spec file found: ' + str(rpmSpecNames) + '!\n')
469 sys.exit(1)
470
471 return packageInfo
472
473
474 # ###### Read FreeBSD ports packaging information ###########################
475 def readFreeBSDPackagingInformation() -> dict[str,Any]:
476
477 # ====== Initialise ======================================================
478 packageInfo : dict[str,Any] = { }
479 port_makefile_names : Final[list[str]] = glob.glob('freebsd/*/Makefile')
480
481 # ====== Obtain package configuration ====================================
482 if len(port_makefile_names) > 0:
483 packageInfo['port_makefile_name'] = port_makefile_names[0]
484 re_freebsd_version : Final[re.Pattern[str]] = re.compile(r'^(DISTVERSION=[ \t]*)(\d+)\.(\d+)\.(\d+)(.*|)')
485 try:
486 freeBSDMakefileFile : TextIO = open(packageInfo['port_makefile_name'], 'r', encoding='utf-8')
487 freeBSDMakefileFileContents : Final[list[str]] = freeBSDMakefileFile.readlines()
488 for line in freeBSDMakefileFileContents:
489 match : re.Match[str] | None = re_freebsd_version.match(line)
490 if match is not None:
491 packageInfo['port_version_major'] = int(match.group(2))
492 packageInfo['port_version_minor'] = int(match.group(3))
493 packageInfo['port_version_patch'] = int(match.group(4))
494 packageInfo['port_version_extra'] = match.group(5)
495 packageInfo['port_version_string'] = \
496 str(packageInfo['port_version_major']) + '.' + \
497 str(packageInfo['port_version_minor']) + '.' + \
498 str(packageInfo['port_version_patch']) + packageInfo['port_version_extra']
499 freeBSDMakefileFile.close()
500
501 except Exception as e:
502 sys.stderr.write('ERROR: Unable to read ' + packageInfo['port_makefile_name'] + ': ' + str(e) + '\n')
503 sys.exit(1)
504
505 # ====== Check whether information is complete ========================
506 if not 'port_version_string' in packageInfo:
507 sys.stderr.write('ERROR: Cannot find required package versioning details in ' + packageInfo['port_makefile_name'] + '!\n')
508 sys.exit(1)
509
510 return packageInfo
511
512
513 # ###### Read other packaging information ###################################
514 def readOtherPackagingInformation() -> dict[str,Any]:
515
516 # ====== Initialise ======================================================
517 packageInfo : dict[str,Any] = { }
518
519 # ====== Obtain package configuration ====================================
520 for otherFileName in [ 'version' ]:
521 if os.path.isfile(otherFileName):
522 break
523
524 if os.path.isfile(otherFileName):
525 packageInfo['other_file_name'] = otherFileName
526 re_otherfile_version : Final[re.Pattern[str]] = \
527 re.compile(r'(\S+) (\d).(\d).(\d+)([~+][a-zA-Z0-9\.+]+|)')
528 try:
529 otherFile : TextIO = open(otherFileName, 'r', encoding='utf-8')
530 otherFileContents : Final[list[str]] = otherFile.readlines()
531 line : str = otherFileContents[0]
532 match : re.Match[str] | None = re_otherfile_version.match(line)
533 if match is not None:
534 packageInfo['other_package_name'] = match.group(1)
535 packageInfo['other_version_major'] = int(match.group(2))
536 packageInfo['other_version_minor'] = int(match.group(3))
537 packageInfo['other_version_patch'] = int(match.group(4))
538 packageInfo['other_version_extra'] = match.group(5)
539 packageInfo['other_version_string'] = \
540 str(packageInfo['other_version_major']) + '.' + \
541 str(packageInfo['other_version_minor']) + '.' + \
542 str(packageInfo['other_version_patch']) + packageInfo['other_version_extra']
543 otherFile.close()
544
545 except Exception as e:
546 sys.stderr.write('ERROR: Unable to read ' + otherFileName + ': ' + str(e) + '\n')
547 sys.exit(1)
548
549 # ====== Check whether information is complete ========================
550 if not 'other_package_name' in packageInfo:
551 sys.stderr.write('ERROR: Cannot find required package versioning details in ' + otherFileName + '!\n')
552 sys.exit(1)
553
554 return packageInfo
555
556
557 # ###### Read packaging information #########################################
558 def readPackagingInformation() -> dict[str,Any]:
559
560 # ====== Read information from different packaging system files ==========
561 packageInfo : dict[str,Any] = readPackagingConfiguration()
562
563 cmakePackageInfo : Final[dict[str,Any]] = readCMakePackagingInformation()
564 if cmakePackageInfo is not None:
565 packageInfo.update(cmakePackageInfo)
566
567 autoconfPackageInfo : Final[dict[str,Any]] = readAutoConfPackagingInformation()
568 if autoconfPackageInfo is not None:
569 packageInfo.update(autoconfPackageInfo)
570
571 debianPackageInfo : Final[dict[str,Any]] = readDebianPackagingInformation()
572 if debianPackageInfo is not None:
573 packageInfo.update(debianPackageInfo)
574
575 rpmPackageInfo : Final[dict[str,Any]] = readRPMPackagingInformation()
576 if rpmPackageInfo is not None:
577 packageInfo.update(rpmPackageInfo)
578
579 freeBSDPackageInfo : Final[dict[str,Any]] = readFreeBSDPackagingInformation()
580 if freeBSDPackageInfo is not None:
581 packageInfo.update(freeBSDPackageInfo)
582
583 otherPackageInfo : Final[dict[str,Any]] = readOtherPackagingInformation()
584 if otherPackageInfo is not None:
585 packageInfo.update(otherPackageInfo)
586
587
588 # ====== Obtain master packaging information =============================
589 for system in Systems:
590 systemPrefix : str = system[0]
591 if hasPackagingFor(packageInfo, systemPrefix):
592 systemName : str = system[1]
593 systemConfigFile : str = system[2]
594 sys.stdout.write('Using master versioning from ' + systemName + '.\n')
595 for entry in [ 'package_name', 'version_string', 'version_major', 'version_minor', 'version_patch', 'version_extra' ]:
596 assert systemPrefix + '_' + entry in packageInfo
597 packageInfo['master_' + entry] = packageInfo[systemPrefix + '_' + entry]
598 break
599 if not hasPackagingFor(packageInfo, 'master'):
600 sys.stderr.write('ERROR: Unable to obtain master packaging information!\n')
601 sys.exit(1)
602
603
604 # ====== Check master packaging information ==============================
605 for system in Systems:
606 systemPrefix = system[0]
607 if hasPackagingFor(packageInfo, systemPrefix):
608 systemName = system[1]
609 systemConfigFile = system[2]
610 sys.stdout.write(('Version from ' + systemName + ': ').ljust(32, ' ') + \
611 packageInfo[systemPrefix + '_version_string'] + \
612 ' (from ' + packageInfo[systemConfigFile] + ')\n')
613 if packageInfo[systemPrefix + '_version_string'] != packageInfo['master_version_string']:
614 sys.stderr.write('ERROR: ' + systemName + ' version ' + \
615 packageInfo[systemPrefix + '_version_string'] + ' does not match master version ' + \
616 packageInfo['master_version_string'] + '!\n')
617 sys.exit(1)
618
619
620 # ====== Look for source tarball =========================================
621 sourcePackageInfo : dict[str,Any] | None = findSourceTarball(packageInfo)
622 if sourcePackageInfo is not None:
623 packageInfo.update(sourcePackageInfo)
624
625 return packageInfo
626
627
628 # ###### Find source tarball ################################################
629 def findSourceTarball(packageInfo : dict[str,Any],
630 quiet : bool = False) -> dict[str,Any] | None:
631
632 # ====== Initialise ======================================================
633 sourceInfo : dict[str,Any] = { }
634
635 # ====== Obtain package configuration ====================================
636 tarballPattern : Final[str] = \
637 packageInfo['master_package_name'] + '-' + \
638 packageInfo['master_version_string'] + '.tar.*'
639 if not quiet:
640 sys.stdout.write('Looking for tarball ' + tarballPattern + ' ... ')
641 tarballs : Final[list[str]] = \
642 glob.glob(tarballPattern) # NOTE: This will also find .tar.xz.asc, etc.!
643 for tarball in tarballs:
644 extension = os.path.splitext(tarball)[1][1:]
645 if extension in TarballFormats:
646 sourceInfo['source_tarball_name'] = tarball
647 sourceInfo['source_tarball_format'] = extension
648
649 # ====== Check for signature file ==================================
650 signature = sourceInfo['source_tarball_name'] + '.asc'
651 if os.path.isfile(signature):
652 sourceInfo['source_tarball_signature'] = signature
653
654 if not quiet:
655 sys.stdout.write('Found ' + sourceInfo['source_tarball_name'] + \
656 ' (format is ' + sourceInfo['source_tarball_format'] + ', signature in ')
657 if 'source_tarball_signature' in sourceInfo:
658 sys.stdout.write(sourceInfo['source_tarball_signature'] + ').\n')
659 else:
660 sys.stdout.write('MISSING!).\n')
661
662 return sourceInfo
663
664 if not quiet:
665 sys.stdout.write('not found!\n')
666
667 return None
668
669
670 # ###### Check whether specific packaging information is available ##########
671 def hasPackagingFor(packageInfo : dict[str,Any],
672 variant : str) -> bool:
673 if variant + '_version_string' in packageInfo:
674 return True
675 return False
676
677
678
679 # ###########################################################################
680 # #### Tools ####
681 # ###########################################################################
682
683
684 # ###### Show package information ###########################################
685 def showInformation(packageInfo : dict[str,Any]) -> None:
686 pprint.pprint(packageInfo, indent=1)
687
688
689 # ###### Make source tarball ################################################
690 def makeSourceTarball(packageInfo : dict[str,Any],
691 skipPackageSigning : bool,
692 summaryFile : TextIO | None) -> bool:
693
694 printSection('Creating source tarball')
695
696 # ====== Make source tarball =============================================
697 if 'source_tarball_name' in packageInfo:
698 sourcePackageInfo = findSourceTarball(packageInfo, quiet = True)
699 if sourcePackageInfo is None:
700 sys.stderr.write('ERROR: Unable to find source tarball!\n')
701 return False
702 assert sourcePackageInfo is not None
703 sys.stdout.write('Tarball is already there: ' + sourcePackageInfo['source_tarball_name'] + \
704 ' (format is ' + sourcePackageInfo['source_tarball_format'] + ')\n')
705 else:
706 print(packageInfo['packaging_make_dist'])
707 result = os.system(packageInfo['packaging_make_dist'])
708 if result != 0:
709 sys.stderr.write('ERROR: Unable to create source tarball!\n')
710 return False
711 sourcePackageInfo = findSourceTarball(packageInfo, quiet=(not skipPackageSigning))
712 if sourcePackageInfo is None:
713 sys.stderr.write('ERROR: Unable to find source tarball!\n')
714 return False
715 assert sourcePackageInfo is not None
716 # The source tarball is new, i.e. an existing signature is obsolete and
717 # must be deleted.
718 try:
719 os.unlink(sourcePackageInfo['source_tarball_name'] + '.asc')
720 except FileNotFoundError:
721 pass
722
723 if summaryFile is not None:
724 summaryFile.write('sourceTarballFile: ' + os.path.abspath(sourcePackageInfo['source_tarball_name']) + '\n')
725
726 # ====== Sign tarball ====================================================
727 if skipPackageSigning == False:
728 if 'source_tarball_signature' in sourcePackageInfo:
729 sys.stdout.write('Signature is already there: ' + sourcePackageInfo['source_tarball_signature'] + '\n')
730
731 else:
732 result = os.system('gpg --sign --armor --detach-sign ' + \
733 sourcePackageInfo['source_tarball_name'])
734 if result != 0:
735 sys.stderr.write('ERROR: Unable to sign source tarball!\n')
736 return False
737 sourcePackageInfo = findSourceTarball(packageInfo)
738 if ( (sourcePackageInfo is None) or
739 (not 'source_tarball_name' in sourcePackageInfo) ):
740 sys.stderr.write('ERROR: Unable to find signature of source tarball!\n')
741 assert sourcePackageInfo is not None
742
743 result = os.system('gpg --verify ' + \
744 sourcePackageInfo['source_tarball_signature'] + ' ' + \
745 sourcePackageInfo['source_tarball_name'])
746 if result == 0:
747 sys.stderr.write('Signature verified.\n')
748 else:
749 sys.stderr.write('ERROR: Bad signature! Something is wrong!\n')
750 return False
751
752 if summaryFile is not None:
753 summaryFile.write('sourceTarballSignatureFile: ' + os.path.abspath(sourcePackageInfo['source_tarball_signature']) + '\n')
754
755 packageInfo.update(sourcePackageInfo)
756 return True
757
758
759 # ###### Get modified debian packaging version for given codename ###########
760 def modifyDebianVersionPackaging(packageInfo : dict[str,Any],
761 codename : str) -> str:
762 assert DebianCodenames is not None
763
764 # ------- Debian ------------------------------------------------------
765 if codename in DebianCodenames:
766 # Update codename and package versioning:
767 # Drop Ubuntu packaging version:
768 if codename == 'unstable':
769 newSuffix : str = ''
770 else:
771 newSuffix = '~' + codename + '1'
772 newDebianVersionPackaging : str = re.sub(r'(ubuntu|ppa|)[0-9]+$', newSuffix,
773 packageInfo['debian_version_packaging'])
774
775 # ------- Ubuntu ------------------------------------------------------
776 else:
777 # Update codename and package versioning:
778 # Drop Ubuntu packaging version:
779 newDebianVersionPackaging = re.sub(r'[0-9]+$', '~' + codename + '1',
780 packageInfo['debian_version_packaging'])
781
782 return newDebianVersionPackaging
783
784
785 # ###### Get Debian/Ubuntu codenames ########################################
786 def getDistributionCodenames(distribution : str = 'debian') -> list[str]:
787
788 if distribution == 'debian':
789 distroInfo : str = 'debian-distro-info'
790 else:
791 distroInfo = 'ubuntu-distro-info'
792 try:
793 process : subprocess.Popen[str] = \
794 subprocess.Popen([ distroInfo, '--all'],
795 stdout=subprocess.PIPE, universal_newlines=True)
796 assert process is not None
797 assert process.stdout is not None
798 result : Final[list[str]] = process.stdout.readlines()
799 except Exception as e:
800 sys.stderr.write('ERROR: Unable to obtain Debian codenames: ' + str(e) + '\n')
801 sys.exit(1)
802
803 codenames : list[str] = [ codename.strip() for codename in result ]
804 if distribution == 'debian':
805 codenames += [ 'unstable', 'testing', 'stable', 'oldstable' ]
806 codenames += [ codename.strip() + '-backports' for codename in result]
807 codenames += [ codename.strip() + '-backports-sloppy' for codename in result]
808 codenames = sorted(codenames)
809
810 # pprint.pprint(codenames, indent=1)
811 return codenames
812
813
814 # ###### Get Debian default architecture ####################################
815 def getDebianDefaultArchitecture() -> str:
816 try:
817 process : subprocess.Popen[str] = \
818 subprocess.Popen([ 'dpkg', '--print-architecture'],
819 stdout=subprocess.PIPE, universal_newlines=True)
820 assert process is not None
821 assert process.stdout is not None
822 result : Final[str] = process.stdout.readlines()[0].strip()
823 except Exception as e:
824 sys.stderr.write('ERROR: Unable to obtain Debian default architecture: ' + str(e) + '\n')
825 sys.exit(1)
826 return result
827
828
829 # ###### Get name of Debian DSC file name ###################################
830 def getDebianDscName(packageInfo : dict[str,Any],
831 debianVersionPackaging : str | None = None) -> str:
832
833 if debianVersionPackaging is None:
834 debianVersionPackaging = packageInfo['debian_version_packaging']
835 assert debianVersionPackaging is not None
836 dscFileName : Final[str] = \
837 str(packageInfo['debian_package_name']) + '_' + \
838 str(packageInfo['debian_version_string']) + '-' + \
839 debianVersionPackaging + '.dsc'
840 return dscFileName
841
842
843 # ###### Get name of Debian source buildinfo name ###########################
844 def getDebianBuildinfoName(packageInfo : dict[str,Any],
845 debianVersionPackaging : str | None = None,
846 architecture : str = 'source') -> str:
847
848 if debianVersionPackaging is None:
849 debianVersionPackaging = packageInfo['debian_version_packaging']
850 assert debianVersionPackaging is not None
851 sourceBuildInfoFileName : Final[str] = \
852 str(packageInfo['debian_package_name']) + '_' + \
853 str(packageInfo['debian_version_string']) + '-' + \
854 debianVersionPackaging + '_' + \
855 architecture + '.buildinfo'
856 return sourceBuildInfoFileName
857
858
859 # ###### Get name of Debian source buildinfo name ###########################
860 def getDebianChangesName(packageInfo : dict[str,Any],
861 debianVersionPackaging : str | None = None,
862 architecture : str = 'source') -> str:
863
864 if debianVersionPackaging is None:
865 debianVersionPackaging = packageInfo['debian_version_packaging']
866 assert debianVersionPackaging is not None
867 changesFileName : Final[str] = \
868 str(packageInfo['debian_package_name']) + '_' + \
869 str(packageInfo['debian_version_string']) + '-' + \
870 debianVersionPackaging + '_' + \
871 architecture + '.changes'
872 return changesFileName
873
874
875 # ###### Get name of Debian control tarball name ############################
876 def getDebianControlTarballName(packageInfo : dict[str,Any],
877 debianVersionPackaging : str | None = None) -> str:
878
879 if debianVersionPackaging is None:
880 debianVersionPackaging = packageInfo['debian_version_packaging']
881 assert debianVersionPackaging is not None
882 controlTarballFileName : Final[str] =\
883 str(packageInfo['debian_package_name']) + '_' + \
884 str(packageInfo['debian_version_string']) + '-' + \
885 debianVersionPackaging + '.debian.tar.' + \
886 'xz' # FIXME: Check packageInfo['source_tarball_format'] with ".tar.gz" package!
887 return controlTarballFileName
888
889
890 # ###### Fetch Debian changelog file ########################################
891 def fetchDebianChangelogAndControl(packageInfo : dict[str,Any],
892 codename : str = 'unstable') -> tuple[list[str] | None, list[str] | None]:
893 if not hasPackagingFor(packageInfo, 'debian'):
894 sys.stderr.write('ERROR: Cannot find required Debian packaging information!\n')
895 sys.exit(1)
896
897 assert DebianCodenames is not None
898 if codename in DebianCodenames:
899 # Debian
900 statusPageURL : str = 'https://packages.debian.org/source/' + codename + '/' + packageInfo['debian_package_name']
901 else:
902 # Ubuntu
903 statusPageURL = 'https://packages.ubuntu.com/source/' + codename + '/' + packageInfo['debian_package_name']
904
905 debianNoSuchPackage : bool = False
906 debianVersion : str | None = None
907 debianLocation : str | None = None
908 debianArchive : str | None = None
909 debianArchiveFormat : str | None = None
910
911 # ====== Get package status =================================================
912 # NOTE: https://packages.debian.org is well-known for being quite unreliable:
913 # HTTP 503 "No healthy backends"; see also
914 # https://www.reddit.com/r/debian/comments/1e0foqv/is_packagesdebianorg_inaccessible/
915 # => Work-around: Retry with random waiting time:
916 maxTrials : Final[int] = 50
917 avgWaitingTime : Final[int] = 15
918
919 re_no_such_package : Final[re.Pattern[str]] = \
920 re.compile(r'^.*<p>No such package.</p>.*$')
921 re_debian_package : Final[re.Pattern[str]] = \
922 re.compile(r'^.*Source Package: ' + packageInfo['debian_package_name'] + r' \(([0-9-+~\.a-z]+)\)')
923 re_debian_archive : Final[re.Pattern[str]] = \
924 re.compile(r'^.*href="((http|https)://[a-zA-Z0-9\./+-]+/' + \
925 packageInfo['debian_package_name'][0:1] + '/' + \
926 packageInfo['debian_package_name'] + '/' + \
927 r')(' + packageInfo['debian_package_name'] + r'_[0-9-+~\.a-z]+\.debian\.tar\.[a-zA-Z]+)"')
928 httpHeders : Final[dict[str,str]] = {
929 'User-Agent': 'Build-Tool/0.2.0',
930 'Accept': '*/*'
931 }
932
933 for trial in range(0, maxTrials):
934 if trial > 0:
935 sys.stderr.write('\n')
936 sys.stderr.write('Looking for package status on ' + statusPageURL +
937 ' (trial ' + str(trial + 1) + '/' + str(maxTrials) + ') ... ')
938 sys.stderr.flush()
939
940 try:
941 statusPageRequest : urllib.request.Request = urllib.request.Request(statusPageURL,
942 headers = httpHeders)
943 statusPage : http.client.HTTPResponse = urllib.request.urlopen(statusPageRequest)
944
945 for statusPageLine in statusPage:
946 line = statusPageLine.decode('utf-8')
947
948 match = re_no_such_package.match(line)
949 if match is not None:
950 debianNoSuchPackage = True
951 else:
952 match = re_debian_package.match(line)
953 if match is not None:
954 debianVersion = match.group(1)
955 else:
956 match = re_debian_archive.match(line)
957 if match is not None:
958 debianLocation = match.group(1)
959 debianArchive = match.group(3)
960
961 statusPage.close()
962
963 # A status page has been downloaded successfully -> Done!
964 # NOTE: The status page may say "No such package", if there is no package.
965 # There is *no* HTTP 404 in this case!
966 break
967
968 except urllib.error.HTTPError as e:
969 sys.stderr.write('not found (HTTP ' + str(e.code) + ')')
970 if trial + 1 < maxTrials:
971 time.sleep(random.uniform(0, 2 * avgWaitingTime))
972
973 if debianNoSuchPackage == True:
974 sys.stderr.write('not in Debian!\n')
975 return (None, None)
976
977 if ( (debianVersion is None) or (debianLocation is None) or (debianArchive is None) ):
978 sys.stderr.write('ERROR: Unable to determinate package status in Debian (https://packages.ubuntu.com/ may be malfunctioning)!\n')
979 sys.exit(1)
980
981 sys.stderr.write('Version in ' + codename + ' is ' + debianVersion + '\n')
982
983
984 # ====== Determine necessary compression option =============================
985 debianArchiveFormat = debianArchive[len(debianArchive) - 2 : len(debianArchive)]
986 tarCompressionOption = TarOptions[debianArchiveFormat]
987
988
989 # ====== Fetch debian archive ===============================================
990 archiveFileURL : Final[str] = debianLocation + debianArchive
991 result : tuple[list[str] | None,list[str] | None] = (None, None)
992 sys.stderr.write('Looking for \"debian\" archive at ' + archiveFileURL + ' ... ')
993 sys.stderr.flush()
994 try:
995 archiveFileRequest : urllib.request.Request = urllib.request.Request(archiveFileURL,
996 headers = httpHeders)
997 archiveFile : http.client.HTTPResponse = urllib.request.urlopen(archiveFileRequest)
998 debianArchiveFile : tempfile._TemporaryFileWrapper[bytes] = \
999 tempfile.NamedTemporaryFile(delete = False)
1000
1001 shutil.copyfileobj(cast(TextIO, archiveFile), debianArchiveFile)
1002 debianArchiveFile.close()
1003 archiveFile.close()
1004 sys.stderr.write('found!\n')
1005
1006 debianChangelog : list[str] = [ ]
1007 debianControl : list[str] = [ ]
1008 try:
1009 # ------ Extract debian/changelog ----------------------------------
1010 process : subprocess.Popen[str] = \
1011 subprocess.Popen([ 'tar', 'x' + tarCompressionOption + 'fO', debianArchiveFile.name, 'debian/changelog'],
1012 stdout=subprocess.PIPE, universal_newlines=True)
1013 if ( (process is not None) and (process.stdout is not None) ):
1014 debianChangelog = process.stdout.readlines()
1015
1016 # ------ Extract debian/control ------------------------------------
1017 process = \
1018 subprocess.Popen([ 'tar', 'x' + tarCompressionOption + 'fO', debianArchiveFile.name, 'debian/control'],
1019 stdout=subprocess.PIPE, universal_newlines=True)
1020 if ( (process is not None) and (process.stdout is not None) ):
1021 debianControl = process.stdout.readlines()
1022
1023 os.unlink(debianArchiveFile.name)
1024 result = (debianChangelog, debianControl)
1025
1026 except Exception as e:
1027 sys.stderr.write('ERROR: Failed to extract debian/changelog from ' + debianArchiveFile.name + ': ' + str(e) + '\n')
1028 sys.exit(1)
1029
1030 except urllib.error.HTTPError as e:
1031 sys.stderr.write('not found (HTTP ' + str(e.code) + ')!\n')
1032
1033 return result
1034
1035
1036 # ###### Filter Debian changelog ############################################
1037 # Filter Debian changelog: obtain entries until ITP entry.
1038 def filterDebianChangelog(changeLogContents : list[str]) -> list[str]:
1039
1040 re_begin_of_entry : Final[re.Pattern[str]] = re.compile(r'^[a-zA-Z].*$')
1041 re_end_of_entry : Final[re.Pattern[str]] = re.compile(r'^ --.*$')
1042 re_empty : Final[re.Pattern[str]] = re.compile(r'^$')
1043 re_item : Final[re.Pattern[str]] = re.compile(r'^ *')
1044 re_item_is_itp : Final[re.Pattern[str]] = re.compile(r'^(.*Closes:.*ITP.*|.*ITP.*Closes:.*)$')
1045
1046 resultingChangelog : list[str] = [ ]
1047 entries : int = 0
1048 entryContentLines : int = 0
1049 entryContent : str = ''
1050 entryIsITP : bool = False
1051
1052 for line in changeLogContents:
1053
1054 # ====== Begin of entry ===============================================
1055 if entryContentLines == 0:
1056 if re_begin_of_entry.match(line):
1057 if entries == 0:
1058 entryContent = line
1059 else:
1060 entryContent = '\n' + line
1061 entryContentLines = 1
1062
1063 # ====== Within entry =================================================
1064 else:
1065 # ------ End of entry ----------------------------------------------
1066 if re_end_of_entry.match(line):
1067 entryContent = entryContent + line
1068 if entryContentLines > 1:
1069 entries = entries + 1
1070
1071 # ------ Print entry -----------------------------------------
1072 if not entryIsITP:
1073 resultingChangelog.append(entryContent)
1074
1075 # ------ Print entry with ITP --------------------------------
1076 # Special case: The ITP package for Debian must only contain the
1077 # ITP entry with ITP item and nothing else!
1078 else:
1079 splittedITPEntry = entryContent.splitlines()
1080 i = 0
1081 for itpLine in splittedITPEntry:
1082 i = i + 1
1083 if (i <= 2) or (i >= len(splittedITPEntry) - 2):
1084 resultingChangelog.append(itpLine + '\n')
1085 elif re_item_is_itp.match(itpLine) is not None:
1086 resultingChangelog.append(itpLine + '\n')
1087 break # ITP -> done!
1088
1089 entryContent = ''
1090 entryIsITP = False
1091
1092 entryContentLines = 0
1093
1094 # ------ Part of entry ---------------------------------------------
1095 else:
1096 if re_item.match(line):
1097 entryContent = entryContent + line
1098 entryContentLines = entryContentLines + 1
1099 if re_item_is_itp.match(line):
1100 entryIsITP = True
1101
1102 return resultingChangelog
1103
1104
1105 # ###### Merge Debian changelogs ###########################################
1106 # This function merges debian/changelog entries.
1107 # 1. Import old entries from distributor's changelog
1108 # 2a. Get all newer entries from PPA changelog
1109 # 2b. Merge newer entries into a single entry
1110 def mergeDebianChangelogs(ppaChangelogContents : list[str],
1111 distributorChangelogContents : list[str]) -> list[str]:
1112
1113 # ====== Merge changelogs ================================================
1114 re_entry_header : Final[re.Pattern[str]] = re.compile(r'^([a-zA-Z0-9-]+ \([0-9a-zA-Z\.~+]+-)')
1115 re_entry_footer : Final[re.Pattern[str]] = re.compile(r'^ -- .*')
1116 re_empty : Final[re.Pattern[str]] = re.compile(r'^\S*$')
1117
1118 topics : Final[list[dict[str,Any]]] = [
1119 { 'regexp': re.compile(r'^ \* .*ew upstream (version|release).*$'), 'count': 0, 'max': 1 },
1120 { 'regexp': re.compile(r'^ \* .*standards version.*$'), 'count': 0, 'max': 1 },
1121 { 'regexp': re.compile(r'^ \* .*debian/compat:.*$'), 'count': 0, 'max': 0 }
1122 ]
1123
1124 # ------ Get latest entry from distribution changelog --------------------
1125 latestDistributionEntry : str = distributorChangelogContents[0]
1126 match : re.Match[str] | None = re_entry_header.match(latestDistributionEntry)
1127 if match is None:
1128 sys.stderr.write('ERROR: Bad distributor changelog header!\n')
1129 sys.stderr.write('First distributor entry: "' + latestDistributionEntry.strip() + '"\n')
1130 sys.exit(1)
1131 latestDistributionEntry = match.group(1)
1132
1133 # ------ Join all new entries from PPA changelog -------------------------
1134 resultingChangelogContents : list[str] = [ ]
1135 entries : int = 0
1136 insideEntry : bool = False
1137 foundLatestDistributionEntryInPPA : bool = False
1138 firstFooter : str | None = None
1139
1140 for line in ppaChangelogContents:
1141
1142 # ------ Begin of an entry --------------------------------------------
1143 match = re_entry_header.match(line)
1144 if match is not None:
1145
1146 # ------ Done? -----------------------------------------------------
1147 if match.group(1) == latestDistributionEntry:
1148 foundLatestDistributionEntryInPPA = True
1149 break
1150
1151 # ------ Add this entry --------------------------------------------
1152 entries = entries + 1
1153 if entries == 1:
1154 resultingChangelogContents.append(line)
1155 resultingChangelogContents.append('\n')
1156
1157 continue
1158
1159 # ------ Empty line ---------------------------------------------------
1160 match = re_empty.match(line)
1161 if match is not None:
1162 continue
1163
1164 # ------ End of an entry ----------------------------------------------
1165 match = re_entry_footer.match(line)
1166 if match is not None:
1167 if entries == 1:
1168 firstFooter = line
1169 continue
1170
1171 # ------ Topics -------------------------------------------------------
1172 skip = False
1173 for topic in topics:
1174 match = topic['regexp'].match(line)
1175 if match is not None:
1176 topic['count'] = topic['count'] + 1
1177 if topic['count'] > topic['max']:
1178 skip = True
1179 break
1180 if skip == True:
1181 continue
1182
1183 # ------ Add line to output -------------------------------------------
1184 if line[0] == ' ':
1185 resultingChangelogContents.append(line)
1186 continue
1187
1188 # ------ Something is wrong -------------------------------------------
1189 sys.stderr.write('ERROR: Unexpected line: ' + line + '!\n')
1190 sys.exit(1)
1191
1192
1193 resultingChangelogContents.append('\n')
1194 if firstFooter is not None:
1195 resultingChangelogContents.append(firstFooter)
1196
1197 if foundLatestDistributionEntryInPPA == False:
1198 # Distributor changelog is equal to PPA changelog?
1199 if ppaChangelogContents[0] != latestDistributionEntry:
1200 sys.stderr.write('ERROR: Did not find the latest distribution entry in the PPA changelog!\n')
1201 sys.stderr.write('Latest distributor entry: "' + latestDistributionEntry.strip() + '"\n')
1202 sys.stderr.write('First PPA entry: "' + ppaChangelogContents[0].strip() + '"\n')
1203 sys.exit(1)
1204
1205 for line in distributorChangelogContents:
1206 resultingChangelogContents.append(line)
1207
1208 #for line in resultingChangelogContents:
1209 #sys.stdout.write(line)
1210
1211 return resultingChangelogContents
1212
1213
1214
1215 # ###### Make Debian source package #########################################
1216 def makeSourceDeb(packageInfo : dict[str,Any],
1217 codenames : list[str],
1218 skipPackageSigning : bool,
1219 summaryFile : TextIO | None) -> bool:
1220
1221 assert DebianCodenames is not None
1222
1223 # ====== Make sure that the source tarball is available ==================
1224 if makeSourceTarball(packageInfo, skipPackageSigning, summaryFile) == False:
1225 return False
1226 if len(codenames) == 0:
1227 codenames = [ packageInfo['debian_codename'] ]
1228
1229
1230 # ====== Build for each distribution codename ============================
1231 changesFiles : dict[str,str] = { }
1232 dscFiles : dict[str,str] = { }
1233 re_launchpad : Final[re.Pattern[str]] = re.compile(r'^.*\(LP: #[0-9]+')
1234 re_dhcompat : Final[re.Pattern[str]] = re.compile(r'^(Build-Depends:[ \t]*|[ \t]*)(debhelper-compat \(= [0-9]+\))(.*)$')
1235 re_parallel : Final[re.Pattern[str]] = re.compile(r' --parallel')
1236 re_vcs : Final[re.Pattern[str]] = re.compile(r'^(Vcs-[a-zA-Z]+)(:[ t]*)(.*)$')
1237
1238 printSection('Creating source Debian packages')
1239
1240 # Make sure to have the original packages with their Debian names:
1241 originalTarball : Final[str] = packageInfo['debian_package_name'] + '_' + \
1242 packageInfo['debian_version_string'] + '.orig.tar.' + \
1243 packageInfo['source_tarball_format']
1244 originalSignature : Final[str] = originalTarball + '.asc'
1245 try:
1246 os.link(packageInfo['source_tarball_name'], originalTarball)
1247 except FileExistsError:
1248 pass
1249 if skipPackageSigning == False:
1250 try:
1251 os.link(packageInfo['source_tarball_signature'], originalSignature)
1252 except FileExistsError:
1253 pass
1254
1255 defaultArchitecture : Final[str] = getDebianDefaultArchitecture()
1256 for codename in codenames:
1257 updatedDebhelperVersion : int = 0
1258
1259 printSubsection('Creating source Debian package for ' + codename)
1260
1261 # ====== Prepare work directory =======================================
1262 workdir : str = '/tmp/packaging-' + \
1263 codename + '-' + \
1264 packageInfo['debian_package_name'] + '-' + \
1265 packageInfo['debian_version_string'] + '-' + \
1266 packageInfo['debian_version_packaging']
1267 sys.stdout.write('Preparing work directory ' + workdir + ' ...\n')
1268
1269 shutil.rmtree(workdir, ignore_errors = True)
1270 os.makedirs(workdir, exist_ok = True)
1271
1272 # !!! Using *symlink* below! !!!
1273 # shutil.copyfile(originalTarball, workdir + '/' + originalTarball)
1274 # if skipPackageSigning == False:
1275 #shutil.copyfile(originalSignature, workdir + '/' + originalSignature)
1276 os.symlink(os.path.abspath(packageInfo['source_tarball_name']), workdir + '/' + originalTarball)
1277 if skipPackageSigning == False:
1278 os.symlink(os.path.abspath(packageInfo['source_tarball_signature']), workdir + '/' + originalSignature)
1279
1280
1281 # ====== Unpack the sources ===========================================
1282 compressionOption : str = TarOptions[packageInfo['source_tarball_format']]
1283 try:
1284 subprocess.run([ 'tar', 'x' + compressionOption + 'f', originalTarball ], cwd = workdir, check = True)
1285 except Exception as e:
1286 sys.stderr.write('ERROR: Unable to uncompress upstream source tarball ' + originalTarball + ': ' + str(e) + '\n')
1287 sys.exit(1)
1288
1289 upstreamSourceDir : str = workdir + '/' + packageInfo['debian_package_name'] + '-' + packageInfo['debian_version_string']
1290 if not os.path.isdir(upstreamSourceDir):
1291 # Sources not found in expected directory!
1292 sys.stderr.write('ERROR: Sources are not in the expected directory ' + upstreamSourceDir + '!\n')
1293 # Check for package-*/debian/.. as new path:
1294 found = glob.glob(workdir + '/' + packageInfo['debian_package_name'] + '-*/debian/..')
1295 if len(found) == 1:
1296 # Found -> set new upstream source path
1297 sys.stderr.write('WARNING: Sources are not in the expected directory ' + upstreamSourceDir)
1298 upstreamSourceDir = os.path.realpath(found[0])
1299 sys.stderr.write(' => using ' + upstreamSourceDir + '!\n')
1300 else:
1301 # Not found -> abort with error.
1302 sys.stderr.write('ERROR: Sources are not in the expected directory ' + upstreamSourceDir + '!\n')
1303 sys.exit(1)
1304
1305
1306 # ====== Adapt packaging ==============================================
1307 changeLogContents : list[str] = readTextFile(packageInfo['debian_changelog_name'])
1308 controlContents : list[str] = readTextFile(packageInfo['debian_control_name'])
1309 rulesContents : list[str] = readTextFile(packageInfo['debian_rules_name'])
1310 upstreamControlContents : list[str] | None = None
1311
1312 newDebianVersionPackaging : str = modifyDebianVersionPackaging(packageInfo, codename)
1313 sys.stdout.write('Modifying packaging version from ' + \
1314 packageInfo['debian_version_packaging'] + \
1315 ' to ' + newDebianVersionPackaging + '!\n')
1316
1317
1318 # ====== Update changelog =============================================
1319 changeLogContents[0] = \
1320 packageInfo['debian_package_name'] + \
1321 ' (' + packageInfo['debian_version_prefix'] + packageInfo['debian_version_string'] + '-' + newDebianVersionPackaging + ') ' + \
1322 codename + '; ' + \
1323 'urgency=' + packageInfo['debian_urgency'] + \
1324 '\n'
1325 sys.stdout.write('Updating changelog header: ' + changeLogContents[0])
1326
1327 # ------- Debian ------------------------------------------------------
1328 if codename in DebianCodenames:
1329 # Remove Launchpad entries:
1330 changeLogContents = \
1331 [ line for line in changeLogContents if not re_launchpad.match(line) ]
1332
1333 # ------ Fetch distributor's latest changelog and control file -----
1334 distributorChangelogContents, distributorControlContents = \
1335 fetchDebianChangelogAndControl(packageInfo, codename)
1336
1337 # ------ Update debian/changelog -----------------------------------
1338 if distributorChangelogContents is not None:
1339 # Merge new entries from changelog into a single entry, and append
1340 # the distributor's changelog with the rest:
1341 changeLogContents = \
1342 mergeDebianChangelogs(changeLogContents, distributorChangelogContents)
1343
1344 changeLogContents = filterDebianChangelog(changeLogContents)
1345
1346 # ------ Update debian/control -------------------------------------
1347 if distributorControlContents is not None:
1348 # Find Vcs-* defined by distributor:
1349 vcsGit : str | None = None
1350 vcsBrowser : str | None = None
1351 for line in distributorControlContents:
1352 match : re.Match[str] | None = re_vcs.match(line)
1353 if match:
1354 if match.group(1) == 'Vcs-Git':
1355 vcsGit = match.group(3)
1356 elif match.group(1) == 'Vcs-Browser':
1357 vcsBrowser = match.group(3)
1358
1359 # Replace Vcs-* with versions from distributor:
1360 if ( (vcsGit is not None) or (vcsBrowser is not None) ):
1361 for i in range(0, len(controlContents)):
1362 match = re_vcs.match(controlContents[i])
1363 if match:
1364 if vcsGit is not None:
1365 controlContents[i] = re.sub(r'^Vcs-Git:.*$', 'Vcs-Git: ' + vcsGit, controlContents[i])
1366 if vcsBrowser is not None:
1367 controlContents[i] = re.sub(r'^Vcs-Browser:.*$', 'Vcs-Browser: ' + vcsBrowser, controlContents[i])
1368 else:
1369 # No distributor Vcs-* fields -> remove them!
1370 controlContents = \
1371 [ line for line in controlContents if not re_vcs.match(line) ]
1372 else:
1373 controlContents = \
1374 [ line for line in controlContents if not re_vcs.match(line) ]
1375
1376 # ------- Ubuntu ------------------------------------------------------
1377 else:
1378 # ------ Translate Debian debhelper configuration to Ubuntu --------
1379 # Debian insists on the latest version of Debhelper,
1380 # Ubuntu in older versions does not provide the up-to-date Debhelper.
1381 # => Translate to older Debhelper versions, if necessary.
1382 if codename in DebhelperCompatFixes:
1383 dhcompatVersion : int = DebhelperCompatFixes[codename]
1384 for i in range(0, len(controlContents)):
1385 match = re_dhcompat.match(controlContents[i])
1386 if match:
1387 controlContents[i] = match.group(1) + \
1388 'debhelper (>= ' + str(dhcompatVersion) + ')' + \
1389 match.group(3) + '\n'
1390
1391 # Write debian/compat file:
1392 writeTextFile(upstreamSourceDir + '/debian/compat', [ str(dhcompatVersion) + '\n' ])
1393
1394 # Replace "${DEB_HOST_MULTIARCH}" -> "*" in *.install:
1395 installFiles : list[str] = glob.glob(upstreamSourceDir + '/debian/*.install')
1396 if len(installFiles) > 0:
1397 sedCommand = [ 'sed', '-e', 's#${DEB_HOST_MULTIARCH}#*#', '-i' ] + installFiles
1398 try:
1399 subprocess.run(sedCommand, check=True)
1400 except Exception as e:
1401 sys.stderr.write('ERROR: PBuilder run failed: ' + str(e) + '\n')
1402 sys.exit(1)
1403
1404 updatedDebhelperVersion = dhcompatVersion
1405 break
1406
1407
1408 # ====== Clean up empty lines =========================================
1409 writeTextFile(upstreamSourceDir + '/debian/changelog', changeLogContents)
1410 writeTextFile(upstreamSourceDir + '/debian/control', controlContents)
1411 writeTextFile(upstreamSourceDir + '/debian/rules', rulesContents)
1412
1413 # print(upstreamSourceDir + '/debian/changelog')
1414 # print(upstreamSourceDir + '/debian/control')
1415 # sys.exit(2)
1416
1417 sys.stdout.write('Updated Debian changelog:\n')
1418 showDiff(packageInfo['debian_changelog_name'], upstreamSourceDir + '/debian/changelog')
1419 sys.stdout.write('Updated Debian control:\n')
1420 showDiff(packageInfo['debian_control_name'], upstreamSourceDir + '/debian/control')
1421 sys.stdout.write('Updated Debian rules:\n')
1422 showDiff(packageInfo['debian_rules_name'], upstreamSourceDir + '/debian/rules')
1423
1424
1425 # ====== Build source Debian package ==================================
1426 if skipPackageSigning == False:
1427 # Build source package including signature:
1428 if packageInfo['packaging_maintainer_key'] is None:
1429 sys.stderr.write('ERROR: No MAINTAINER_KEY in ' + packageInfo['packaging_config_name'] + '\n')
1430 sys.exit(1)
1431 debuild = [ 'debuild', '--no-check-builddeps', '-sa', '-S', '-k' + packageInfo['packaging_maintainer_key'], '-i' ]
1432 else:
1433 # Build source package without signature:
1434 debuild = [ 'debuild', '--no-check-builddeps', '-us', '-uc', '-S', '-i' ]
1435 if updatedDebhelperVersion != 0:
1436 debuild.append('--no-check-builddeps')
1437 try:
1438 subprocess.run(debuild, cwd = upstreamSourceDir, check = True)
1439 except Exception as e:
1440 sys.stderr.write('ERROR: Debuild run failed: ' + str(e) + '\n')
1441 sys.exit(1)
1442
1443
1444 # ====== Check results ================================================
1445 sys.stdout.write('Checking results:\n')
1446 dscFileName : str = getDebianDscName(packageInfo, newDebianVersionPackaging)
1447 buildinfoName : str = getDebianBuildinfoName(packageInfo, newDebianVersionPackaging)
1448 changesName : str = getDebianChangesName(packageInfo, newDebianVersionPackaging)
1449 controlTarballName : str = getDebianControlTarballName(packageInfo, newDebianVersionPackaging)
1450 if os.path.isfile(workdir + '/' + dscFileName):
1451 sys.stdout.write('* DSC file is ' + dscFileName + '.\n')
1452 dscFiles[codename] = dscFileName
1453 else:
1454 sys.stderr.write('ERROR: DSC file not found at expected location ' + workdir + '/' + dscFileName + '!\n')
1455 sys.exit(1)
1456 changesFiles[codename] = changesName
1457
1458 if os.path.isfile(workdir + '/' + buildinfoName):
1459 sys.stdout.write('* Buildinfo file is ' + buildinfoName + '.\n')
1460 else:
1461 sys.stderr.write('ERROR: Buildinfo file not found at expected location ' + workdir + '/' + buildinfoName + '!\n')
1462 sys.exit(1)
1463 if os.path.isfile(workdir + '/' + changesName):
1464 sys.stdout.write('* Changes file is ' + changesName + '.\n')
1465 else:
1466 sys.stderr.write('ERROR: Source changes file not found at expected location ' + workdir + '/' + changesName + '!\n')
1467 sys.exit(1)
1468 if os.path.isfile(workdir + '/' + controlTarballName):
1469 sys.stdout.write('* Control tarball file is ' + controlTarballName + '.\n')
1470 else:
1471 sys.stderr.write('ERROR: Control tarball file not found at expected location ' + workdir + '/' + controlTarballName + '!\n')
1472 sys.exit(1)
1473
1474 # Copy results to main directory.
1475 # NOTE: The original tarball and signature are already there (symlinked)!
1476 for fileName in [ dscFileName, buildinfoName, changesName, controlTarballName ] :
1477 shutil.copyfile(workdir + '/' + fileName, fileName)
1478
1479 # ====== Add files to summary =========================================
1480 if summaryFile is not None:
1481 summaryFile.write('debSourceDscFile: ' + workdir + '/' + dscFileName + ' ' + codename + '\n')
1482 summaryFile.write('debSourceBuildinfoFile: ' + workdir + '/' + buildinfoName + ' ' + codename + '\n')
1483 summaryFile.write('debSourceChangesFile: ' + workdir + '/' + changesName + ' ' + codename + '\n')
1484 summaryFile.write('debSourceControlTarballFile: ' + workdir + '/' + controlTarballName + ' ' + codename + '\n')
1485
1486 # ====== Print overview ==================================================
1487 printSection('Debian source package overview')
1488
1489 sys.stdout.write('\x1b[34mUpload to PPA:\x1b[0m\n')
1490 for codename in sorted(changesFiles.keys()):
1491 if codename in DebianCodenames:
1492 ppa = 'mentors'
1493 else:
1494 ppa = 'ppa'
1495 sys.stdout.write('\x1b[34m dput ' + ppa + ' ' + changesFiles[codename] + '\x1b[0m\n')
1496 sys.stdout.write('\n')
1497
1498 sys.stdout.write('\x1b[34mBuild Test Commands:\x1b[0m\n')
1499 for codename in sorted(dscFiles.keys()):
1500
1501 buildArchitecture = getDebianDefaultArchitecture()
1502 buildDistribution = codename
1503 if codename in DebianCodenames:
1504 buildSystem = 'debian'
1505 lintianProfile = 'debian'
1506 else:
1507 buildSystem = 'ubuntu'
1508 lintianProfile = 'ubuntu'
1509 basetgz = '/var/cache/pbuilder/' + buildSystem + '-' + codename + '-' + buildArchitecture + '-base.tgz'
1510
1511 sys.stdout.write('\x1b[34m ' + \
1512 'sudo pbuilder build --basetgz ' + basetgz + ' ' + \
1513 dscFiles[codename] + ' && ' + \
1514 'lintian -iIEv --profile ' + lintianProfile + ' --pedantic ' + \
1515 '/var/cache/pbuilder/result/*/' + changesFiles[codename] + \
1516 '\x1b[0m\n')
1517 sys.stdout.write('\n')
1518
1519 return True
1520
1521
1522 # ###### Build Debian binary package ########################################
1523 def buildDeb(packageInfo : dict[str,Any],
1524 codenames : list[str],
1525 architectures : list[str],
1526 skipPackageSigning : bool,
1527 summaryFile : TextIO | None,
1528 twice : bool) -> bool:
1529
1530 assert DebianCodenames is not None
1531
1532 # ====== Build for each distribution codename ============================
1533 printSection('Creating binary Debian packages')
1534
1535 if len(codenames) == 0:
1536 codenames = [ packageInfo['debian_codename'] ]
1537 if len(architectures) == 0:
1538 architectures = [ getDebianDefaultArchitecture() ]
1539 for codename in codenames:
1540
1541 # ====== Make sure that the source Debian files are available ============
1542 makeSourceDeb(packageInfo, [ codename ], skipPackageSigning, summaryFile)
1543
1544 for buildArchitecture in architectures:
1545 newDebianVersionPackaging = modifyDebianVersionPackaging(packageInfo, codename)
1546
1547 printSubsection('Creating binary Debian package for ' + codename + '/' + buildArchitecture)
1548
1549 dscFileName = getDebianDscName(packageInfo, newDebianVersionPackaging)
1550 if not os.path.isfile(dscFileName):
1551 sys.stderr.write('ERROR: DSC file ' + dscFileName + ' does not exist!\n')
1552 sys.exit(1)
1553
1554 buildDistribution : str = codename
1555 if codename in DebianCodenames:
1556 buildSystem : str = 'debian'
1557 lintianProfile : str = 'debian'
1558 else:
1559 buildSystem = 'ubuntu'
1560 lintianProfile = 'ubuntu'
1561 basetgz : str = '/var/cache/pbuilder/' + buildSystem + '-' + codename + '-' + buildArchitecture + '-base.tgz'
1562 if not os.path.isfile(basetgz):
1563 sys.stderr.write('ERROR: Base tgz ' + basetgz + ' for pbuilder is not available!\nCheck pbuilder installation and configuration!\n')
1564 sys.exit(1)
1565 buildlog : str = 'build-' + buildSystem + '-' + codename + '-' + buildArchitecture + '.log'
1566
1567 # ====== Run pbuilder ==============================================
1568 pbuilderCommand : list[str] = [ 'sudo',
1569 'OS=' + buildSystem,
1570 'ARCH=' + buildArchitecture,
1571 'DIST=' + codename,
1572 'pbuilder',
1573 'build',
1574 '--basetgz', basetgz,
1575 '--logfile', buildlog ]
1576 if twice:
1577 pbuilderCommand.append('--twice')
1578 pbuilderCommand.append(dscFileName)
1579 print(pbuilderCommand)
1580 try:
1581 subprocess.run(pbuilderCommand, check=True)
1582 except Exception as e:
1583 sys.stderr.write('ERROR: PBuilder run failed: ' + str(e) + '\n')
1584 sys.exit(1)
1585
1586 # ====== Check for changes file ====================================
1587 changesFileName : str = getDebianChangesName(packageInfo,
1588 newDebianVersionPackaging,
1589 buildArchitecture)
1590 changesFileGlobs : list[str] = [
1591 '/var/cache/pbuilder/result/' + buildSystem + '-' + codename + '-' + buildArchitecture + '/' + changesFileName,
1592 '/var/cache/pbuilder/result/' + changesFileName,
1593 '/var/cache/pbuilder/result/*/' + changesFileName
1594 ]
1595 for changesFileGlob in changesFileGlobs:
1596 foundChangesFiles : list[str] = glob.glob(changesFileGlob)
1597 if len(foundChangesFiles) != 0:
1598 break
1599 if len(foundChangesFiles) < 1:
1600 sys.stderr.write('ERROR: Unable to locate the changes file!\n')
1601 sys.stderr.write('Search locations for changes file: ' + str(changesFileGlobs) + '!')
1602 sys.exit(1)
1603 elif len(foundChangesFiles) > 1:
1604 sys.stderr.write('ERROR: Multiple changes files have been found! PBuilder configuration problem?\n')
1605 sys.stderr.write('Found changes files: ' + str(foundChangesFiles) + '\n')
1606 sys.exit(1)
1607
1608 # ====== Run BLHC ==================================================
1609 # FIXME: BLHC < 0.14 does not properly handle D_FORTIFY_SOURCE=3!
1610 if shutil.which('blhc') is not None:
1611 blhcCommand : str = 'blhc ' + buildlog + ' | grep -v "^CPPFLAGS missing (-D_FORTIFY_SOURCE=2).*-D_FORTIFY_SOURCE=3.*" | grep -v "^NONVERBOSE BUILD:"'
1612 printSubsection('Running BLHC')
1613 print('=> ' + blhcCommand)
1614 try:
1615 subprocess.run(blhcCommand, check=False, shell=True)
1616 except Exception as e:
1617 sys.stderr.write('ERROR: BLHC run failed: ' + str(e) + '\n')
1618 sys.exit(1)
1619 else:
1620 sys.stderr.write('NOTE: BLHC is not installed -> checks skipped!\n')
1621
1622 # ====== Run Lintian ===============================================
1623 if shutil.which('lintian') is not None:
1624 lintianCommand : str = 'lintian -v -i -I -E --pedantic' + \
1625 ' --profile ' + lintianProfile + \
1626 ' --suppress-tags malformed-deb-archive,bad-distribution-in-changes-file' + \
1627 ' ' + foundChangesFiles[0]
1628 printSubsection('Running Lintian')
1629 print('=> ' + lintianCommand)
1630 try:
1631 subprocess.run(lintianCommand, check=False, shell=True)
1632 except Exception as e:
1633 sys.stderr.write('ERROR: Lintian run failed: ' + str(e) + '\n')
1634 sys.exit(1)
1635 else:
1636 sys.stderr.write('NOTE: Lintian is not installed -> checks skipped!\n')
1637
1638 # ====== Run LRC ===================================================
1639 if shutil.which('lrc') is not None:
1640 lrcCommand : str = 'lrc -t'
1641 printSubsection('Running LRC')
1642 print('=> ' + lrcCommand)
1643 try:
1644 subprocess.run(lrcCommand, check=False, shell=True)
1645 except Exception as e:
1646 sys.stderr.write('ERROR: LRC run failed: ' + str(e) + '\n')
1647 sys.exit(1)
1648 else:
1649 sys.stderr.write('NOTE: LRC is not installed -> checks skipped!\n')
1650
1651 # ====== Add Changes file to summary ===============================
1652 if summaryFile is not None:
1653 summaryFile.write('debBuildChangesFile: ' + foundChangesFiles[0] + ' ' + codename + ' ' + buildArchitecture + '\n')
1654
1655 return True
1656
1657
1658 # ###### Make SRPM source package ###########################################
1659 def makeSourceRPM(packageInfo : dict[str,Any],
1660 skipPackageSigning : bool,
1661 summaryFile : TextIO | None) -> bool:
1662
1663 # ====== Make sure that the source tarball is available ==================
1664 if makeSourceTarball(packageInfo, skipPackageSigning, summaryFile) == False:
1665 return False
1666
1667 printSection('Creating SRPM source packages')
1668
1669 # ====== Initialise RPM build directories ================================
1670 homeDir : Final[str | None] = os.environ.get('HOME')
1671 assert homeDir is not None
1672 rpmbuildDir : Final[str] = os.path.join(homeDir, 'rpmbuild')
1673 for subdir in [ 'BUILD', 'BUILDROOT', 'RPMS', 'SOURCES', 'SPECS', 'SRPMS' ]:
1674 os.makedirs(rpmbuildDir + '/' + subdir, exist_ok = True)
1675
1676 # ====== Copy source tarball =============================================
1677 if skipPackageSigning == False:
1678 result = os.system('gpg --verify ' + \
1679 packageInfo['source_tarball_signature'] + ' ' + \
1680 packageInfo['source_tarball_name'])
1681 if result == 0:
1682 sys.stderr.write('Signature verified.\n')
1683 else:
1684 sys.stderr.write('ERROR: Bad signature! Something is wrong!\n')
1685 return False
1686
1687 try:
1688 os.unlink(rpmbuildDir + '/SOURCES/' + packageInfo['source_tarball_name'])
1689 except FileNotFoundError:
1690 pass
1691 shutil.copyfile(os.path.abspath(packageInfo['source_tarball_name']),
1692 rpmbuildDir + '/SOURCES/' + packageInfo['source_tarball_name'])
1693
1694 rpmSpecNames : Final[list[str]] = glob.glob('rpm/*.spec')
1695 if len(rpmSpecNames) == 1:
1696 packageInfo['rpm_spec_name'] = rpmSpecNames[0]
1697 shutil.copyfile(packageInfo['rpm_spec_name'],
1698 rpmbuildDir + '/SPECS/' + packageInfo['rpm_package_name'] + '.spec')
1699 elif len(rpmSpecNames) > 1:
1700 sys.stderr.write('ERROR: More than one spec file found: ' + str(rpmSpecNames) + '!\n')
1701 sys.exit(1)
1702 else:
1703 sys.stderr.write('ERROR: No spec file found!\n')
1704 sys.exit(1)
1705
1706 # ====== Create SRPM =====================================================
1707 rpmbuild : Final[list[str]] = [ 'rpmbuild', '-bs', packageInfo['rpm_spec_name'] ]
1708 print(rpmbuild)
1709 try:
1710 subprocess.run(rpmbuild, check = True)
1711 except Exception as e:
1712 sys.stderr.write('ERROR: RPMBuild run failed: ' + str(e) + '\n')
1713 sys.exit(1)
1714
1715 srpmFile = rpmbuildDir + '/SRPMS/' + \
1716 packageInfo['rpm_package_name'] + '-' + \
1717 packageInfo['rpm_version_string'] + '-' + str(packageInfo['rpm_version_packaging']) + \
1718 '.src.rpm'
1719 if not os.path.isfile(srpmFile):
1720 sys.stderr.write('ERROR: SRPM ' + srpmFile + ' not found!\n')
1721 sys.exit(1)
1722
1723 # ====== Sign SRPM =======================================================
1724 if skipPackageSigning == False:
1725 rpmsign = [ 'rpmsign',
1726 '--define', '_gpg_name ' + packageInfo['packaging_maintainer_key'],
1727 '--addsign', srpmFile ]
1728 print(rpmsign)
1729 try:
1730 subprocess.run(rpmsign, check = True)
1731 except Exception as e:
1732 sys.stderr.write('ERROR: RPMSign run failed: ' + str(e) + '\n')
1733 sys.exit(1)
1734
1735 # ====== Run RPM Lint ====================================================
1736 if shutil.which('rpmlint') is not None:
1737 rpmlintCommand = 'rpmlint -P ' + srpmFile
1738 printSubsection('Running RPM Lint')
1739 print('=> ' + rpmlintCommand)
1740 try:
1741 subprocess.run(rpmlintCommand, check=False, shell=True)
1742 except Exception as e:
1743 sys.stderr.write('ERROR: RPM Lint run failed: ' + str(e) + '\n')
1744 sys.exit(1)
1745 else:
1746 sys.stderr.write('NOTE: RPM Lint is not installed -> checks skipped!\n')
1747
1748 # ====== Add SRPM file to summary ========================================
1749 if summaryFile is not None:
1750 summaryFile.write('rpmSourceFile: ' + srpmFile + '\n')
1751
1752 return True
1753
1754
1755 # ###### Build RPM binary package ###########################################
1756 def buildRPM(packageInfo : dict[str,Any],
1757 releases : list[str],
1758 architectures : list[str],
1759 skipPackageSigning : bool,
1760 summaryFile : TextIO | None) -> bool:
1761
1762 # ====== Make sure that the source Debian files are available ============
1763 if len(releases) == 0:
1764 if distro.id() == 'fedora':
1765 releases = [ 'fedora-' + distro.major_version() ]
1766 else:
1767 releases = [ 'rawhide' ]
1768 if len(architectures) == 0:
1769 architectures = [ getArchitecture() ]
1770 makeSourceRPM(packageInfo, skipPackageSigning, summaryFile)
1771
1772 # ====== Build for each distribution codename ============================
1773 printSection('Creating binary RPM packages')
1774
1775 # ====== Check SRPM ======================================================
1776 homeDir : Final[str | None] = os.environ.get('HOME')
1777 assert homeDir is not None
1778 rpmbuildDir : Final[str] = os.path.join(homeDir, 'rpmbuild')
1779 srpmFile = rpmbuildDir + '/SRPMS/' + \
1780 packageInfo['rpm_package_name'] + '-' + \
1781 packageInfo['rpm_version_string'] + '-' + str(packageInfo['rpm_version_packaging']) + \
1782 '.src.rpm'
1783 if not os.path.isfile(srpmFile):
1784 sys.stderr.write('ERROR: SRPM ' + srpmFile + ' not found!\n')
1785 sys.exit(1)
1786
1787 if skipPackageSigning == False:
1788 rpm = [ 'rpm',
1789 '--define', '_gpg_name ' + packageInfo['packaging_maintainer_key'],
1790 '--checksig', srpmFile ]
1791 print(rpm)
1792 try:
1793 subprocess.run(rpm, check = True)
1794 except Exception as e:
1795 sys.stderr.write('ERROR: RPMSign run failed: ' + str(e) + '\n')
1796 sys.exit(1)
1797
1798 # ====== Build for each release ==========================================
1799 for buildArchitecture in architectures:
1800 for release in releases:
1801
1802 printSubsection('Creating binary RPM package(s) for ' + release + '/' + buildArchitecture)
1803
1804 # ====== Check for mock configuration file =========================
1805 configuration = release + '-' + buildArchitecture
1806 if not os.path.isfile('/etc/mock/' + configuration + '.cfg'):
1807 sys.stderr.write('ERROR: Configuration ' + '/etc/mock/' + configuration + '.cfg does not exist!\n')
1808 sys.exit(1)
1809
1810 # ====== Delete old RPMs ===========================================
1811 for rpmFilePrefix in packageInfo['rpm_packages']:
1812 for architecture in [ 'noarch', buildArchitecture ]:
1813 rpmFile = '/var/lib/mock/' + configuration + '/result/' + \
1814 rpmFilePrefix + '.' + \
1815 architecture + '.rpm'
1816 try:
1817 os.unlink(rpmFile)
1818 except FileNotFoundError:
1819 pass
1820
1821 # ====== Run mock ==================================================
1822 try:
1823 # NOTE: using old chroot instead of container, to allow running
1824 # mock inside a container!
1825 commands : list[list[str]] = [
1826 [ 'mock', '-r', configuration, '--isolation=auto', '--init' ],
1827 [ 'mock', '-r', configuration, '--isolation=auto', '--installdeps', srpmFile ],
1828 [ 'mock', '-r', configuration, '--isolation=auto', '--rebuild', '--no-clean', srpmFile ]
1829 ]
1830 for command in commands:
1831 print(command)
1832 subprocess.run(command, check = True)
1833 except Exception as e:
1834 sys.stderr.write('ERROR: Mock run failed: ' + str(e) + '\n')
1835 sys.exit(1)
1836
1837 # ------ Check resulting RPM =======================================
1838 for rpmFilePrefix in packageInfo['rpm_packages']:
1839 rpmArchitecture : str | None = None
1840 found : bool = False
1841 for architecture in [ 'noarch', buildArchitecture ]:
1842 rpmFile = \
1843 '/var/lib/mock/' + configuration + '/result/' + \
1844 rpmFilePrefix + '.' + \
1845 architecture + '.rpm'
1846 if os.path.isfile(rpmFile):
1847 rpmArchitecture = architecture
1848 found = True
1849 break
1850 if not found:
1851 sys.stderr.write('ERROR: RPM ' + rpmFile + ' not found!\n')
1852 sys.exit(1)
1853
1854 # ====== Sign SRPM ==============================================
1855 if skipPackageSigning == False:
1856 rpmsign : list[str] = \
1857 [ 'rpmsign',
1858 '--define', '_gpg_name ' + packageInfo['packaging_maintainer_key'],
1859 '--addsign', rpmFile ]
1860 print(rpmsign)
1861 try:
1862 subprocess.run(rpmsign, check = True)
1863 except Exception as e:
1864 sys.stderr.write('ERROR: RPMSign run failed: ' + str(e) + '\n')
1865 sys.exit(1)
1866
1867 # ====== Run RPM Lint ===========================================
1868 if shutil.which('rpmlint') is not None:
1869 rpmlintCommand = 'rpmlint -P ' + rpmFile
1870 printSubsection('Running RPM Lint')
1871 print('=> ' + rpmlintCommand)
1872 try:
1873 subprocess.run(rpmlintCommand, check=False, shell=True)
1874 except Exception as e:
1875 sys.stderr.write('ERROR: RPM Lint run failed: ' + str(e) + '\n')
1876 sys.exit(1)
1877 else:
1878 sys.stderr.write('NOTE: RPM Lint is not installed -> checks skipped!\n')
1879
1880 # ====== Add RPM file to summary ================================
1881 if summaryFile is not None:
1882 summaryFile.write('rpmFile: ' + rpmFile + ' ' + release + ' ' + rpmArchitecture + '\n')
1883
1884 return True
1885
1886
1887
1888 # ###########################################################################
1889 # #### Main Program ####
1890 # ###########################################################################
1891
1892 # ====== Check arguments ====================================================
1893 if len(sys.argv) < 2:
1894 sys.stderr.write('Usage: ' + sys.argv[0] + ' tool [options ...]\n')
1895 sys.stderr.write('\n* ' + sys.argv[0] + ' info\n')
1896 sys.stderr.write('\n* ' + sys.argv[0] + ' make-source-tarball [--skip-signing]\n')
1897 sys.stderr.write('\n* ' + sys.argv[0] + ' make-source-deb [--summary=file] [codename ...] [--skip-signing]\n')
1898 sys.stderr.write(' ' + sys.argv[0] + ' build-deb [--summary=file] [codename ...] [--skip-signing] [--architecture=arch[,...]] [--twice]\n')
1899 sys.stderr.write(' ' + sys.argv[0] + ' fetch-debian-changelog [codename]\n')
1900 sys.stderr.write(' ' + sys.argv[0] + ' fetch-debian-control [codename]\n')
1901 sys.stderr.write('\n* ' + sys.argv[0] + ' make-source-rpm [--summary=file] [release ...] [--skip-signing]\n')
1902 sys.stderr.write(' ' + sys.argv[0] + ' build-rpm [--summary=file] [release ...] [--skip-signing] [--architecture=[,...]]\n')
1903 sys.exit(1)
1904
1905
1906 packageInfo : dict[str,Any] = readPackagingInformation()
1907 tool : Final[str] = sys.argv[1]
1908 summaryFile : TextIO | None = None
1909 skipPackageSigning : bool = False
1910 codenames : list[str] = [ ]
1911 releases : list[str] = [ ]
1912 architectures : list[str] = [ ]
1913
1914 # ====== Print information ==================================================
1915 if tool == 'info':
1916 showInformation(packageInfo)
1917
1918 # ====== Make source tarball ================================================
1919 elif tool == 'make-source-tarball':
1920 for i in range(2, len(sys.argv)):
1921 if sys.argv[i] == '--skip-signing':
1922 skipPackageSigning = True
1923 elif sys.argv[i][0:10] == '--summary=':
1924 summaryFileName = sys.argv[i][10:]
1925 try:
1926 summaryFile = open(summaryFileName, 'w', encoding='utf-8')
1927 except:
1928 sys.stderr.write('ERROR: Unable to create summary file ' + summaryFileName + '!\n')
1929 sys.exit(1)
1930 else:
1931 sys.stderr.write('ERROR: Bad make-source-tarball parameter ' + sys.argv[i] + '!\n')
1932 sys.exit(1)
1933 if makeSourceTarball(packageInfo, skipPackageSigning, summaryFile) == False:
1934 sys.exit(1)
1935
1936 # ====== Make source deb file ===============================================
1937 elif tool == 'make-source-deb':
1938 obtainDistributionCodenames()
1939 for i in range(2, len(sys.argv)):
1940 if sys.argv[i][0] != '-':
1941 codenames.append(sys.argv[i])
1942 elif sys.argv[i] == '--skip-signing':
1943 skipPackageSigning = True
1944 elif sys.argv[i][0:10] == '--summary=':
1945 summaryFileName = sys.argv[i][10:]
1946 try:
1947 summaryFile = open(summaryFileName, 'w', encoding='utf-8')
1948 except:
1949 sys.stderr.write('ERROR: Unable to create summary file ' + summaryFileName + '!\n')
1950 sys.exit(1)
1951 else:
1952 sys.stderr.write('ERROR: Bad make-source-debparameter ' + sys.argv[i] + '!\n')
1953 sys.exit(1)
1954 makeSourceDeb(packageInfo, codenames, skipPackageSigning, summaryFile)
1955
1956 # ====== Build deb file =====================================================
1957 elif tool == 'build-deb':
1958 obtainDistributionCodenames()
1959 twice : bool = False
1960 for i in range(2, len(sys.argv)):
1961 if sys.argv[i][0] != '-':
1962 codenames.append(sys.argv[i])
1963 elif sys.argv[i] == '--skip-signing':
1964 skipPackageSigning = True
1965 elif sys.argv[i][0:10] == '--summary=':
1966 summaryFileName = sys.argv[i][10:]
1967 try:
1968 summaryFile = open(summaryFileName, 'w', encoding='utf-8')
1969 except:
1970 sys.stderr.write('ERROR: Unable to create summary file ' + summaryFileName + '!\n')
1971 sys.exit(1)
1972 elif sys.argv[i][0:15] == '--architecture=':
1973 for architecture in sys.argv[i][15:].split(','):
1974 architectures.append(architecture)
1975 elif sys.argv[i] == '--twice':
1976 twice = True
1977 else:
1978 sys.stderr.write('ERROR: Bad build-deb parameter ' + sys.argv[i] + '!\n')
1979 sys.exit(1)
1980 buildDeb(packageInfo, codenames, architectures, skipPackageSigning, summaryFile, twice)
1981
1982 # ====== Make source deb file ===============================================
1983 elif tool == 'make-source-rpm':
1984 for i in range(2, len(sys.argv)):
1985 if sys.argv[i] == '--skip-signing':
1986 skipPackageSigning = True
1987 elif sys.argv[i][0:10] == '--summary=':
1988 summaryFileName = sys.argv[i][10:]
1989 try:
1990 summaryFile = open(summaryFileName, 'w', encoding='utf-8')
1991 except:
1992 sys.stderr.write('ERROR: Unable to create summary file ' + summaryFileName + '!\n')
1993 sys.exit(1)
1994 else:
1995 sys.stderr.write('ERROR: Bad make-source-rpm parameter ' + sys.argv[i] + '!\n')
1996 sys.exit(1)
1997 makeSourceRPM(packageInfo, skipPackageSigning, summaryFile)
1998
1999 # ====== Build deb file =====================================================
2000 elif tool == 'build-rpm':
2001 for i in range(2, len(sys.argv)):
2002 if sys.argv[i][0] != '-':
2003 releases.append(sys.argv[i])
2004 elif sys.argv[i] == '--skip-signing':
2005 skipPackageSigning = True
2006 elif sys.argv[i][0:10] == '--summary=':
2007 summaryFileName = sys.argv[i][10:]
2008 try:
2009 summaryFile = open(summaryFileName, 'w', encoding='utf-8')
2010 except:
2011 sys.stderr.write('ERROR: Unable to create summary file ' + summaryFileName + '!\n')
2012 sys.exit(1)
2013 elif sys.argv[i][0:15] == '--architecture=':
2014 for architecture in sys.argv[i][15:].split(','):
2015 architectures.append(architecture)
2016 else:
2017 sys.stderr.write('ERROR: Bad build-rpm parameter ' + sys.argv[i] + '!\n')
2018 sys.exit(1)
2019 buildRPM(packageInfo, releases, architectures, skipPackageSigning, summaryFile)
2020
2021 # ====== Fetch Debian changelog file ========================================
2022 elif tool == 'fetch-debian-changelog':
2023 obtainDistributionCodenames()
2024 codename : str = 'unstable'
2025 if len(sys.argv) >= 3:
2026 codename = sys.argv[2]
2027 changelogContents, controlContents = \
2028 fetchDebianChangelogAndControl(packageInfo, codename)
2029 if changelogContents is not None:
2030 sys.stdout.write('\n')
2031 for line in changelogContents:
2032 sys.stdout.write(line)
2033
2034 # ====== Fetch Debian control file ==========================================
2035 elif tool == 'fetch-debian-control':
2036 obtainDistributionCodenames()
2037 codename = 'unstable'
2038 if len(sys.argv) >= 3:
2039 codename = sys.argv[2]
2040 changelogContents, controlContents = \
2041 fetchDebianChangelogAndControl(packageInfo, codename)
2042 if controlContents is not None:
2043 sys.stdout.write('\n')
2044 for line in controlContents:
2045 sys.stdout.write(line)
2046
2047 # ====== Invalid tool =======================================================
2048 else:
2049 sys.stderr.write('ERROR: Invalid tool "' + tool + '"\n')
2050 sys.exit(1)