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