Coverage for daklib/utils.py: 62%

774 statements  

« prev     ^ index     » next       coverage.py v7.6.0, created at 2026-11-21 08:51 +0000

1# vim:set et ts=4 sw=4: 

2 

3"""Utility functions 

4 

5@contact: Debian FTP Master <ftpmaster@debian.org> 

6@copyright: 2000, 2001, 2002, 2003, 2004, 2005, 2006 James Troup <james@nocrew.org> 

7@license: GNU General Public License version 2 or later 

8""" 

9 

10# This program is free software; you can redistribute it and/or modify 

11# it under the terms of the GNU General Public License as published by 

12# the Free Software Foundation; either version 2 of the License, or 

13# (at your option) any later version. 

14 

15# This program is distributed in the hope that it will be useful, 

16# but WITHOUT ANY WARRANTY; without even the implied warranty of 

17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

18# GNU General Public License for more details. 

19 

20# You should have received a copy of the GNU General Public License 

21# along with this program; if not, write to the Free Software 

22# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 

23 

24import datetime 

25import email.message 

26import email.policy 

27import email.utils 

28import errno 

29import functools 

30import grp 

31import os 

32import pwd 

33import re 

34import shutil 

35import subprocess 

36import sys 

37import tempfile 

38from collections import defaultdict 

39from collections.abc import Collection, Iterable, Mapping, Sequence 

40from pathlib import Path 

41from typing import TYPE_CHECKING, Any, Literal, NoReturn, override 

42 

43import apt_inst 

44import apt_pkg 

45from sqlalchemy import select, sql 

46 

47import daklib.mail 

48from daklib import config 

49from daklib.dbconn import ( 

50 Component, 

51 DBConn, 

52 MetadataProxy, 

53 Override, 

54 OverrideType, 

55 get_active_keyring_paths, 

56 get_architecture, 

57 get_component, 

58 get_or_set_metadatakey, 

59 get_suite, 

60 get_suite_architectures, 

61) 

62 

63from .dak_exceptions import ( 

64 InvalidDscError, 

65 NoFilesFieldError, 

66 NoFreeFilenameError, 

67 ParseChangesError, 

68 SendmailFailedError, 

69 UnknownFormatError, 

70) 

71from .formats import parse_format, validate_changes_format 

72from .gpg import SignedFile 

73from .regexes import ( 

74 re_build_dep_arch, 

75 re_issource, 

76 re_multi_line_field, 

77 re_parse_maintainer, 

78 re_re_mark, 

79 re_single_line_field, 

80 re_srchasver, 

81 re_whitespace_comment, 

82) 

83from .srcformats import get_format_from_string 

84from .textutils import fix_maintainer 

85 

86if TYPE_CHECKING: 

87 from sqlalchemy.orm import Session 

88 

89 import daklib.daklog 

90 import daklib.fstransactions 

91 import daklib.upload 

92 

93type StrPath = str | os.PathLike[str] 

94 

95 

96################################################################################ 

97 

98key_uid_email_cache: dict[str, list[str]] = ( 

99 {} 

100) #: Cache for email addresses from gpg key uids 

101 

102################################################################################ 

103 

104 

105def input_or_exit(prompt: str | None = None) -> str: 

106 try: 

107 return input(prompt) 

108 except EOFError: 

109 sys.exit("\nUser interrupt (^D).") 

110 

111 

112################################################################################ 

113 

114 

115def extract_component_from_section(section: str) -> tuple[str, str]: 

116 """split "section" into "section", "component" parts 

117 

118 If "component" is not given, "main" is used instead. 

119 

120 :return: tuple (section, component) 

121 """ 

122 if section.find("/") != -1: 

123 return section, section.split("/", 1)[0] 

124 return section, "main" 

125 

126 

127################################################################################ 

128 

129 

130def parse_deb822( 

131 armored_contents: bytes, 

132 signing_rules: Literal[-1, 0, 1] = 0, 

133 keyrings: Collection[str] | None = None, 

134) -> dict[str, str]: 

135 require_signature = True 

136 if keyrings is None: 136 ↛ 140line 136 didn't jump to line 140 because the condition on line 136 was always true

137 keyrings = [] 

138 require_signature = False 

139 

140 signed_file = SignedFile( 

141 armored_contents, keyrings=keyrings, require_signature=require_signature 

142 ) 

143 contents = signed_file.contents.decode("utf-8") 

144 

145 error = "" 

146 changes = {} 

147 

148 # Split the lines in the input, keeping the linebreaks. 

149 lines = contents.splitlines(True) 

150 

151 if len(lines) == 0: 

152 raise ParseChangesError("[Empty changes file]") 

153 

154 # Reindex by line number so we can easily verify the format of 

155 # .dsc files... 

156 indexed_lines = {} 

157 for index, line in enumerate(lines, 1): 

158 indexed_lines[index] = line[:-1] 

159 

160 num_of_lines = len(indexed_lines) 

161 index = 0 

162 first = -1 

163 while index < num_of_lines: 

164 index += 1 

165 line = indexed_lines[index] 

166 if line == "" and signing_rules == 1: 166 ↛ 167line 166 didn't jump to line 167 because the condition on line 166 was never true

167 if index != num_of_lines: 

168 raise InvalidDscError(index) 

169 break 

170 if slf := re_single_line_field.match(line): 

171 field = slf.groups()[0].lower() 

172 changes[field] = slf.groups()[1] 

173 first = 1 

174 continue 

175 if line == " .": 

176 changes[field] += "\n" 

177 continue 

178 if mlf := re_multi_line_field.match(line): 

179 if first == -1: 179 ↛ 180line 179 didn't jump to line 180 because the condition on line 179 was never true

180 raise ParseChangesError( 

181 "'%s'\n [Multi-line field continuing on from nothing?]" % (line) 

182 ) 

183 if first == 1 and changes[field] != "": 

184 changes[field] += "\n" 

185 first = 0 

186 changes[field] += mlf.groups()[0] + "\n" 

187 continue 

188 error += line 

189 

190 changes["filecontents"] = armored_contents.decode() 

191 

192 # Strip the source version in brackets from the source field, 

193 # put it in the "source-version" field instead. 

194 if "source" in changes and (srcver := re_srchasver.search(changes["source"])): 194 ↛ 195line 194 didn't jump to line 195 because the condition on line 194 was never true

195 changes["source"] = srcver.group(1) 

196 changes["source-version"] = srcver.group(2) 

197 

198 if error: 198 ↛ 199line 198 didn't jump to line 199 because the condition on line 198 was never true

199 raise ParseChangesError(error) 

200 

201 return changes 

202 

203 

204################################################################################ 

205 

206 

207def parse_changes( 

208 filename: str, 

209 signing_rules: Literal[-1, 0, 1] = 0, 

210 dsc_file: bool = False, 

211 keyrings: Collection[str] | None = None, 

212) -> dict[str, str]: 

213 """ 

214 Parses a changes or source control (.dsc) file and returns a dictionary 

215 where each field is a key. The mandatory first argument is the 

216 filename of the .changes file. 

217 

218 signing_rules is an optional argument: 

219 

220 - If signing_rules == -1, no signature is required. 

221 - If signing_rules == 0 (the default), a signature is required. 

222 - If signing_rules == 1, it turns on the same strict format checking 

223 as dpkg-source. 

224 

225 The rules for (signing_rules == 1)-mode are: 

226 

227 - The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----" 

228 followed by any PGP header data and must end with a blank line. 

229 

230 - The data section must end with a blank line and must be followed by 

231 "-----BEGIN PGP SIGNATURE-----". 

232 

233 :param dsc_file: `filename` is a Debian source control (.dsc) file 

234 """ 

235 

236 with open(filename, "rb") as changes_in: 

237 content = changes_in.read() 

238 changes = parse_deb822(content, signing_rules, keyrings=keyrings) 

239 

240 if not dsc_file: 

241 # Finally ensure that everything needed for .changes is there 

242 must_keywords = ( 

243 "Format", 

244 "Date", 

245 "Source", 

246 "Architecture", 

247 "Version", 

248 "Distribution", 

249 "Maintainer", 

250 "Changes", 

251 "Files", 

252 ) 

253 

254 missingfields = [] 

255 for keyword in must_keywords: 

256 if keyword.lower() not in changes: 256 ↛ 257line 256 didn't jump to line 257 because the condition on line 256 was never true

257 missingfields.append(keyword) 

258 

259 if len(missingfields): 

260 raise ParseChangesError( 

261 "Missing mandatory field(s) in changes file (policy 5.5): %s" 

262 % (missingfields) 

263 ) 

264 

265 return changes 

266 

267 

268################################################################################ 

269 

270 

271def check_dsc_files( 

272 dsc_filename: str, 

273 dsc: Mapping[str, str], 

274 dsc_files: Iterable[str], 

275) -> list[str]: 

276 """ 

277 Verify that the files listed in the Files field of the .dsc are 

278 those expected given the announced Format. 

279 

280 :param dsc_filename: path of .dsc file 

281 :param dsc: the content of the .dsc parsed by :func:`parse_changes` 

282 :param dsc_files: the file list returned by :func:`build_file_list` 

283 :return: all errors detected 

284 """ 

285 rejmsg = [] 

286 

287 # Ensure .dsc lists proper set of source files according to the format 

288 # announced 

289 has: defaultdict[str, int] = defaultdict(lambda: 0) 

290 

291 ftype_lookup = ( 

292 (r"orig\.tar\.(gz|bz2|xz)\.asc", ("orig_tar_sig",)), 

293 (r"orig\.tar\.gz", ("orig_tar_gz", "orig_tar")), 

294 (r"diff\.gz", ("debian_diff",)), 

295 (r"tar\.gz", ("native_tar_gz", "native_tar")), 

296 (r"debian\.tar\.(gz|bz2|xz)", ("debian_tar",)), 

297 (r"orig\.tar\.(gz|bz2|xz)", ("orig_tar",)), 

298 (r"tar\.(gz|bz2|xz)", ("native_tar",)), 

299 (r"orig-.+\.tar\.(gz|bz2|xz)\.asc", ("more_orig_tar_sig",)), 

300 (r"orig-.+\.tar\.(gz|bz2|xz)", ("more_orig_tar",)), 

301 ) 

302 

303 for f in dsc_files: 

304 m = re_issource.match(f) 

305 if not m: 305 ↛ 306line 305 didn't jump to line 306 because the condition on line 305 was never true

306 rejmsg.append( 

307 "%s: %s in Files field not recognised as source." % (dsc_filename, f) 

308 ) 

309 continue 

310 

311 # Populate 'has' dictionary by resolving keys in lookup table 

312 matched = False 

313 for regex, keys in ftype_lookup: 313 ↛ 321line 313 didn't jump to line 321 because the loop on line 313 didn't complete

314 if re.match(regex, m.group(3)): 

315 matched = True 

316 for key in keys: 

317 has[key] += 1 

318 break 

319 

320 # File does not match anything in lookup table; reject 

321 if not matched: 321 ↛ 322line 321 didn't jump to line 322 because the condition on line 321 was never true

322 rejmsg.append("%s: unexpected source file '%s'" % (dsc_filename, f)) 

323 break 

324 

325 # Check for multiple files 

326 for file_type in ( 

327 "orig_tar", 

328 "orig_tar_sig", 

329 "native_tar", 

330 "debian_tar", 

331 "debian_diff", 

332 ): 

333 if has[file_type] > 1: 333 ↛ 334line 333 didn't jump to line 334 because the condition on line 333 was never true

334 rejmsg.append("%s: lists multiple %s" % (dsc_filename, file_type)) 

335 

336 # Source format specific tests 

337 try: 

338 format = get_format_from_string(dsc["format"]) 

339 rejmsg.extend(["%s: %s" % (dsc_filename, x) for x in format.reject_msgs(has)]) 

340 

341 except UnknownFormatError: 

342 # Not an error here for now 

343 pass 

344 

345 return rejmsg 

346 

347 

348################################################################################ 

349 

350# Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl 

351 

352 

353def build_file_list( 

354 changes: Mapping[str, str], is_a_dsc: bool = False, field="files", hashname="md5sum" 

355) -> dict[str, dict[str, str]]: 

356 files = {} 

357 

358 # Make sure we have a Files: field to parse... 

359 if field not in changes: 359 ↛ 360line 359 didn't jump to line 360 because the condition on line 359 was never true

360 raise NoFilesFieldError 

361 

362 # Validate .changes Format: field 

363 if not is_a_dsc: 363 ↛ 364line 363 didn't jump to line 364 because the condition on line 363 was never true

364 validate_changes_format(parse_format(changes["format"]), field) 

365 

366 includes_section = (not is_a_dsc) and field == "files" 

367 

368 # Parse each entry/line: 

369 for i in changes[field].split("\n"): 369 ↛ 397line 369 didn't jump to line 397 because the loop on line 369 didn't complete

370 if not i: 

371 break 

372 s = i.split() 

373 section = priority = "" 

374 try: 

375 if includes_section: 375 ↛ 376line 375 didn't jump to line 376 because the condition on line 375 was never true

376 (md5, size, section, priority, name) = s 

377 else: 

378 (md5, size, name) = s 

379 except ValueError: 

380 raise ParseChangesError(i) 

381 

382 if section == "": 382 ↛ 384line 382 didn't jump to line 384 because the condition on line 382 was always true

383 section = "-" 

384 if priority == "": 384 ↛ 387line 384 didn't jump to line 387 because the condition on line 384 was always true

385 priority = "-" 

386 

387 (section, component) = extract_component_from_section(section) 

388 

389 files[name] = { 

390 "size": size, 

391 "section": section, 

392 "priority": priority, 

393 "component": component, 

394 } 

395 files[name][hashname] = md5 

396 

397 return files 

398 

399 

400################################################################################ 

401 

402 

403def _mail_read_whitelists( 

404 whitelists: list[str | None] | None, 

405) -> tuple[bool, list[re.Pattern]]: 

406 if whitelists is None or None in whitelists: 

407 whitelists = [] 

408 if mail_white_list := Cnf.get("Dinstall::MailWhiteList", ""): 408 ↛ 409line 408 didn't jump to line 409 because the condition on line 408 was never true

409 whitelists.append(mail_white_list) 

410 if not whitelists: 410 ↛ 413line 410 didn't jump to line 413 because the condition on line 410 was always true

411 return False, [] 

412 

413 patterns: list[re.Pattern] = [] 

414 for path in whitelists: 

415 assert path is not None 

416 with open(path, "r") as whitelist_in: 

417 for line in whitelist_in: 

418 if re_whitespace_comment.match(line): 

419 continue 

420 if re_re_mark.match(line): 

421 patterns.append(re.compile(re_re_mark.sub("", line.strip(), 1))) 

422 else: 

423 patterns.append(re.compile(re.escape(line.strip()))) 

424 

425 return True, patterns 

426 

427 

428def _mail_apply_whitelists( 

429 msg: email.message.EmailMessage, patterns: list[re.Pattern] 

430) -> bool: 

431 # Fields to check. 

432 fields = ["To", "Bcc", "Cc"] 

433 for field in fields: 

434 # Check each field 

435 value = msg.get(field, None) 

436 if value is None: 

437 continue 

438 match = [] 

439 for item in value.split(","): 

440 (rfc822_maint, rfc2047_maint, name, mail) = fix_maintainer(item.strip()) 

441 mail_whitelisted = any(wr.fullmatch(mail) for wr in patterns) 

442 if not mail_whitelisted: 

443 print("Skipping {0} since it's not whitelisted".format(item)) 

444 continue 

445 match.append(item) 

446 

447 # Doesn't have any mail in whitelist so remove the header 

448 if len(match) == 0: 

449 del msg[field] 

450 else: 

451 msg.replace_header(field, ", ".join(match)) 

452 

453 # Change message fields in order if we don't have a To header 

454 if "To" not in msg: 

455 fields.reverse() 

456 for field in fields: 

457 if field in msg: 

458 msg[fields[-1]] = msg[field] 

459 del msg[field] 

460 break 

461 else: 

462 # return, as we removed all recipients. 

463 return False 

464 

465 return True 

466 

467 

468def send_mail(message: str, whitelists: list[str | None] | None = None) -> None: 

469 """sendmail wrapper, takes a message string 

470 

471 :param whitelists: path to whitelists. :const:`None` or an empty list whitelists 

472 everything, otherwise an address is whitelisted if it is 

473 included in any of the lists. 

474 In addition a global whitelist can be specified in 

475 Dinstall::MailWhiteList. 

476 """ 

477 

478 msg = daklib.mail.parse_mail(message) 

479 

480 # The incoming message might be UTF-8, but outgoing mail should 

481 # use a legacy-compatible encoding. Set the content to the 

482 # text to make sure this is the case. 

483 # Note that this does not work with multipart messages. 

484 msg.set_content(msg.get_payload(), cte="quoted-printable") 

485 

486 if "Date" not in msg: 486 ↛ 490line 486 didn't jump to line 490 because the condition on line 486 was always true

487 msg["Date"] = email.utils.format_datetime( 

488 datetime.datetime.now(tz=datetime.UTC) 

489 ) 

490 if "Message-Id" not in msg: 490 ↛ 494line 490 didn't jump to line 494 because the condition on line 490 was always true

491 msg["Message-Id"] = email.utils.make_msgid() 

492 

493 # Check whether we're supposed to be sending mail 

494 call_sendmail = True 

495 if "Dinstall::Options::No-Mail" in Cnf and Cnf["Dinstall::Options::No-Mail"]: 

496 call_sendmail = False 

497 

498 have_whitelist, whitelist_patterns = _mail_read_whitelists(whitelists) 

499 if have_whitelist: 499 ↛ 500line 499 didn't jump to line 500 because the condition on line 499 was never true

500 recipients_left = _mail_apply_whitelists(msg, whitelist_patterns) 

501 call_sendmail = call_sendmail and recipients_left 

502 

503 # sign mail 

504 if mailkey := Cnf.get("Dinstall::Mail-Signature-Key", ""): 504 ↛ 513line 504 didn't jump to line 513 because the condition on line 504 was always true

505 msg = daklib.mail.sign_mail( 

506 msg, 

507 keyids=[mailkey], 

508 pubring=Cnf.get("Dinstall::SigningPubKeyring") or None, 

509 homedir=Cnf.get("Dinstall::SigningHomedir") or None, 

510 passphrase_file=Cnf.get("Dinstall::SigningPassphraseFile") or None, 

511 ) 

512 

513 msg_bytes = msg.as_bytes(policy=email.policy.default) 

514 

515 maildir = Cnf.get("Dir::Mail") 

516 if maildir: 516 ↛ 523line 516 didn't jump to line 523 because the condition on line 516 was always true

517 path = os.path.join(maildir, datetime.datetime.now(tz=datetime.UTC).isoformat()) 

518 path = find_next_free(path) 

519 with open(path, "wb") as fh: 

520 fh.write(msg_bytes) 

521 

522 # Invoke sendmail 

523 if not call_sendmail: 

524 return 

525 try: 

526 subprocess.run( 

527 Cnf["Dinstall::SendmailCommand"].split(), 

528 input=msg_bytes, 

529 check=True, 

530 stdout=subprocess.PIPE, 

531 stderr=subprocess.STDOUT, 

532 ) 

533 except subprocess.CalledProcessError as e: 

534 raise SendmailFailedError(e.output.decode().rstrip()) 

535 

536 

537################################################################################ 

538 

539 

540def poolify(source: str) -> str: 

541 """convert `source` name into directory path used in pool structure""" 

542 if source[:3] == "lib": 542 ↛ 543line 542 didn't jump to line 543 because the condition on line 542 was never true

543 return source[:4] + "/" + source + "/" 

544 else: 

545 return source[:1] + "/" + source + "/" 

546 

547 

548################################################################################ 

549 

550 

551def move(src: str, dest: str, overwrite: bool = False, perms: int = 0o664) -> None: 

552 if os.path.exists(dest) and os.path.isdir(dest): 

553 dest_dir = dest 

554 else: 

555 dest_dir = os.path.dirname(dest) 

556 if not os.path.lexists(dest_dir): 

557 umask = os.umask(00000) 

558 os.makedirs(dest_dir, 0o2775) 

559 os.umask(umask) 

560 # print "Moving %s to %s..." % (src, dest) 

561 if os.path.exists(dest) and os.path.isdir(dest): 

562 dest += "/" + os.path.basename(src) 

563 # Don't overwrite unless forced to 

564 if os.path.lexists(dest): 

565 if not overwrite: 

566 fubar("Can't move %s to %s - file already exists." % (src, dest)) 

567 else: 

568 if not os.access(dest, os.W_OK): 

569 fubar( 

570 "Can't move %s to %s - can't write to existing file." % (src, dest) 

571 ) 

572 shutil.copy2(src, dest) 

573 os.chmod(dest, perms) 

574 os.unlink(src) 

575 

576 

577################################################################################ 

578 

579 

580def TemplateSubst(subst_map: Mapping[str, str], filename: str) -> str: 

581 """Perform a substition of template""" 

582 with open(filename) as templatefile: 

583 template = templatefile.read() 

584 for k, v in subst_map.items(): 

585 template = template.replace(k, str(v)) 

586 return template 

587 

588 

589################################################################################ 

590 

591 

592def fubar(msg: str, exit_code: int = 1) -> NoReturn: 

593 """print error message and exit program""" 

594 print("E:", msg, file=sys.stderr) 

595 sys.exit(exit_code) 

596 

597 

598def warn(msg: str) -> None: 

599 """print warning message""" 

600 print("W:", msg, file=sys.stderr) 

601 

602 

603################################################################################ 

604 

605 

606def whoami() -> str: 

607 """get user name 

608 

609 Returns the user name with a laughable attempt at rfc822 conformancy 

610 (read: removing stray periods). 

611 """ 

612 return pwd.getpwuid(os.getuid())[4].split(",")[0].replace(".", "") 

613 

614 

615def getusername() -> str: 

616 """get login name""" 

617 return pwd.getpwuid(os.getuid())[0] 

618 

619 

620################################################################################ 

621 

622 

623def size_type(c: float) -> str: 

624 t = " B" 

625 if c > 10240: 

626 c = c / 1024 

627 t = " KB" 

628 if c > 10240: 628 ↛ 629line 628 didn't jump to line 629 because the condition on line 628 was never true

629 c = c / 1024 

630 t = " MB" 

631 return "%d%s" % (c, t) 

632 

633 

634################################################################################ 

635 

636 

637def find_next_free(dest: str, too_many: int = 100) -> str: 

638 extra = 0 

639 orig_dest = dest 

640 while os.path.lexists(dest) and extra < too_many: 

641 dest = orig_dest + "." + repr(extra) 

642 extra += 1 

643 if extra >= too_many: 643 ↛ 644line 643 didn't jump to line 644 because the condition on line 643 was never true

644 raise NoFreeFilenameError 

645 return dest 

646 

647 

648################################################################################ 

649 

650 

651def result_join(original: Iterable[str | None], sep: str = "\t") -> str: 

652 return sep.join(x if x is not None else "" for x in original) 

653 

654 

655################################################################################ 

656 

657 

658def prefix_multi_line_string( 

659 lines: str, prefix: str, include_blank_lines: bool = False 

660) -> str: 

661 """prepend `prefix` to each line in `lines`""" 

662 return "\n".join( 

663 prefix + cleaned_line 

664 for line in lines.split("\n") 

665 if (cleaned_line := line.strip()) or include_blank_lines 

666 ) 

667 

668 

669################################################################################ 

670 

671 

672def join_with_commas_and(list: Sequence[str]) -> str: 

673 if len(list) == 0: 673 ↛ 674line 673 didn't jump to line 674 because the condition on line 673 was never true

674 return "nothing" 

675 if len(list) == 1: 675 ↛ 677line 675 didn't jump to line 677 because the condition on line 675 was always true

676 return list[0] 

677 return ", ".join(list[:-1]) + " and " + list[-1] 

678 

679 

680################################################################################ 

681 

682 

683def pp_deps(deps: Iterable[tuple[str, str, str]]) -> str: 

684 pp_deps = ( 

685 f"{pkg} ({constraint} {version})" if constraint else pkg 

686 for pkg, constraint, version in deps 

687 ) 

688 return " |".join(pp_deps) 

689 

690 

691################################################################################ 

692 

693 

694def get_conf() -> apt_pkg.Configuration: 

695 return Cnf 

696 

697 

698################################################################################ 

699 

700 

701def parse_args( 

702 Options: apt_pkg.Configuration, 

703) -> tuple[str, str, str, bool, dict[str, object]]: 

704 """Handle -a, -c and -s arguments; returns them as SQL constraints 

705 

706 The constraints refer to bind parameters (`suite_ids`, `component_ids` 

707 and `architecture_ids`), whose values are returned in the dict. 

708 """ 

709 # XXX: This should go away and everything which calls it be converted 

710 # to use SQLA properly. For now, we'll just fix it not to use 

711 # the old Pg interface though 

712 session = DBConn().session() 

713 parameters: dict[str, object] = {} 

714 # Process suite 

715 if Options["Suite"]: 715 ↛ 732line 715 didn't jump to line 732 because the condition on line 715 was always true

716 suite_ids_list = [] 

717 for suitename in split_args(Options["Suite"]): 

718 suite = get_suite(suitename, session=session) 

719 if not suite or suite.suite_id is None: 719 ↛ 720line 719 didn't jump to line 720 because the condition on line 719 was never true

720 warn( 

721 "suite '%s' not recognised." 

722 % (suite and suite.suite_name or suitename) 

723 ) 

724 else: 

725 suite_ids_list.append(suite.suite_id) 

726 if suite_ids_list: 726 ↛ 730line 726 didn't jump to line 730 because the condition on line 726 was always true

727 con_suites = "AND su.id = ANY(:suite_ids)" 

728 parameters["suite_ids"] = suite_ids_list 

729 else: 

730 fubar("No valid suite given.") 

731 else: 

732 con_suites = "" 

733 

734 # Process component 

735 if Options["Component"]: 735 ↛ 736line 735 didn't jump to line 736 because the condition on line 735 was never true

736 component_ids_list = [] 

737 for componentname in split_args(Options["Component"]): 

738 component = get_component(componentname, session=session) 

739 if component is None: 

740 warn("component '%s' not recognised." % (componentname)) 

741 else: 

742 component_ids_list.append(component.component_id) 

743 if component_ids_list: 

744 con_components = "AND c.id = ANY(:component_ids)" 

745 parameters["component_ids"] = component_ids_list 

746 else: 

747 fubar("No valid component given.") 

748 else: 

749 con_components = "" 

750 

751 # Process architecture 

752 con_architectures = "" 

753 check_source = False 

754 if Options["Architecture"]: 754 ↛ 755line 754 didn't jump to line 755 because the condition on line 754 was never true

755 arch_ids_list = [] 

756 for archname in split_args(Options["Architecture"]): 

757 if archname == "source": 

758 check_source = True 

759 else: 

760 arch = get_architecture(archname, session=session) 

761 if arch is None: 

762 warn("architecture '%s' not recognised." % (archname)) 

763 else: 

764 arch_ids_list.append(arch.arch_id) 

765 if arch_ids_list: 

766 con_architectures = "AND a.id = ANY(:architecture_ids)" 

767 parameters["architecture_ids"] = arch_ids_list 

768 else: 

769 if not check_source: 

770 fubar("No valid architecture given.") 

771 else: 

772 check_source = True 

773 

774 return (con_suites, con_architectures, con_components, check_source, parameters) 

775 

776 

777################################################################################ 

778 

779 

780@functools.total_ordering 

781class ArchKey: 

782 """ 

783 Key object for use in sorting lists of architectures. 

784 

785 Sorts normally except that 'source' dominates all others. 

786 """ 

787 

788 __slots__ = ["arch", "issource"] 

789 

790 def __init__(self, arch: str, *args): 

791 self.arch = arch 

792 self.issource = arch == "source" 

793 

794 def __lt__(self, other: "ArchKey") -> bool: 

795 if self.issource: 

796 return not other.issource 

797 if other.issource: 

798 return False 

799 return self.arch < other.arch 

800 

801 @override 

802 def __eq__(self, other: object) -> bool: 

803 if not isinstance(other, ArchKey): 803 ↛ 804line 803 didn't jump to line 804 because the condition on line 803 was never true

804 return NotImplemented 

805 return self.arch == other.arch 

806 

807 

808################################################################################ 

809 

810 

811def split_args(s: str, dwim: bool = True) -> list[str]: 

812 """ 

813 Split command line arguments which can be separated by either commas 

814 or whitespace. If dwim is set, it will complain about string ending 

815 in comma since this usually means someone did 'dak ls -a i386, m68k 

816 foo' or something and the inevitable confusion resulting from 'm68k' 

817 being treated as an argument is undesirable. 

818 """ 

819 

820 if s.find(",") == -1: 820 ↛ 823line 820 didn't jump to line 823 because the condition on line 820 was always true

821 return s.split() 

822 else: 

823 if s[-1:] == "," and dwim: 

824 fubar("split_args: found trailing comma, spurious space maybe?") 

825 return s.split(",") 

826 

827 

828################################################################################ 

829 

830 

831def split_args_or_none(s: str | None, dwim: bool = True) -> list[str] | None: 

832 """ 

833 Split command line arguments like `split_args`, but return `None` for empty string 

834 """ 

835 if not s: 

836 return None 

837 return split_args(s, dwim) 

838 

839 

840################################################################################ 

841 

842 

843def gpg_keyring_args(keyrings: Iterable[str] | None = None) -> list[str]: 

844 if keyrings is None: 844 ↛ 847line 844 didn't jump to line 847 because the condition on line 844 was always true

845 keyrings = get_active_keyring_paths() 

846 

847 return ["--keyring={}".format(path) for path in keyrings] 

848 

849 

850################################################################################ 

851 

852 

853def _gpg_get_addresses_from_listing(output: bytes) -> list[str]: 

854 addresses: list[str] = [] 

855 

856 for line in output.split(b"\n"): 

857 parts = line.split(b":") 

858 if parts[0] not in (b"uid", b"pub"): 

859 continue 

860 if parts[1] in (b"i", b"d", b"r"): 860 ↛ 862line 860 didn't jump to line 862 because the condition on line 860 was never true

861 # Skip uid that is invalid, disabled or revoked 

862 continue 

863 try: 

864 uid_bytes = parts[9] 

865 except IndexError: 

866 continue 

867 try: 

868 uid = uid_bytes.decode(encoding="utf-8") 

869 except UnicodeDecodeError: 

870 # If the uid is not valid UTF-8, we assume it is an old uid 

871 # still encoding in Latin-1. 

872 uid = uid_bytes.decode(encoding="latin1") 

873 m = re_parse_maintainer.match(uid) 

874 if not m: 

875 continue 

876 address = m.group(2) 

877 if address.endswith("@debian.org"): 877 ↛ 880line 877 didn't jump to line 880 because the condition on line 877 was never true

878 # prefer @debian.org addresses 

879 # TODO: maybe not hardcode the domain 

880 addresses.insert(0, address) 

881 else: 

882 addresses.append(address) 

883 

884 return addresses 

885 

886 

887def gpg_get_key_addresses(fingerprint: str) -> list[str]: 

888 """retreive email addresses from gpg key uids for a given fingerprint""" 

889 addresses = key_uid_email_cache.get(fingerprint) 

890 if addresses is not None: 

891 return addresses 

892 

893 try: 

894 cmd = ["gpg", "--no-default-keyring"] 

895 cmd.extend(gpg_keyring_args()) 

896 cmd.extend(["--with-colons", "--list-keys", "--", fingerprint]) 

897 output = subprocess.check_output(cmd, stderr=subprocess.DEVNULL) 

898 except subprocess.CalledProcessError: 

899 addresses = [] 

900 else: 

901 addresses = _gpg_get_addresses_from_listing(output) 

902 

903 key_uid_email_cache[fingerprint] = addresses 

904 return addresses 

905 

906 

907################################################################################ 

908 

909 

910def open_ldap_connection() -> Any: 

911 """open connection to the configured LDAP server""" 

912 import ldap # type: ignore 

913 

914 LDAPServer = Cnf["Import-LDAP-Fingerprints::LDAPServer"] 

915 ca_cert_file = Cnf.get("Import-LDAP-Fingerprints::CACertFile") 

916 

917 conn = ldap.initialize(LDAPServer) 

918 

919 if ca_cert_file: 

920 conn.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_HARD) 

921 conn.set_option(ldap.OPT_X_TLS_CACERTFILE, ca_cert_file) 

922 conn.set_option(ldap.OPT_X_TLS_NEWCTX, True) 

923 conn.start_tls_s() 

924 

925 conn.simple_bind_s("", "") 

926 

927 return conn 

928 

929 

930################################################################################ 

931 

932 

933def get_logins_from_ldap(fingerprint: str = "*") -> dict[str, str]: 

934 """retrieve login from LDAP linked to a given fingerprint""" 

935 import ldap 

936 

937 conn = open_ldap_connection() 

938 LDAPDn = Cnf["Import-LDAP-Fingerprints::LDAPDn"] 

939 Attrs = conn.search_s( 

940 LDAPDn, 

941 ldap.SCOPE_ONELEVEL, 

942 "(keyfingerprint=%s)" % fingerprint, 

943 ["uid", "keyfingerprint"], 

944 ) 

945 login: dict[str, str] = {} 

946 for elem in Attrs: 

947 fpr = elem[1]["keyFingerPrint"][0].decode() 

948 uid = elem[1]["uid"][0].decode() 

949 login[fpr] = uid 

950 return login 

951 

952 

953################################################################################ 

954 

955 

956def get_users_from_ldap() -> dict[str, str]: 

957 """retrieve login and user names from LDAP""" 

958 import ldap 

959 

960 conn = open_ldap_connection() 

961 LDAPDn = Cnf["Import-LDAP-Fingerprints::LDAPDn"] 

962 Attrs = conn.search_s( 

963 LDAPDn, ldap.SCOPE_ONELEVEL, "(uid=*)", ["uid", "cn", "mn", "sn"] 

964 ) 

965 users: dict[str, str] = {} 

966 for elem in Attrs: 

967 elem = elem[1] 

968 name = [] 

969 for k in ("cn", "mn", "sn"): 

970 try: 

971 value = elem[k][0].decode() 

972 if value and value[0] != "-": 

973 name.append(value) 

974 except KeyError: 

975 pass 

976 users[" ".join(name)] = elem["uid"][0] 

977 return users 

978 

979 

980################################################################################ 

981 

982 

983def clean_symlink(src: str, dest: str, root: str) -> str: 

984 """ 

985 Relativize an absolute symlink from 'src' -> 'dest' relative to 'root'. 

986 Returns fixed 'src' 

987 """ 

988 src = src.replace(root, "", 1) 

989 dest = dest.replace(root, "", 1) 

990 dest = os.path.dirname(dest) 

991 new_src = "../" * len(dest.split("/")) 

992 return new_src + src 

993 

994 

995################################################################################ 

996 

997 

998def temp_dirname( 

999 parent: str | None = None, 

1000 prefix: str = "dak", 

1001 suffix: str = "", 

1002 mode: int | None = None, 

1003 group: str | None = None, 

1004) -> str: 

1005 """ 

1006 Return a secure and unique directory by pre-creating it. 

1007 

1008 :param parent: If non-null it will be the directory the directory is pre-created in. 

1009 :param prefix: The filename will be prefixed with this string 

1010 :param suffix: The filename will end with this string 

1011 :param mode: If set the file will get chmodded to those permissions 

1012 :param group: If set the file will get chgrped to the specified group. 

1013 :return: Returns a pair (fd, name) 

1014 

1015 """ 

1016 

1017 tfname = tempfile.mkdtemp(suffix, prefix, parent) 

1018 if mode is not None: 1018 ↛ 1020line 1018 didn't jump to line 1020 because the condition on line 1018 was always true

1019 os.chmod(tfname, mode) 

1020 if group is not None: 1020 ↛ 1021line 1020 didn't jump to line 1021 because the condition on line 1020 was never true

1021 gid = grp.getgrnam(group).gr_gid 

1022 os.chown(tfname, -1, gid) 

1023 return tfname 

1024 

1025 

1026################################################################################ 

1027 

1028 

1029def get_changes_files(from_dir: str) -> list[str]: 

1030 """ 

1031 Takes a directory and lists all .changes files in it (as well as chdir'ing 

1032 to the directory; this is due to broken behaviour on the part of p-u/p-a 

1033 when you're not in the right place) 

1034 

1035 Returns a list of filenames 

1036 """ 

1037 try: 

1038 # Much of the rest of p-u/p-a depends on being in the right place 

1039 os.chdir(from_dir) 

1040 changes_files = [x for x in os.listdir(from_dir) if x.endswith(".changes")] 

1041 except OSError as e: 

1042 fubar("Failed to read list from directory %s (%s)" % (from_dir, e)) 

1043 

1044 return changes_files 

1045 

1046 

1047################################################################################ 

1048 

1049 

1050Cnf: apt_pkg.Configuration = config.Config().Cnf 

1051 

1052################################################################################ 

1053 

1054 

1055def parse_wnpp_bug_file( 

1056 file: str = "/srv/ftp-master.debian.org/scripts/masterfiles/wnpp_rm", 

1057) -> dict[str, list[str]]: 

1058 """ 

1059 Parses the wnpp bug list available at https://qa.debian.org/data/bts/wnpp_rm 

1060 Well, actually it parsed a local copy, but let's document the source 

1061 somewhere ;) 

1062 

1063 returns a dict associating source package name with a list of open wnpp 

1064 bugs (Yes, there might be more than one) 

1065 """ 

1066 

1067 try: 

1068 with open(file) as f: 

1069 lines = f.readlines() 

1070 except OSError: 

1071 print( 

1072 "Warning: Couldn't open %s; don't know about WNPP bugs, so won't close any." 

1073 % file 

1074 ) 

1075 lines = [] 

1076 wnpp = {} 

1077 

1078 for line in lines: 

1079 splited_line = line.split(": ", 1) 

1080 if len(splited_line) > 1: 

1081 wnpp[splited_line[0]] = splited_line[1].split("|") 

1082 

1083 for source, values in wnpp.items(): 

1084 bugs = [] 

1085 for wnpp_bug in values: 

1086 m = re.search(r"(\d)+", wnpp_bug) 

1087 assert m is not None 

1088 bug_no = m.group() 

1089 if bug_no: 

1090 bugs.append(bug_no) 

1091 wnpp[source] = bugs 

1092 return wnpp 

1093 

1094 

1095################################################################################ 

1096 

1097 

1098def deb_extract_control(path: str) -> bytes: 

1099 """extract DEBIAN/control from a binary package""" 

1100 return apt_inst.DebFile(path).control.extractdata("control") 

1101 

1102 

1103################################################################################ 

1104 

1105 

1106def mail_addresses_for_upload( 

1107 maintainer: str, 

1108 changed_by: str, 

1109 fingerprint: str, 

1110 authorized_by_fingerprint: str | None, 

1111) -> list[str]: 

1112 """mail addresses to contact for an upload 

1113 

1114 :param maintainer: Maintainer field of the .changes file 

1115 :param changed_by: Changed-By field of the .changes file 

1116 :param fingerprint: fingerprint of the key used to sign the upload 

1117 :return: list of RFC 2047-encoded mail addresses to contact regarding 

1118 this upload 

1119 """ 

1120 recipients = Cnf.value_list("Dinstall::UploadMailRecipients") 

1121 if not recipients: 1121 ↛ 1130line 1121 didn't jump to line 1130 because the condition on line 1121 was always true

1122 recipients = [ 

1123 "maintainer", 

1124 "changed_by", 

1125 "signer", 

1126 "authorized_by", 

1127 ] 

1128 

1129 # Ensure signer and authorized_by are last if present 

1130 for r in ("signer", "authorized_by"): 

1131 try: 

1132 recipients.remove(r) 

1133 except ValueError: 

1134 pass 

1135 else: 

1136 recipients.append(r) 

1137 

1138 # Compute the set of addresses of the recipients 

1139 addresses = set() # Name + email 

1140 emails = set() # Email only, used to avoid duplicates 

1141 for recipient in recipients: 

1142 address: str | None 

1143 if recipient.startswith("mail:"): # Email hardcoded in config 1143 ↛ 1144line 1143 didn't jump to line 1144 because the condition on line 1143 was never true

1144 address = recipient[5:] 

1145 elif recipient == "maintainer": 

1146 address = maintainer 

1147 elif recipient == "changed_by": 

1148 address = changed_by 

1149 elif recipient == "signer" or recipient == "authorized_by": 1149 ↛ 1159line 1149 didn't jump to line 1159 because the condition on line 1149 was always true

1150 fpr = fingerprint if recipient == "signer" else authorized_by_fingerprint 

1151 if not fpr: 1151 ↛ 1152line 1151 didn't jump to line 1152 because the condition on line 1151 was never true

1152 continue 

1153 fpr_addresses = gpg_get_key_addresses(fpr) 

1154 address = fpr_addresses[0] if fpr_addresses else None 

1155 if any(x in emails for x in fpr_addresses): 

1156 # The signer already gets a copy via another email 

1157 address = None 

1158 else: 

1159 raise Exception( 

1160 "Unsupported entry in {0}: {1}".format( 

1161 "Dinstall::UploadMailRecipients", recipient 

1162 ) 

1163 ) 

1164 

1165 if address is not None: 

1166 mail = fix_maintainer(address)[3] 

1167 if mail not in emails: 

1168 addresses.add(address) 

1169 emails.add(mail) 

1170 

1171 encoded_addresses = [fix_maintainer(e)[1] for e in addresses] 

1172 return encoded_addresses 

1173 

1174 

1175################################################################################ 

1176 

1177 

1178def call_editor_for_file(path: str) -> None: 

1179 editor = os.environ.get("VISUAL", os.environ.get("EDITOR", "sensible-editor")) 

1180 subprocess.check_call([editor, path]) 

1181 

1182 

1183################################################################################ 

1184 

1185 

1186def call_editor(text: str = "", suffix: str = ".txt") -> str: 

1187 """run editor and return the result as a string 

1188 

1189 :param text: initial text 

1190 :param suffix: extension for temporary file 

1191 :return: string with the edited text 

1192 """ 

1193 with tempfile.NamedTemporaryFile(mode="w+t", suffix=suffix) as fh: 

1194 print(text, end="", file=fh) 

1195 fh.flush() 

1196 call_editor_for_file(fh.name) 

1197 fh.seek(0) 

1198 return fh.read() 

1199 

1200 

1201################################################################################ 

1202 

1203 

1204def check_reverse_depends( 

1205 removals: Iterable[str], 

1206 suite: str, 

1207 arches: Iterable[str] | None = None, 

1208 session: "Session | None" = None, 

1209 cruft: bool = False, 

1210 quiet: bool = False, 

1211 include_arch_all: bool = True, 

1212) -> bool: 

1213 assert session is not None # TODO: remove default value... 

1214 

1215 dbsuite = get_suite(suite, session) 

1216 assert dbsuite is not None 

1217 overridesuite = ( 

1218 get_suite(dbsuite.overridesuite, session) if dbsuite.overridesuite else dbsuite 

1219 ) 

1220 assert overridesuite is not None 

1221 dep_problem = False 

1222 p2c = {} 

1223 all_broken: defaultdict[str, defaultdict[str, set[str]]] = defaultdict( 1223 ↛ exitline 1223 didn't jump to the function exit

1224 lambda: defaultdict(set) 

1225 ) 

1226 if arches: 1226 ↛ 1227line 1226 didn't jump to line 1227 because the condition on line 1226 was never true

1227 all_arches = set(arches) 

1228 else: 

1229 all_arches = { 

1230 x.arch_string for x in get_suite_architectures(suite, session=session) 

1231 } 

1232 all_arches -= {"source", "all"} 

1233 removal_set = set(removals) 

1234 metakey_d = get_or_set_metadatakey("Depends", session) 

1235 metakey_p = get_or_set_metadatakey("Provides", session) 

1236 if include_arch_all: 

1237 rdep_architectures = all_arches | {"all"} 

1238 else: 

1239 rdep_architectures = all_arches 

1240 for architecture in rdep_architectures: 

1241 deps = {} 

1242 sources = {} 

1243 virtual_packages = {} 

1244 

1245 params: dict[str, object] = { 

1246 "suite_id": dbsuite.suite_id, 

1247 "metakey_d_id": metakey_d.key_id, 

1248 "metakey_p_id": metakey_p.key_id, 

1249 } 

1250 arch = get_architecture(architecture, session) 

1251 if arch is None: 1251 ↛ 1252line 1251 didn't jump to line 1252 because the condition on line 1251 was never true

1252 continue 

1253 params["arch_id"] = arch.arch_id 

1254 

1255 statement = sql.text( 

1256 """ 

1257 SELECT b.package, s.source, c.name as component, 

1258 (SELECT bmd.value FROM binaries_metadata bmd WHERE bmd.bin_id = b.id AND bmd.key_id = :metakey_d_id) AS depends, 

1259 (SELECT bmp.value FROM binaries_metadata bmp WHERE bmp.bin_id = b.id AND bmp.key_id = :metakey_p_id) AS provides 

1260 FROM binaries b 

1261 JOIN bin_associations ba ON b.id = ba.bin AND ba.suite = :suite_id 

1262 JOIN source s ON b.source = s.id 

1263 JOIN files_archive_map af ON b.file = af.file_id 

1264 JOIN component c ON af.component_id = c.id 

1265 WHERE b.architecture = :arch_id""" 

1266 ) 

1267 query = session.execute(statement, params) 

1268 for package, source, component, depends, provides in query: 

1269 sources[package] = source 

1270 p2c[package] = component 

1271 if depends is not None: 1271 ↛ 1272line 1271 didn't jump to line 1272 because the condition on line 1271 was never true

1272 deps[package] = depends 

1273 # Maintain a counter for each virtual package. If a 

1274 # Provides: exists, set the counter to 0 and count all 

1275 # provides by a package not in the list for removal. 

1276 # If the counter stays 0 at the end, we know that only 

1277 # the to-be-removed packages provided this virtual 

1278 # package. 

1279 if provides is not None: 1279 ↛ 1280line 1279 didn't jump to line 1280 because the condition on line 1279 was never true

1280 for virtual_pkg in provides.split(","): 

1281 virtual_pkg = virtual_pkg.strip() 

1282 if virtual_pkg == package: 

1283 continue 

1284 if virtual_pkg not in virtual_packages: 

1285 virtual_packages[virtual_pkg] = 0 

1286 if package not in removals: 

1287 virtual_packages[virtual_pkg] += 1 

1288 

1289 # If a virtual package is only provided by the to-be-removed 

1290 # packages, treat the virtual package as to-be-removed too. 

1291 removal_set.update( 

1292 virtual_pkg 

1293 for virtual_pkg in virtual_packages 

1294 if not virtual_packages[virtual_pkg] 

1295 ) 

1296 

1297 # Check binary dependencies (Depends) 

1298 for package, package_deps in deps.items(): 1298 ↛ 1299line 1298 didn't jump to line 1299 because the loop on line 1298 never started

1299 if package in removals: 

1300 continue 

1301 try: 

1302 parsed_dep = apt_pkg.parse_depends(package_deps) 

1303 except ValueError as e: 

1304 print("Error for package %s: %s" % (package, e)) 

1305 parsed_dep = [] 

1306 for dep in parsed_dep: 

1307 # Check for partial breakage. If a package has a ORed 

1308 # dependency, there is only a dependency problem if all 

1309 # packages in the ORed depends will be removed. 

1310 unsat = 0 

1311 for dep_package, _, _ in dep: 

1312 if dep_package in removals: 

1313 unsat += 1 

1314 if unsat == len(dep): 

1315 component = p2c[package] 

1316 source = sources[package] 

1317 if component != "main": 

1318 source = "%s/%s" % (source, component) 

1319 all_broken[source][package].add(architecture) 

1320 dep_problem = True 

1321 

1322 if all_broken and not quiet: 1322 ↛ 1323line 1322 didn't jump to line 1323 because the condition on line 1322 was never true

1323 if cruft: 

1324 print(" - broken Depends:") 

1325 else: 

1326 print("# Broken Depends:") 

1327 for source, bindict in sorted(all_broken.items()): 

1328 lines = [] 

1329 for binary, bin_arches in sorted(bindict.items()): 

1330 if bin_arches == all_arches or "all" in bin_arches: 

1331 lines.append(binary) 

1332 else: 

1333 lines.append("%s [%s]" % (binary, " ".join(sorted(bin_arches)))) 

1334 if cruft: 

1335 print(" %s: %s" % (source, lines[0])) 

1336 else: 

1337 print("%s: %s" % (source, lines[0])) 

1338 for line in lines[1:]: 

1339 if cruft: 

1340 print(" " + " " * (len(source) + 2) + line) 

1341 else: 

1342 print(" " * (len(source) + 2) + line) 

1343 if not cruft: 

1344 print() 

1345 

1346 # Check source dependencies (Build-Depends, Build-Depends-Arch, Build-Depends-Indep) 

1347 all_broken_bd: dict[str, set[str]] = defaultdict(set) 

1348 metakey_bd = get_or_set_metadatakey("Build-Depends", session) 

1349 metakey_bda = get_or_set_metadatakey("Build-Depends-Arch", session) 

1350 metakey_bdi = get_or_set_metadatakey("Build-Depends-Indep", session) 

1351 metakey_ids: list[int] 

1352 if include_arch_all: 

1353 metakey_ids = [metakey_bd.key_id, metakey_bda.key_id, metakey_bdi.key_id] 

1354 else: 

1355 metakey_ids = [metakey_bd.key_id, metakey_bda.key_id] 

1356 

1357 params = { 

1358 "suite_id": dbsuite.suite_id, 

1359 "metakey_ids": metakey_ids, 

1360 } 

1361 statement = sql.text( 

1362 """ 

1363 SELECT s.source, replace(string_agg(trim(sm.value), ', '), ',,', ',') as build_dep 

1364 FROM source s 

1365 JOIN source_metadata sm ON s.id = sm.src_id 

1366 WHERE s.id in 

1367 (SELECT src FROM newest_src_association 

1368 WHERE suite = :suite_id) 

1369 AND sm.key_id = ANY(:metakey_ids) 

1370 GROUP BY s.id, s.source""" 

1371 ) 

1372 query = session.execute(statement, params) 

1373 for source, build_dep in query: 

1374 if source in removals: 

1375 continue 

1376 parsed_dep = [] 

1377 if build_dep is not None: 1377 ↛ 1384line 1377 didn't jump to line 1384 because the condition on line 1377 was always true

1378 # Remove [arch] information since we want to see breakage on all arches 

1379 build_dep = re_build_dep_arch.sub("", build_dep) 

1380 try: 

1381 parsed_dep = apt_pkg.parse_src_depends(build_dep) 

1382 except ValueError as e: 

1383 print("Error for source %s: %s" % (source, e)) 

1384 for dep in parsed_dep: 

1385 unsat = 0 

1386 for dep_package, _, _ in dep: 

1387 if dep_package in removals: 

1388 unsat += 1 

1389 if unsat == len(dep): 

1390 q = ( 

1391 select(Component.component_name) 

1392 .join(Component.overrides) 

1393 .where(Override.suite == overridesuite) 

1394 .where( 

1395 Override.package 

1396 == re.sub("/(contrib|non-free-firmware|non-free)$", "", source) 

1397 ) 

1398 .join(Override.overridetype) 

1399 .where(OverrideType.overridetype == "dsc") 

1400 ) 

1401 component = session.execute(q).scalar_one_or_none() 

1402 key = source 

1403 if component != "main": 1403 ↛ 1404line 1403 didn't jump to line 1404 because the condition on line 1403 was never true

1404 key = "%s/%s" % (source, component) 

1405 all_broken_bd[key].add(pp_deps(dep)) 

1406 dep_problem = True 

1407 

1408 if all_broken_bd and not quiet: 

1409 if cruft: 1409 ↛ 1410line 1409 didn't jump to line 1410 because the condition on line 1409 was never true

1410 print(" - broken Build-Depends:") 

1411 else: 

1412 print("# Broken Build-Depends:") 

1413 for source, bdeps in sorted(all_broken_bd.items()): 

1414 sorted_bdeps = sorted(bdeps) 

1415 if cruft: 1415 ↛ 1416line 1415 didn't jump to line 1416 because the condition on line 1415 was never true

1416 print(" %s: %s" % (source, sorted_bdeps[0])) 

1417 else: 

1418 print("%s: %s" % (source, sorted_bdeps[0])) 

1419 for bdep in sorted_bdeps[1:]: 1419 ↛ 1420line 1419 didn't jump to line 1420 because the loop on line 1419 never started

1420 if cruft: 

1421 print(" " + " " * (len(source) + 2) + bdep) 

1422 else: 

1423 print(" " * (len(source) + 2) + bdep) 

1424 if not cruft: 1424 ↛ 1427line 1424 didn't jump to line 1427 because the condition on line 1424 was always true

1425 print() 

1426 

1427 return dep_problem 

1428 

1429 

1430################################################################################ 

1431 

1432 

1433def parse_built_using(control: Mapping[str, str]) -> list[tuple[str, str]]: 

1434 """source packages referenced via Built-Using 

1435 

1436 :param control: control file to take Built-Using field from 

1437 :return: list of (source_name, source_version) pairs 

1438 """ 

1439 built_using = control.get("Built-Using", None) 

1440 if built_using is None: 

1441 return [] 

1442 

1443 bu = [] 

1444 for dep in apt_pkg.parse_depends(built_using): 

1445 assert len(dep) == 1, "Alternatives are not allowed in Built-Using field" 

1446 source_name, source_version, comp = dep[0] 

1447 assert comp == "=", "Built-Using must contain strict dependencies" 

1448 bu.append((source_name, source_version)) 

1449 

1450 return bu 

1451 

1452 

1453################################################################################ 

1454 

1455 

1456def is_in_debug_section(control: Mapping[str, str] | MetadataProxy) -> bool: 

1457 """binary package is a debug package 

1458 

1459 :param control: control file of binary package 

1460 :return: True if the binary package is a debug package 

1461 """ 

1462 section = control["Section"].split("/", 1)[-1] 

1463 auto_built_package = control.get("Auto-Built-Package") 

1464 return section == "debug" and auto_built_package == "debug-symbols" 

1465 

1466 

1467################################################################################ 

1468 

1469 

1470def find_possibly_compressed_file(filename: str) -> str: 

1471 """ 

1472 

1473 :param filename: path to a control file (Sources, Packages, etc) to 

1474 look for 

1475 :return: path to the (possibly compressed) control file, or null if the 

1476 file doesn't exist 

1477 """ 

1478 _compressions = ("", ".xz", ".gz", ".bz2") 

1479 

1480 for ext in _compressions: 1480 ↛ 1485line 1480 didn't jump to line 1485 because the loop on line 1480 didn't complete

1481 _file = filename + ext 

1482 if os.path.exists(_file): 

1483 return _file 

1484 

1485 raise OSError(errno.ENOENT, os.strerror(errno.ENOENT), filename) 

1486 

1487 

1488################################################################################ 

1489 

1490 

1491def parse_boolean_from_user(value: str) -> bool: 

1492 value = value.lower() 

1493 if value in {"yes", "true", "enable", "enabled"}: 

1494 return True 

1495 if value in {"no", "false", "disable", "disabled"}: 1495 ↛ 1497line 1495 didn't jump to line 1497 because the condition on line 1495 was always true

1496 return False 

1497 raise ValueError("Not sure whether %s should be a True or a False" % value) 

1498 

1499 

1500_DURATION_RE = re.compile(r"(?P<amount>\d+)\s*(?P<unit>[hms])", re.IGNORECASE) 

1501 

1502 

1503def parse_duration(value: str) -> datetime.timedelta: 

1504 """Parse duration from strings like "1h", "30m", or "1h 15m 10s".""" 

1505 value = value.strip() 

1506 if not value: 

1507 raise ValueError("Duration must be non-empty") 

1508 

1509 total_seconds = 0 

1510 for match in _DURATION_RE.finditer(value): 

1511 amount = int(match.group("amount")) 

1512 unit = match.group("unit").lower() 

1513 if unit == "h": 

1514 total_seconds += amount * 3600 

1515 elif unit == "m": 

1516 total_seconds += amount * 60 

1517 else: 

1518 total_seconds += amount 

1519 

1520 remainder = _DURATION_RE.sub("", value).strip(" ,") 

1521 if remainder: 

1522 raise ValueError("Invalid duration: %s" % value) 

1523 if total_seconds <= 0: 

1524 raise ValueError("Duration must be greater than zero") 

1525 return datetime.timedelta(seconds=total_seconds) 

1526 

1527 

1528def suite_suffix(suite_name: str) -> str: 

1529 """Return suite_suffix for the given suite""" 

1530 suffix = Cnf.find("Dinstall::SuiteSuffix", "") 

1531 if suffix == "": 1531 ↛ 1533line 1531 didn't jump to line 1533 because the condition on line 1531 was always true

1532 return "" 

1533 elif "Dinstall::SuiteSuffixSuites" not in Cnf: 

1534 # TODO: warn (once per run) that SuiteSuffix will be deprecated in the future 

1535 return suffix 

1536 elif suite_name in Cnf.value_list("Dinstall::SuiteSuffixSuites"): 

1537 return suffix 

1538 return "" 

1539 

1540 

1541################################################################################ 

1542 

1543 

1544def process_buildinfos( 

1545 directory: str, 

1546 buildinfo_files: "Iterable[daklib.upload.HashedFile]", 

1547 fs_transaction: "daklib.fstransactions.FilesystemTransaction", 

1548 logger: "daklib.daklog.Logger", 

1549) -> None: 

1550 """Copy buildinfo files into Dir::BuildinfoArchive 

1551 

1552 :param directory: directory where .changes is stored 

1553 :param buildinfo_files: names of buildinfo files 

1554 :param fs_transaction: FilesystemTransaction instance 

1555 :param logger: logger instance 

1556 """ 

1557 

1558 if "Dir::BuildinfoArchive" not in Cnf: 

1559 return 

1560 

1561 target_dir = os.path.join( 

1562 Cnf["Dir::BuildinfoArchive"], 

1563 datetime.datetime.now(tz=datetime.UTC).strftime("%Y/%m/%d"), 

1564 ) 

1565 

1566 for f in buildinfo_files: 

1567 src = os.path.join(directory, f.filename) 

1568 dst = find_next_free(os.path.join(target_dir, f.filename)) 

1569 

1570 logger.log(["Archiving", f.filename]) 

1571 fs_transaction.copy(src, dst, mode=0o644) 

1572 

1573 

1574################################################################################ 

1575 

1576 

1577def move_to_morgue( 

1578 morguesubdir: str, 

1579 filenames: Iterable[str], 

1580 fs_transaction: "daklib.fstransactions.FilesystemTransaction", 

1581 logger: "daklib.daklog.Logger", 

1582) -> None: 

1583 """Move a file to the correct dir in morgue 

1584 

1585 :param morguesubdir: subdirectory of morgue where this file needs to go 

1586 :param filenames: names of files 

1587 :param fs_transaction: FilesystemTransaction instance 

1588 :param logger: logger instance 

1589 """ 

1590 

1591 assert Cnf["Dir::Base"] 

1592 morguedir = Cnf.get("Dir::Morgue", os.path.join(Cnf["Dir::Base"], "morgue")) 

1593 

1594 # Build directory as morguedir/morguesubdir/year/month/day 

1595 now = datetime.datetime.now(tz=datetime.UTC) 

1596 dest = os.path.join( 

1597 morguedir, morguesubdir, str(now.year), "%.2d" % now.month, "%.2d" % now.day 

1598 ) 

1599 

1600 for filename in filenames: 

1601 dest_filename = dest + "/" + os.path.basename(filename) 

1602 # If the destination file exists; try to find another filename to use 

1603 if os.path.lexists(dest_filename): 1603 ↛ 1604line 1603 didn't jump to line 1604 because the condition on line 1603 was never true

1604 dest_filename = find_next_free(dest_filename) 

1605 logger.log(["move to morgue", filename, dest_filename]) 

1606 fs_transaction.move(filename, dest_filename) 

1607 

1608 

1609################################################################################ 

1610 

1611 

1612def resolve_relative_path(base_path: StrPath, relative_path: StrPath) -> Path: 

1613 """Resolve absolute path joining base_path and relative_path 

1614 

1615 Raises: 

1616 ValueError: when the resolved path is not relative to base_path 

1617 """ 

1618 base = Path(base_path).resolve() 

1619 path = (base / relative_path).resolve() 

1620 

1621 if not path.is_relative_to(base): 1621 ↛ 1622line 1621 didn't jump to line 1622 because the condition on line 1621 was never true

1622 raise ValueError(f"Path {relative_path} is not relative to {base_path}: {path}") 

1623 

1624 return path 

1625 

1626 

1627################################################################################ 

1628 

1629 

1630def remove_unsafe_symlinks(base_path: StrPath) -> None: 

1631 """Remove all unsafe symlinks below base_path""" 

1632 base = Path(base_path).resolve() 

1633 for dirpath, _, filenames in base.walk(): 

1634 for filename in filenames: 

1635 current_dir = base / dirpath 

1636 path = current_dir / filename 

1637 if not path.is_symlink(): 1637 ↛ 1639line 1637 didn't jump to line 1639 because the condition on line 1637 was always true

1638 continue 

1639 target = (current_dir / path.readlink()).resolve() 

1640 if not target.is_relative_to(base): 

1641 path.unlink()