Coverage for dak/rm.py: 71%
175 statements
« prev ^ index » next coverage.py v7.6.0, created at 2026-11-21 08:51 +0000
« prev ^ index » next coverage.py v7.6.0, created at 2026-11-21 08:51 +0000
1"""General purpose package removal tool for ftpmaster"""
3# Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006 James Troup <james@nocrew.org>
4# Copyright (C) 2010 Alexander Reichle-Schmehl <tolimar@debian.org>
6# This program is free software; you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation; either version 2 of the License, or
9# (at your option) any later version.
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20################################################################################
22# o OpenBSD team wants to get changes incorporated into IPF. Darren no
23# respond.
24# o Ask again -> No respond. Darren coder supreme.
25# o OpenBSD decide to make changes, but only in OpenBSD source
26# tree. Darren hears, gets angry! Decides: "LICENSE NO ALLOW!"
27# o Insert Flame War.
28# o OpenBSD team decide to switch to different packet filter under BSD
29# license. Because Project Goal: Every user should be able to make
30# changes to source tree. IPF license bad!!
31# o Darren try get back: says, NetBSD, FreeBSD allowed! MUAHAHAHAH!!!
32# o Theo say: no care, pf much better than ipf!
33# o Darren changes mind: changes license. But OpenBSD will not change
34# back to ipf. Darren even much more bitter.
35# o Darren so bitterbitter. Decides: I'LL GET BACK BY FORKING OPENBSD AND
36# RELEASING MY OWN VERSION. HEHEHEHEHE.
38# http://slashdot.org/comments.pl?sid=26697&cid=2883271
40################################################################################
42import functools
43import sys
44from collections import defaultdict
45from typing import TYPE_CHECKING, NoReturn
47import apt_pkg
48from sqlalchemy import sql
50from daklib import utils
51from daklib.config import Config
52from daklib.dbconn import DBConn, get_maintainer, get_suite
53from daklib.rm import remove
55if TYPE_CHECKING:
56 from sqlalchemy.orm import Session
58################################################################################
60Options: apt_pkg.Configuration
62################################################################################
65def usage(exit_code=0) -> NoReturn:
66 print(
67 """Usage: dak rm [OPTIONS] PACKAGE[...]
68Remove PACKAGE(s) from suite(s).
70 -A, --no-arch-all-rdeps Do not report breaking arch:all packages
71 or Build-Depends-Indep
72 -a, --architecture=ARCH only act on this architecture
73 -b, --binary PACKAGE are binary packages to remove
74 -B, --binary-only remove binaries only
75 --binary-version=VER only remove packages with binary version VER
76 (can be a comma-separated list)
77 --keep-binary-version=VER
78 never remove packages with binary version VER
79 (can be a comma-separated list)
80 -c, --component=COMPONENT act on this component
81 -C, --carbon-copy=EMAIL send a CC of removal message to EMAIL
82 -d, --done=BUG# send removal message as closure to bug#
83 -D, --do-close also close all bugs associated to that package
84 -h, --help show this help and exit
85 -m, --reason=MSG reason for removal
86 -n, --no-action don't do anything
87 -o, --outdated remove only outdated sources or binaries that were
88 built from previous source versions
89 -p, --partial don't affect override files
90 -R, --rdep-check check reverse dependencies
91 -s, --suite=SUITE act on this suite
92 -S, --source-only remove source only
93 --source-version=VER only remove packages with source version VER
94 (can be a comma-separated list)
95 --keep-source-version=VER
96 never remove packages with source version VER
97 (can be a comma-separated list)
99ARCH, BUG#, COMPONENT, SUITE and VER can be comma (or space) separated lists, e.g.
100 --architecture=amd64,i386"""
101 )
103 sys.exit(exit_code)
106################################################################################
108# "Hudson: What that's great, that's just fucking great man, now what
109# the fuck are we supposed to do? We're in some real pretty shit now
110# man...That's it man, game over man, game over, man! Game over! What
111# the fuck are we gonna do now? What are we gonna do?"
114def game_over() -> None:
115 answer = utils.input_or_exit("Continue (y/N)? ").lower()
116 if answer != "y": 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true
117 print("Aborted.")
118 sys.exit(1)
121################################################################################
124def reverse_depends_check(
125 removals: list[str],
126 suite: str,
127 arches: list[str] | None,
128 session: "Session",
129 include_arch_all: bool,
130) -> None:
131 print("Checking reverse dependencies...")
132 if utils.check_reverse_depends( 132 ↛ 135line 132 didn't jump to line 135 because the condition on line 132 was never true
133 removals, suite, arches, session, include_arch_all=include_arch_all
134 ):
135 print("Dependency problem found.")
136 if not Options["No-Action"]:
137 game_over()
138 else:
139 print("No dependency problem found.")
140 print()
143################################################################################
146def main() -> None:
147 global Options
149 cnf = Config()
151 Arguments = [
152 ("h", "help", "Rm::Options::Help"),
153 ("A", "no-arch-all-rdeps", "Rm::Options::NoArchAllRdeps"),
154 ("a", "architecture", "Rm::Options::Architecture", "HasArg"),
155 ("b", "binary", "Rm::Options::Binary"),
156 ("B", "binary-only", "Rm::Options::Binary-Only"),
157 ("\0", "binary-version", "Rm::Options::Binary-Version", "HasArg"),
158 ("\0", "keep-binary-version", "Rm::Options::Keep-Binary-Version", "HasArg"),
159 ("c", "component", "Rm::Options::Component", "HasArg"),
160 ("C", "carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
161 ("d", "done", "Rm::Options::Done", "HasArg"), # Bugs fixed
162 ("D", "do-close", "Rm::Options::Do-Close"),
163 ("R", "rdep-check", "Rm::Options::Rdep-Check"),
164 (
165 "m",
166 "reason",
167 "Rm::Options::Reason",
168 "HasArg",
169 ), # Hysterical raisins; -m is old-dinstall option for rejection reason
170 ("n", "no-action", "Rm::Options::No-Action"),
171 ("o", "outdated", "Rm::Options::Outdated"),
172 ("p", "partial", "Rm::Options::Partial"),
173 ("s", "suite", "Rm::Options::Suite", "HasArg"),
174 ("S", "source-only", "Rm::Options::Source-Only"),
175 ("\0", "source-version", "Rm::Options::Source-Version", "HasArg"),
176 ("\0", "keep-source-version", "Rm::Options::Keep-Source-Version", "HasArg"),
177 ]
179 for i in [
180 "NoArchAllRdeps",
181 "architecture",
182 "binary",
183 "binary-only",
184 "carbon-copy",
185 "component",
186 "done",
187 "help",
188 "no-action",
189 "outdated",
190 "partial",
191 "rdep-check",
192 "reason",
193 "source-only",
194 "Do-Close",
195 ]:
196 key = "Rm::Options::%s" % (i)
197 if key not in cnf: 197 ↛ 179line 197 didn't jump to line 179
198 cnf[key] = ""
199 if "Rm::Options::Suite" not in cnf: 199 ↛ 202line 199 didn't jump to line 202 because the condition on line 199 was always true
200 cnf["Rm::Options::Suite"] = "unstable"
202 arguments = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv) # type: ignore[attr-defined]
203 Options = cnf.subtree("Rm::Options")
205 if Options["Help"]:
206 usage()
208 session = DBConn().session()
210 # Sanity check options
211 if not arguments: 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true
212 utils.fubar("need at least one package name as an argument.")
213 if Options["Architecture"] and Options["Source-Only"]: 213 ↛ 214line 213 didn't jump to line 214 because the condition on line 213 was never true
214 utils.fubar(
215 "can't use -a/--architecture and -S/--source-only options simultaneously."
216 )
217 actions = [Options["Binary"], Options["Binary-Only"], Options["Source-Only"]]
218 nr_actions = len([act for act in actions if act])
219 if nr_actions > 1: 219 ↛ 220line 219 didn't jump to line 220 because the condition on line 219 was never true
220 utils.fubar(
221 "Only one of -b/--binary, -B/--binary-only and -S/--source-only can be used."
222 )
223 if Options["Architecture"] and not Options["Partial"]: 223 ↛ 224line 223 didn't jump to line 224 because the condition on line 223 was never true
224 utils.warn("-a/--architecture implies -p/--partial.")
225 Options["Partial"] = "true" # type: ignore[index]
226 if Options["Outdated"] and not Options["Partial"]: 226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true
227 utils.warn("-o/--outdated implies -p/--partial.")
228 Options["Partial"] = "true" # type: ignore[index]
229 if Options["Do-Close"] and not Options["Done"]: 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true
230 utils.fubar("-D/--do-close needs -d/--done (bugnr).")
231 if Options["Do-Close"] and ( 231 ↛ 234line 231 didn't jump to line 234 because the condition on line 231 was never true
232 Options["Binary"] or Options["Binary-Only"] or Options["Source-Only"]
233 ):
234 utils.fubar(
235 "-D/--do-close cannot be used with -b/--binary, -B/--binary-only or -S/--source-only."
236 )
238 # Force the admin to tell someone if we're not doing a 'dak
239 # cruft-report' inspired removal (or closing a bug, which counts
240 # as telling someone).
241 if ( 241 ↛ 248line 241 didn't jump to line 248
242 not Options["No-Action"]
243 and not Options["Carbon-Copy"]
244 and not Options["Done"]
245 and Options["Reason"].find("[auto-cruft]") == -1
246 and Options["Reason"].find("[cruft]") == -1
247 ):
248 utils.fubar(
249 "Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal."
250 )
252 parameters: dict[str, object] = {
253 "binary_versions": utils.split_args_or_none(Options.get("Binary-Version", "")),
254 "source_versions": utils.split_args_or_none(Options.get("Source-Version", "")),
255 "keep_binary_versions": utils.split_args_or_none(
256 Options.get("Keep-Binary-Version", "")
257 ),
258 "keep_source_versions": utils.split_args_or_none(
259 Options.get("Keep-Source-Version", "")
260 ),
261 }
263 if Options["Binary"]: 263 ↛ 264line 263 didn't jump to line 264 because the condition on line 263 was never true
264 con_packages = "AND b.package = ANY(:packages)"
265 parameters["packages"] = arguments
266 else:
267 con_packages = "AND s.source = ANY(:sources)"
268 parameters["sources"] = arguments
270 (con_suites, con_architectures, con_components, check_source, parse_parameters) = (
271 utils.parse_args(Options)
272 )
273 parameters.update(parse_parameters)
275 # Additional suite checks
276 suite_ids_list = []
277 whitelists = []
278 suites = utils.split_args(Options["Suite"])
279 suites_list = utils.join_with_commas_and(suites)
280 if not Options["No-Action"]:
281 for suite in suites:
282 s = get_suite(suite, session=session)
283 if s is not None: 283 ↛ 286line 283 didn't jump to line 286 because the condition on line 283 was always true
284 suite_ids_list.append(s.suite_id)
285 whitelists.append(s.mail_whitelist)
286 if suite in ("oldstable", "stable"): 286 ↛ 287line 286 didn't jump to line 287 because the condition on line 286 was never true
287 print("**WARNING** About to remove from the (old)stable suite!")
288 print(
289 "This should only be done just prior to a (point) release and not at"
290 )
291 print("any other time.")
292 game_over()
293 elif suite == "testing": 293 ↛ 294line 293 didn't jump to line 294 because the condition on line 293 was never true
294 print("**WARNING About to remove from the testing suite!")
295 print(
296 "There's no need to do this normally as removals from unstable will"
297 )
298 print("propogate to testing automagically.")
299 game_over()
301 # Additional architecture checks
302 if Options["Architecture"] and check_source: 302 ↛ 303line 302 didn't jump to line 303 because the condition on line 302 was never true
303 utils.warn("'source' in -a/--argument makes no sense and is ignored.")
305 # Don't do dependency checks on multiple suites
306 if Options["Rdep-Check"] and len(suites) > 1: 306 ↛ 307line 306 didn't jump to line 307 because the condition on line 306 was never true
307 utils.fubar("Reverse dependency check on multiple suites is not implemented.")
309 q_outdated = "TRUE"
310 if Options["Outdated"]: 310 ↛ 311line 310 didn't jump to line 311 because the condition on line 310 was never true
311 q_outdated = "s.version < newest_source.version"
313 to_remove: list[tuple[str, str, str, int, int, str, str, str]] = []
314 maintainers: set[int] = set()
316 # We have 3 modes of package selection: binary, source-only, binary-only
317 # and source+binary.
319 if Options["Binary"]: 319 ↛ 321line 319 didn't jump to line 321 because the condition on line 319 was never true
320 # Removal by binary package name
321 q = session.execute(
322 sql.text(
323 """
324 SELECT b.package, b.version, a.arch_string, b.id, b.maintainer, s.source,
325 s.version as source_version, newest_source.version as newest_sversion
326 FROM binaries b
327 JOIN source s ON s.id = b.source
328 JOIN bin_associations ba ON ba.bin = b.id
329 JOIN architecture a ON a.id = b.architecture
330 JOIN suite su ON su.id = ba.suite
331 JOIN files f ON f.id = b.file
332 JOIN files_archive_map af ON af.file_id = f.id AND af.archive_id = su.archive_id
333 JOIN component c ON c.id = af.component_id
334 LEFT JOIN newest_source on s.source = newest_source.source AND su.id = newest_source.suite
335 WHERE
336 (CAST(:binary_versions AS debversion[]) IS NULL OR b.version = ANY(CAST(:binary_versions AS debversion[])))
337 AND (CAST(:source_versions AS debversion[]) IS NULL OR s.version = ANY(CAST(:source_versions AS debversion[])))
338 AND (CAST(:keep_binary_versions AS debversion[]) IS NULL OR b.version != ALL(CAST(:keep_binary_versions AS debversion[])))
339 AND (CAST(:keep_source_versions AS debversion[]) IS NULL OR s.version != ALL(CAST(:keep_source_versions AS debversion[])))
340 AND %s %s %s %s %s
341 """
342 % (
343 q_outdated,
344 con_packages,
345 con_suites,
346 con_components,
347 con_architectures,
348 )
349 ),
350 parameters,
351 )
352 to_remove.extend(q) # type: ignore[arg-type]
353 else:
354 # Source-only
355 if not Options["Binary-Only"]: 355 ↛ 379line 355 didn't jump to line 379 because the condition on line 355 was always true
356 q = session.execute(
357 sql.text(
358 """
359 SELECT s.source, s.version, 'source', s.id, s.maintainer, s.source,
360 s.version as source_version, newest_source.version as newest_sversion
361 FROM source s
362 JOIN src_associations sa ON sa.source = s.id
363 JOIN suite su ON su.id = sa.suite
364 JOIN archive ON archive.id = su.archive_id
365 JOIN files f ON f.id = s.file
366 JOIN files_archive_map af ON af.file_id = f.id AND af.archive_id = su.archive_id
367 JOIN component c ON c.id = af.component_id
368 LEFT JOIN newest_source on s.source = newest_source.source AND su.id = newest_source.suite
369 WHERE
370 (CAST(:source_versions AS debversion[]) IS NULL OR s.version = ANY(CAST(:source_versions AS debversion[])))
371 AND (CAST(:keep_source_versions AS debversion[]) IS NULL OR s.version != ALL(CAST(:keep_source_versions AS debversion[])))
372 AND %s %s %s %s
373 """
374 % (q_outdated, con_packages, con_suites, con_components)
375 ),
376 parameters,
377 )
378 to_remove.extend(q) # type: ignore[arg-type]
379 if not Options["Source-Only"]: 379 ↛ 414line 379 didn't jump to line 414 because the condition on line 379 was always true
380 # Source + Binary
381 q = session.execute(
382 sql.text(
383 """
384 SELECT b.package, b.version, a.arch_string, b.id, b.maintainer, s.source,
385 s.version as source_version, newest_source.version as newest_sversion
386 FROM binaries b
387 JOIN bin_associations ba ON b.id = ba.bin
388 JOIN architecture a ON b.architecture = a.id
389 JOIN suite su ON ba.suite = su.id
390 JOIN archive ON archive.id = su.archive_id
391 JOIN files_archive_map af ON b.file = af.file_id AND af.archive_id = archive.id
392 JOIN component c ON af.component_id = c.id
393 JOIN source s ON b.source = s.id
394 LEFT JOIN newest_source on s.source = newest_source.source AND su.id = newest_source.suite
395 WHERE
396 (CAST(:binary_versions AS debversion[]) IS NULL OR b.version = ANY(CAST(:binary_versions AS debversion[])))
397 AND (CAST(:source_versions AS debversion[]) IS NULL OR s.version = ANY(CAST(:source_versions AS debversion[])))
398 AND (CAST(:keep_binary_versions AS debversion[]) IS NULL OR b.version != ALL(CAST(:keep_binary_versions AS debversion[])))
399 AND (CAST(:keep_source_versions AS debversion[]) IS NULL OR s.version != ALL(CAST(:keep_source_versions AS debversion[])))
400 AND %s %s %s %s %s
401 """
402 % (
403 q_outdated,
404 con_packages,
405 con_suites,
406 con_components,
407 con_architectures,
408 )
409 ),
410 parameters,
411 )
412 to_remove.extend(q) # type: ignore[arg-type]
414 if not to_remove: 414 ↛ 415line 414 didn't jump to line 415 because the condition on line 414 was never true
415 print("Nothing to do.")
416 sys.exit(0)
418 # Process -C/--carbon-copy
419 #
420 # Accept 3 types of arguments (space separated):
421 # 1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
422 # 2) the keyword 'package' - cc's $package@packages.debian.org for every argument
423 # 3) contains a '@' - assumed to be an email address, used unmodified
424 #
425 carbon_copy = []
426 for copy_to in utils.split_args(Options.get("Carbon-Copy", "")):
427 if copy_to.isdigit(): 427 ↛ 428line 427 didn't jump to line 428 because the condition on line 427 was never true
428 if "Dinstall::BugServer" in cnf:
429 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
430 else:
431 utils.fubar(
432 "Asked to send mail to #%s in BTS but Dinstall::BugServer is not configured"
433 % copy_to
434 )
435 elif copy_to == "package": 435 ↛ 436line 435 didn't jump to line 436 because the condition on line 435 was never true
436 for package in {s[5] for s in to_remove}:
437 if "Dinstall::PackagesServer" in cnf:
438 carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
439 elif "@" in copy_to: 439 ↛ 442line 439 didn't jump to line 442 because the condition on line 439 was always true
440 carbon_copy.append(copy_to)
441 else:
442 utils.fubar(
443 "Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address."
444 % (copy_to)
445 )
447 # If we don't have a reason; spawn an editor so the user can add one
448 # Write the rejection email out as the <foo>.reason file
449 if not Options["Reason"] and not Options["No-Action"]: 449 ↛ 450line 449 didn't jump to line 450 because the condition on line 449 was never true
450 Options["Reason"] = utils.call_editor() # type: ignore[index]
452 # Generate the summary of what's to be removed
453 d: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list))
454 for j in to_remove:
455 package = j[0]
456 version = j[1]
457 architecture = j[2]
458 maintainer = j[4]
459 maintainers.add(maintainer)
460 # source = j[5]
461 # source_version = j[6]
462 # source_newest = j[7]
463 if architecture not in d[package][version]: 463 ↛ 454line 463 didn't jump to line 454 because the condition on line 463 was always true
464 d[package][version].append(architecture)
466 maintainer_list = []
467 for maintainer_id in maintainers:
468 m = get_maintainer(maintainer_id, session=session)
469 assert m is not None
470 maintainer_list.append(m.name)
471 summary = ""
472 removals = sorted(d)
473 for package in removals:
474 versions = sorted(d[package], key=functools.cmp_to_key(apt_pkg.version_compare))
475 for version in versions:
476 d[package][version].sort(key=utils.ArchKey)
477 summary += "%10s | %10s | %s\n" % (
478 package,
479 version,
480 ", ".join(d[package][version]),
481 )
482 print("Will remove the following packages from %s:" % (suites_list))
483 print()
484 print(summary)
485 print("Maintainer: %s" % ", ".join(maintainer_list))
486 if Options["Done"]:
487 print("Will also close bugs: " + Options["Done"])
488 if carbon_copy:
489 print("Will also send CCs to: " + ", ".join(carbon_copy))
490 if Options["Do-Close"]: 490 ↛ 491line 490 didn't jump to line 491 because the condition on line 490 was never true
491 print("Will also close associated bug reports.")
492 print()
493 print("------------------- Reason -------------------")
494 print(Options["Reason"])
495 print("----------------------------------------------")
496 print()
498 if Options["Rdep-Check"]:
499 arches = utils.split_args(Options["Architecture"])
500 include_arch_all = Options["NoArchAllRdeps"] == ""
501 check_all_arches = include_arch_all and "all" in arches
502 # when arches is None, rdeps are checked on all arches in the suite
503 reverse_depends_check(
504 removals,
505 suites[0],
506 arches if not check_all_arches else None,
507 session,
508 include_arch_all=include_arch_all,
509 )
511 # If -n/--no-action, drop out here
512 if Options["No-Action"]:
513 sys.exit(0)
515 print("Going to remove the packages now.")
516 game_over()
518 # Do the actual deletion
519 print("Deleting...", end=" ")
520 sys.stdout.flush()
522 bugs = utils.split_args(Options["Done"])
523 remove(
524 session,
525 Options["Reason"],
526 suites,
527 [j[0:4] for j in to_remove],
528 partial=bool(Options["Partial"]),
529 components=utils.split_args(Options["Component"]),
530 done_bugs=bugs,
531 carbon_copy=carbon_copy,
532 close_related_bugs=bool(Options["Do-Close"]),
533 )
535 print("done.")