]> git.decadent.org.uk Git - dak.git/blob - dak/rm.py
Merge remote-tracking branch 'drkranz/rm' into merge
[dak.git] / dak / rm.py
1 #!/usr/bin/env python
2
3 """ General purpose package removal tool for ftpmaster """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
5 # Copyright (C) 2010 Alexander Reichle-Schmehl <tolimar@debian.org>
6
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 ################################################################################
22
23 # o OpenBSD team wants to get changes incorporated into IPF. Darren no
24 #    respond.
25 # o Ask again -> No respond. Darren coder supreme.
26 # o OpenBSD decide to make changes, but only in OpenBSD source
27 #    tree. Darren hears, gets angry! Decides: "LICENSE NO ALLOW!"
28 # o Insert Flame War.
29 # o OpenBSD team decide to switch to different packet filter under BSD
30 #    license. Because Project Goal: Every user should be able to make
31 #    changes to source tree. IPF license bad!!
32 # o Darren try get back: says, NetBSD, FreeBSD allowed! MUAHAHAHAH!!!
33 # o Theo say: no care, pf much better than ipf!
34 # o Darren changes mind: changes license. But OpenBSD will not change
35 #    back to ipf. Darren even much more bitter.
36 # o Darren so bitterbitter. Decides: I'LL GET BACK BY FORKING OPENBSD AND
37 #    RELEASING MY OWN VERSION. HEHEHEHEHE.
38
39 #                        http://slashdot.org/comments.pl?sid=26697&cid=2883271
40
41 ################################################################################
42
43 import commands
44 import os
45 import sys
46 import apt_pkg
47 import apt_inst
48 from re import sub
49
50 from daklib.config import Config
51 from daklib.dbconn import *
52 from daklib import utils
53 from daklib.dak_exceptions import *
54 from daklib.regexes import re_strip_source_version, re_build_dep_arch, re_bin_only_nmu
55 import debianbts as bts
56
57 ################################################################################
58
59 Options = None
60
61 ################################################################################
62
63 def usage (exit_code=0):
64     print """Usage: dak rm [OPTIONS] PACKAGE[...]
65 Remove PACKAGE(s) from suite(s).
66
67   -a, --architecture=ARCH    only act on this architecture
68   -b, --binary               remove binaries only
69   -c, --component=COMPONENT  act on this component
70   -C, --carbon-copy=EMAIL    send a CC of removal message to EMAIL
71   -d, --done=BUG#            send removal message as closure to bug#
72   -D, --do-close             also close all bugs associated to that package
73   -h, --help                 show this help and exit
74   -m, --reason=MSG           reason for removal
75   -n, --no-action            don't do anything
76   -p, --partial              don't affect override files
77   -R, --rdep-check           check reverse dependencies
78   -s, --suite=SUITE          act on this suite
79   -S, --source-only          remove source only
80
81 ARCH, BUG#, COMPONENT and SUITE can be comma (or space) separated lists, e.g.
82     --architecture=amd64,i386"""
83
84     sys.exit(exit_code)
85
86 ################################################################################
87
88 # "Hudson: What that's great, that's just fucking great man, now what
89 #  the fuck are we supposed to do? We're in some real pretty shit now
90 #  man...That's it man, game over man, game over, man! Game over! What
91 #  the fuck are we gonna do now? What are we gonna do?"
92
93 def game_over():
94     answer = utils.our_raw_input("Continue (y/N)? ").lower()
95     if answer != "y":
96         print "Aborted."
97         sys.exit(1)
98
99 ################################################################################
100
101 def reverse_depends_check(removals, suite, arches=None, session=None):
102     dbsuite = get_suite(suite, session)
103     cnf = Config()
104
105     print "Checking reverse dependencies..."
106     dep_problem = 0
107     p2c = {}
108     all_broken = {}
109     if arches:
110         all_arches = set(arches)
111     else:
112         all_arches = set([x.arch_string for x in get_suite_architectures(suite)])
113     all_arches -= set(["source", "all"])
114     metakey_d = get_or_set_metadatakey("Depends", session)
115     metakey_p = get_or_set_metadatakey("Provides", session)
116     params = {
117         'suite_id':     dbsuite.suite_id,
118         'metakey_d_id': metakey_d.key_id,
119         'metakey_p_id': metakey_p.key_id,
120         'arch_all_id' : get_architecture('all', session).arch_id,
121     }
122     for architecture in all_arches:
123         deps = {}
124         sources = {}
125         virtual_packages = {}
126         params['arch_id'] = get_architecture(architecture, session).arch_id
127
128         statement = '''
129             WITH suite_binaries AS
130                 (select b.id, b.package, b.source, b.file
131                     from binaries b WHERE b.id in
132                         (SELECT bin FROM bin_associations WHERE suite = :suite_id)
133                         AND b.architecture in (:arch_id, :arch_all_id))
134             SELECT b.id, b.package, s.source, c.name as component,
135                 bmd.value as depends, bmp.value as provides
136                 FROM suite_binaries b
137                 LEFT OUTER JOIN binaries_metadata bmd
138                     ON b.id = bmd.bin_id AND bmd.key_id = :metakey_d_id
139                 LEFT OUTER JOIN binaries_metadata bmp
140                     ON b.id = bmp.bin_id AND bmp.key_id = :metakey_p_id
141                 JOIN source s ON b.source = s.id
142                 JOIN files f ON b.file = f.id
143                 JOIN location l ON f.location = l.id
144                 JOIN component c ON l.component = c.id'''
145         session.rollback()
146         query = session.query('id', 'package', 'source', 'component', 'depends', 'provides'). \
147             from_statement(statement).params(params)
148         for binary_id, package, source, component, depends, provides in query:
149             sources[package] = source
150             p2c[package] = component
151             if depends is not None:
152                 deps[package] = depends
153             # Maintain a counter for each virtual package.  If a
154             # Provides: exists, set the counter to 0 and count all
155             # provides by a package not in the list for removal.
156             # If the counter stays 0 at the end, we know that only
157             # the to-be-removed packages provided this virtual
158             # package.
159             if provides is not None:
160                 for virtual_pkg in provides.split(","):
161                     virtual_pkg = virtual_pkg.strip()
162                     if virtual_pkg == package: continue
163                     if not virtual_packages.has_key(virtual_pkg):
164                         virtual_packages[virtual_pkg] = 0
165                     if package not in removals:
166                         virtual_packages[virtual_pkg] += 1
167
168         # If a virtual package is only provided by the to-be-removed
169         # packages, treat the virtual package as to-be-removed too.
170         for virtual_pkg in virtual_packages.keys():
171             if virtual_packages[virtual_pkg] == 0:
172                 removals.append(virtual_pkg)
173
174         # Check binary dependencies (Depends)
175         for package in deps.keys():
176             if package in removals: continue
177             parsed_dep = []
178             try:
179                 parsed_dep += apt_pkg.ParseDepends(deps[package])
180             except ValueError, e:
181                 print "Error for package %s: %s" % (package, e)
182             for dep in parsed_dep:
183                 # Check for partial breakage.  If a package has a ORed
184                 # dependency, there is only a dependency problem if all
185                 # packages in the ORed depends will be removed.
186                 unsat = 0
187                 for dep_package, _, _ in dep:
188                     if dep_package in removals:
189                         unsat += 1
190                 if unsat == len(dep):
191                     component = p2c[package]
192                     source = sources[package]
193                     if component != "main":
194                         source = "%s/%s" % (source, component)
195                     all_broken.setdefault(source, {}).setdefault(package, set()).add(architecture)
196                     dep_problem = 1
197
198     if all_broken:
199         print "# Broken Depends:"
200         for source, bindict in sorted(all_broken.items()):
201             lines = []
202             for binary, arches in sorted(bindict.items()):
203                 if arches == all_arches:
204                     lines.append(binary)
205                 else:
206                     lines.append('%s [%s]' % (binary, ' '.join(sorted(arches))))
207             print '%s: %s' % (source, lines[0])
208             for line in lines[1:]:
209                 print ' ' * (len(source) + 2) + line
210         print
211
212     # Check source dependencies (Build-Depends and Build-Depends-Indep)
213     all_broken.clear()
214     metakey_bd = get_or_set_metadatakey("Build-Depends", session)
215     metakey_bdi = get_or_set_metadatakey("Build-Depends-Indep", session)
216     params = {
217         'suite_id':    dbsuite.suite_id,
218         'metakey_ids': (metakey_bd.key_id, metakey_bdi.key_id),
219     }
220     statement = '''
221         SELECT s.id, s.source, string_agg(sm.value, ', ') as build_dep
222            FROM source s
223            JOIN source_metadata sm ON s.id = sm.src_id
224            WHERE s.id in
225                (SELECT source FROM src_associations
226                    WHERE suite = :suite_id)
227                AND sm.key_id in :metakey_ids
228            GROUP BY s.id, s.source'''
229     query = session.query('id', 'source', 'build_dep').from_statement(statement). \
230         params(params)
231     for source_id, source, build_dep in query:
232         if source in removals: continue
233         parsed_dep = []
234         if build_dep is not None:
235             # Remove [arch] information since we want to see breakage on all arches
236             build_dep = re_build_dep_arch.sub("", build_dep)
237             try:
238                 parsed_dep += apt_pkg.ParseDepends(build_dep)
239             except ValueError, e:
240                 print "Error for source %s: %s" % (source, e)
241         for dep in parsed_dep:
242             unsat = 0
243             for dep_package, _, _ in dep:
244                 if dep_package in removals:
245                     unsat += 1
246             if unsat == len(dep):
247                 component = DBSource.get(source_id, session).get_component_name()
248                 if component != "main":
249                     source = "%s/%s" % (source, component)
250                 all_broken.setdefault(source, set()).add(utils.pp_deps(dep))
251                 dep_problem = 1
252
253     if all_broken:
254         print "# Broken Build-Depends:"
255         for source, bdeps in sorted(all_broken.items()):
256             bdeps = sorted(bdeps)
257             print '%s: %s' % (source, bdeps[0])
258             for bdep in bdeps[1:]:
259                 print ' ' * (len(source) + 2) + bdep
260         print
261
262     if dep_problem:
263         print "Dependency problem found."
264         if not Options["No-Action"]:
265             game_over()
266     else:
267         print "No dependency problem found."
268     print
269
270 ################################################################################
271
272 def main ():
273     global Options
274
275     cnf = Config()
276
277     Arguments = [('h',"help","Rm::Options::Help"),
278                  ('a',"architecture","Rm::Options::Architecture", "HasArg"),
279                  ('b',"binary", "Rm::Options::Binary-Only"),
280                  ('c',"component", "Rm::Options::Component", "HasArg"),
281                  ('C',"carbon-copy", "Rm::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
282                  ('d',"done","Rm::Options::Done", "HasArg"), # Bugs fixed
283                  ('D',"do-close","Rm::Options::Do-Close"),
284                  ('R',"rdep-check", "Rm::Options::Rdep-Check"),
285                  ('m',"reason", "Rm::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
286                  ('n',"no-action","Rm::Options::No-Action"),
287                  ('p',"partial", "Rm::Options::Partial"),
288                  ('s',"suite","Rm::Options::Suite", "HasArg"),
289                  ('S',"source-only", "Rm::Options::Source-Only"),
290                  ]
291
292     for i in [ "architecture", "binary-only", "carbon-copy", "component",
293                "done", "help", "no-action", "partial", "rdep-check", "reason",
294                "source-only", "Do-Close" ]:
295         if not cnf.has_key("Rm::Options::%s" % (i)):
296             cnf["Rm::Options::%s" % (i)] = ""
297     if not cnf.has_key("Rm::Options::Suite"):
298         cnf["Rm::Options::Suite"] = "unstable"
299
300     arguments = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
301     Options = cnf.SubTree("Rm::Options")
302
303     if Options["Help"]:
304         usage()
305
306     session = DBConn().session()
307
308     # Sanity check options
309     if not arguments:
310         utils.fubar("need at least one package name as an argument.")
311     if Options["Architecture"] and Options["Source-Only"]:
312         utils.fubar("can't use -a/--architecture and -S/--source-only options simultaneously.")
313     if Options["Binary-Only"] and Options["Source-Only"]:
314         utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.")
315     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
316         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.")
317     if Options["Architecture"] and not Options["Partial"]:
318         utils.warn("-a/--architecture implies -p/--partial.")
319         Options["Partial"] = "true"
320     if Options["Do-Close"] and not Options["Done"]:
321         utils.fubar("No.")
322     if Options["Do-Close"] and Options["Binary-Only"]:
323         utils.fubar("No.")
324     if Options["Do-Close"] and Options["Source-Only"]:
325         utils.fubar("No.")
326     if Options["Do-Close"] and Options["Suite"] != 'unstable':
327         utils.fubar("No.")
328
329     # Force the admin to tell someone if we're not doing a 'dak
330     # cruft-report' inspired removal (or closing a bug, which counts
331     # as telling someone).
332     if not Options["No-Action"] and not Options["Carbon-Copy"] \
333            and not Options["Done"] and Options["Reason"].find("[auto-cruft]") == -1:
334         utils.fubar("Need a -C/--carbon-copy if not closing a bug and not doing a cruft removal.")
335
336     # Process -C/--carbon-copy
337     #
338     # Accept 3 types of arguments (space separated):
339     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
340     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
341     #  3) contains a '@' - assumed to be an email address, used unmofidied
342     #
343     carbon_copy = []
344     for copy_to in utils.split_args(Options.get("Carbon-Copy")):
345         if copy_to.isdigit():
346             if cnf.has_key("Dinstall::BugServer"):
347                 carbon_copy.append(copy_to + "@" + cnf["Dinstall::BugServer"])
348             else:
349                 utils.fubar("Asked to send mail to #%s in BTS but Dinstall::BugServer is not configured" % copy_to)
350         elif copy_to == 'package':
351             for package in arguments:
352                 if cnf.has_key("Dinstall::PackagesServer"):
353                     carbon_copy.append(package + "@" + cnf["Dinstall::PackagesServer"])
354                 if cnf.has_key("Dinstall::TrackingServer"):
355                     carbon_copy.append(package + "@" + cnf["Dinstall::TrackingServer"])
356         elif '@' in copy_to:
357             carbon_copy.append(copy_to)
358         else:
359             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to))
360
361     if Options["Binary-Only"]:
362         field = "b.package"
363     else:
364         field = "s.source"
365     con_packages = "AND %s IN (%s)" % (field, ", ".join([ repr(i) for i in arguments ]))
366
367     (con_suites, con_architectures, con_components, check_source) = \
368                  utils.parse_args(Options)
369
370     # Additional suite checks
371     suite_ids_list = []
372     suites = utils.split_args(Options["Suite"])
373     suites_list = utils.join_with_commas_and(suites)
374     if not Options["No-Action"]:
375         for suite in suites:
376             s = get_suite(suite, session=session)
377             if s is not None:
378                 suite_ids_list.append(s.suite_id)
379             if suite in ("oldstable", "stable"):
380                 print "**WARNING** About to remove from the (old)stable suite!"
381                 print "This should only be done just prior to a (point) release and not at"
382                 print "any other time."
383                 game_over()
384             elif suite == "testing":
385                 print "**WARNING About to remove from the testing suite!"
386                 print "There's no need to do this normally as removals from unstable will"
387                 print "propogate to testing automagically."
388                 game_over()
389
390     # Additional architecture checks
391     if Options["Architecture"] and check_source:
392         utils.warn("'source' in -a/--argument makes no sense and is ignored.")
393
394     # Additional component processing
395     over_con_components = con_components.replace("c.id", "component")
396
397     # Don't do dependency checks on multiple suites
398     if Options["Rdep-Check"] and len(suites) > 1:
399         utils.fubar("Reverse dependency check on multiple suites is not implemented.")
400
401     print "Working...",
402     sys.stdout.flush()
403     to_remove = []
404     maintainers = {}
405
406     # We have 3 modes of package selection: binary-only, source-only
407     # and source+binary.  The first two are trivial and obvious; the
408     # latter is a nasty mess, but very nice from a UI perspective so
409     # we try to support it.
410
411     # XXX: TODO: This all needs converting to use placeholders or the object
412     #            API. It's an SQL injection dream at the moment
413
414     if Options["Binary-Only"]:
415         # Binary-only
416         q = session.execute("SELECT b.package, b.version, a.arch_string, b.id, b.maintainer FROM binaries b, bin_associations ba, architecture a, suite su, files f, location l, component c WHERE ba.bin = b.id AND ba.suite = su.id AND b.architecture = a.id AND b.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s %s" % (con_packages, con_suites, con_components, con_architectures))
417         for i in q.fetchall():
418             to_remove.append(i)
419     else:
420         # Source-only
421         source_packages = {}
422         q = session.execute("SELECT l.path, f.filename, s.source, s.version, 'source', s.id, s.maintainer FROM source s, src_associations sa, suite su, files f, location l, component c WHERE sa.source = s.id AND sa.suite = su.id AND s.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s" % (con_packages, con_suites, con_components))
423         for i in q.fetchall():
424             source_packages[i[2]] = i[:2]
425             to_remove.append(i[2:])
426         if not Options["Source-Only"]:
427             # Source + Binary
428             binary_packages = {}
429             # First get a list of binary package names we suspect are linked to the source
430             q = session.execute("SELECT DISTINCT b.package FROM binaries b, source s, src_associations sa, suite su, files f, location l, component c WHERE b.source = s.id AND sa.source = s.id AND sa.suite = su.id AND s.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s" % (con_packages, con_suites, con_components))
431             for i in q.fetchall():
432                 binary_packages[i[0]] = ""
433             # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
434             for i in source_packages.keys():
435                 filename = "/".join(source_packages[i])
436                 try:
437                     dsc = utils.parse_changes(filename, dsc_file=1)
438                 except CantOpenError:
439                     utils.warn("couldn't open '%s'." % (filename))
440                     continue
441                 for package in dsc.get("binary").split(','):
442                     package = package.strip()
443                     binary_packages[package] = ""
444             # Then for each binary package: find any version in
445             # unstable, check the Source: field in the deb matches our
446             # source package and if so add it to the list of packages
447             # to be removed.
448             for package in binary_packages.keys():
449                 q = session.execute("SELECT l.path, f.filename, b.package, b.version, a.arch_string, b.id, b.maintainer FROM binaries b, bin_associations ba, architecture a, suite su, files f, location l, component c WHERE ba.bin = b.id AND ba.suite = su.id AND b.architecture = a.id AND b.file = f.id AND f.location = l.id AND l.component = c.id %s %s %s AND b.package = '%s'" % (con_suites, con_components, con_architectures, package))
450                 for i in q.fetchall():
451                     filename = "/".join(i[:2])
452                     control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
453                     source = control.Find("Source", control.Find("Package"))
454                     source = re_strip_source_version.sub('', source)
455                     if source_packages.has_key(source):
456                         to_remove.append(i[2:])
457     print "done."
458
459     if not to_remove:
460         print "Nothing to do."
461         sys.exit(0)
462
463     # If we don't have a reason; spawn an editor so the user can add one
464     # Write the rejection email out as the <foo>.reason file
465     if not Options["Reason"] and not Options["No-Action"]:
466         (fd, temp_filename) = utils.temp_filename()
467         editor = os.environ.get("EDITOR","vi")
468         result = os.system("%s %s" % (editor, temp_filename))
469         if result != 0:
470             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
471         temp_file = utils.open_file(temp_filename)
472         for line in temp_file.readlines():
473             Options["Reason"] += line
474         temp_file.close()
475         os.unlink(temp_filename)
476
477     # Generate the summary of what's to be removed
478     d = {}
479     for i in to_remove:
480         package = i[0]
481         version = i[1]
482         architecture = i[2]
483         maintainer = i[4]
484         maintainers[maintainer] = ""
485         if not d.has_key(package):
486             d[package] = {}
487         if not d[package].has_key(version):
488             d[package][version] = []
489         if architecture not in d[package][version]:
490             d[package][version].append(architecture)
491
492     maintainer_list = []
493     for maintainer_id in maintainers.keys():
494         maintainer_list.append(get_maintainer(maintainer_id).name)
495     summary = ""
496     removals = d.keys()
497     removals.sort()
498     versions = []
499     for package in removals:
500         versions = d[package].keys()
501         versions.sort(apt_pkg.VersionCompare)
502         for version in versions:
503             d[package][version].sort(utils.arch_compare_sw)
504             summary += "%10s | %10s | %s\n" % (package, version, ", ".join(d[package][version]))
505     print "Will remove the following packages from %s:" % (suites_list)
506     print
507     print summary
508     print "Maintainer: %s" % ", ".join(maintainer_list)
509     if Options["Done"]:
510         print "Will also close bugs: "+Options["Done"]
511     if carbon_copy:
512         print "Will also send CCs to: " + ", ".join(carbon_copy)
513     if Options["Do-Close"]:
514         print "Will also close associated bug reports."
515     print
516     print "------------------- Reason -------------------"
517     print Options["Reason"]
518     print "----------------------------------------------"
519     print
520
521     if Options["Rdep-Check"]:
522         arches = utils.split_args(Options["Architecture"])
523         reverse_depends_check(removals, suites[0], arches, session)
524
525     # If -n/--no-action, drop out here
526     if Options["No-Action"]:
527         sys.exit(0)
528
529     print "Going to remove the packages now."
530     game_over()
531
532     whoami = utils.whoami()
533     date = commands.getoutput('date -R')
534
535     # Log first; if it all falls apart I want a record that we at least tried.
536     logfile = utils.open_file(cnf["Rm::LogFile"], 'a')
537     logfile.write("=========================================================================\n")
538     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami))
539     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary))
540     if Options["Done"]:
541         logfile.write("Closed bugs: %s\n" % (Options["Done"]))
542     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]))
543     logfile.write("----------------------------------------------\n")
544
545     # Do the same in rfc822 format
546     logfile822 = utils.open_file(cnf["Rm::LogFile822"], 'a')
547     logfile822.write("Date: %s\n" % date)
548     logfile822.write("Ftpmaster: %s\n" % whoami)
549     logfile822.write("Suite: %s\n" % suites_list)
550     sources = []
551     binaries = []
552     for package in summary.split("\n"):
553         for row in package.split("\n"):
554             element = row.split("|")
555             if len(element) == 3:
556                 if element[2].find("source") > 0:
557                     sources.append("%s_%s" % tuple(elem.strip(" ") for elem in element[:2]))
558                     element[2] = sub("source\s?,?", "", element[2]).strip(" ")
559                 if element[2]:
560                     binaries.append("%s_%s [%s]" % tuple(elem.strip(" ") for elem in element))
561     if sources:
562         logfile822.write("Sources:\n")
563         for source in sources:
564             logfile822.write(" %s\n" % source)
565     if binaries:
566         logfile822.write("Binaries:\n")
567         for binary in binaries:
568             logfile822.write(" %s\n" % binary)
569     logfile822.write("Reason: %s\n" % Options["Reason"].replace('\n', '\n '))
570     if Options["Done"]:
571         logfile822.write("Bug: %s\n" % Options["Done"])
572
573     dsc_type_id = get_override_type('dsc', session).overridetype_id
574     deb_type_id = get_override_type('deb', session).overridetype_id
575
576     # Do the actual deletion
577     print "Deleting...",
578     sys.stdout.flush()
579
580     for i in to_remove:
581         package = i[0]
582         architecture = i[2]
583         package_id = i[3]
584         for suite_id in suite_ids_list:
585             if architecture == "source":
586                 session.execute("DELETE FROM src_associations WHERE source = :packageid AND suite = :suiteid",
587                                 {'packageid': package_id, 'suiteid': suite_id})
588                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id)
589             else:
590                 session.execute("DELETE FROM bin_associations WHERE bin = :packageid AND suite = :suiteid",
591                                 {'packageid': package_id, 'suiteid': suite_id})
592                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id)
593             # Delete from the override file
594             if not Options["Partial"]:
595                 if architecture == "source":
596                     type_id = dsc_type_id
597                 else:
598                     type_id = deb_type_id
599                 # TODO: Again, fix this properly to remove the remaining non-bind argument
600                 session.execute("DELETE FROM override WHERE package = :package AND type = :typeid AND suite = :suiteid %s" % (over_con_components), {'package': package, 'typeid': type_id, 'suiteid': suite_id})
601     session.commit()
602     print "done."
603
604     # If we don't have a Bug server configured, we're done
605     if not cnf.has_key("Dinstall::BugServer"):
606         if Options["Done"] or Options["Do-Close"]:
607             print "Cannot send mail to BugServer as Dinstall::BugServer is not configured"
608
609         logfile.write("=========================================================================\n")
610         logfile.close()
611
612         logfile822.write("\n")
613         logfile822.close()
614
615         return
616
617     # read common subst variables for all bug closure mails
618     Subst_common = {}
619     Subst_common["__RM_ADDRESS__"] = cnf["Dinstall::MyEmailAddress"]
620     Subst_common["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
621     Subst_common["__CC__"] = "X-DAK: dak rm"
622     if carbon_copy:
623         Subst_common["__CC__"] += "\nCc: " + ", ".join(carbon_copy)
624     Subst_common["__SUITE_LIST__"] = suites_list
625     Subst_common["__SUBJECT__"] = "Removed package(s) from %s" % (suites_list)
626     Subst_common["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
627     Subst_common["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
628     Subst_common["__WHOAMI__"] = whoami
629
630     # Send the bug closing messages
631     if Options["Done"]:
632         Subst_close_rm = Subst_common
633         bcc = []
634         if cnf.Find("Dinstall::Bcc") != "":
635             bcc.append(cnf["Dinstall::Bcc"])
636         if cnf.Find("Rm::Bcc") != "":
637             bcc.append(cnf["Rm::Bcc"])
638         if bcc:
639             Subst_close_rm["__BCC__"] = "Bcc: " + ", ".join(bcc)
640         else:
641             Subst_close_rm["__BCC__"] = "X-Filler: 42"
642         summarymail = "%s\n------------------- Reason -------------------\n%s\n" % (summary, Options["Reason"])
643         summarymail += "----------------------------------------------\n"
644         Subst_close_rm["__SUMMARY__"] = summarymail
645
646         whereami = utils.where_am_i()
647         Archive = get_archive(whereami, session)
648         if Archive is None:
649             utils.warn("Cannot find archive %s.  Setting blank values for origin" % whereami)
650             Subst_close_rm["__MASTER_ARCHIVE__"] = ""
651             Subst_close_rm["__PRIMARY_MIRROR__"] = ""
652         else:
653             Subst_close_rm["__MASTER_ARCHIVE__"] = Archive.origin_server
654             Subst_close_rm["__PRIMARY_MIRROR__"] = Archive.primary_mirror
655
656         for bug in utils.split_args(Options["Done"]):
657             Subst_close_rm["__BUG_NUMBER__"] = bug
658             if Options["Do-Close"]:
659                 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close-with-related")
660             else:
661                 mail_message = utils.TemplateSubst(Subst_close_rm,cnf["Dir::Templates"]+"/rm.bug-close")
662             utils.send_mail(mail_message)
663
664     # close associated bug reports
665     if Options["Do-Close"]:
666         Subst_close_other = Subst_common
667         bcc = []
668         wnpp = utils.parse_wnpp_bug_file()
669         versions = list(set([re_bin_only_nmu.sub('', v) for v in versions]))
670         if len(versions) == 1:
671             Subst_close_other["__VERSION__"] = versions[0]
672         else:
673             utils.fubar("Closing bugs with multiple package versions is not supported.  Do it yourself.")
674         if bcc:
675             Subst_close_other["__BCC__"] = "Bcc: " + ", ".join(bcc)
676         else:
677             Subst_close_other["__BCC__"] = "X-Filler: 42"
678         # at this point, I just assume, that the first closed bug gives
679         # some useful information on why the package got removed
680         Subst_close_other["__BUG_NUMBER__"] = utils.split_args(Options["Done"])[0]
681         if len(sources) == 1:
682             source_pkg = source.split("_", 1)[0]
683         else:
684             utils.fubar("Closing bugs for multiple source pakcages is not supported.  Do it yourself.")
685         Subst_close_other["__BUG_NUMBER_ALSO__"] = ""
686         Subst_close_other["__SOURCE__"] = source_pkg
687         other_bugs = bts.get_bugs('src', source_pkg, 'status', 'open')
688         if other_bugs:
689             logfile.write("Also closing bug(s):")
690             logfile822.write("Also-Bugs:")
691             for bug in other_bugs:
692                 Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
693                 logfile.write(" " + str(bug))
694                 logfile822.write(" " + str(bug))
695             logfile.write("\n")
696             logfile822.write("\n")
697         if source_pkg in wnpp.keys():
698             logfile.write("Also closing WNPP bug(s):")
699             logfile822.write("Also-WNPP:")
700             for bug in wnpp[source_pkg]:
701                 # the wnpp-rm file we parse also contains our removal
702                 # bugs, filtering that out
703                 if bug != Subst_close_other["__BUG_NUMBER__"]:
704                     Subst_close_other["__BUG_NUMBER_ALSO__"] += str(bug) + "-done@" + cnf["Dinstall::BugServer"] + ","
705                     logfile.write(" " + str(bug))
706                     logfile822.write(" " + str(bug))
707             logfile.write("\n")
708             logfile822.write("\n")
709
710         mail_message = utils.TemplateSubst(Subst_close_other,cnf["Dir::Templates"]+"/rm.bug-close-related")
711         if Subst_close_other["__BUG_NUMBER_ALSO__"]:
712             utils.send_mail(mail_message)
713
714
715     logfile.write("=========================================================================\n")
716     logfile.close()
717
718     logfile822.write("\n")
719     logfile822.close()
720
721 #######################################################################################
722
723 if __name__ == '__main__':
724     main()