]> git.decadent.org.uk Git - dak.git/blob - melanie
Use parse_args(), use join_with_commas_and(), handle nothing-to-do case better
[dak.git] / melanie
1 #!/usr/bin/env python
2
3 # General purpose package removal tool for ftpmaster
4 # Copyright (C) 2000, 2001, 2002  James Troup <james@nocrew.org>
5 # $Id: melanie,v 1.28 2002-07-14 15:01:51 troup Exp $
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, os, pg, re, string, sys, tempfile
44 import utils, db_access
45 import apt_pkg, apt_inst;
46
47 ################################################################################
48
49 re_strip_source_version = re.compile (r'\s+.*$');
50
51 ################################################################################
52
53 Cnf = None;
54 projectB = None;
55
56 ################################################################################
57
58 def usage (exit_code=0):
59     print """Usage: melanie [OPTIONS] PACKAGE[...]
60 Remove PACKAGE(s) from suite(s).
61
62   -a, --architecture=ARCH    only act on this architecture
63   -b, --binary               remove binaries only
64   -c, --component=COMPONENT  act on this component
65   -C, --carbon-copy=EMAIL    send a CC of removal message to EMAIL
66   -d, --done=BUG#            send removal message as closure to bug#
67   -m, --reason=MSG           reason for removal
68   -n, --no-action            don't do anything
69   -p, --partial              don't affect override files
70   -s, --suite=SUITE          act on this suite
71   -S, --source-only          remove source only
72   -h, --help                 show this help and exit
73
74 ARCH, BUG#, COMPONENT and SUITE can be space seperated lists, e.g.
75     --architecture=\"m68k i386\""""
76
77     sys.exit(exit_code)
78
79 ################################################################################
80
81 # "That's just fucking great!  Game over, man!  What the fuck are we
82 #  going to do now?"
83
84 def game_over():
85     answer = string.lower(utils.our_raw_input("Continue (y/N)? "));
86     if answer != "y":
87         print "Aborted."
88         sys.exit(1);
89
90 ################################################################################
91
92 def main ():
93     global Cnf, projectB;
94
95     Cnf = utils.get_conf()
96
97     Arguments = [('h',"help","Melanie::Options::Help"),
98                  ('a',"architecture","Melanie::Options::Architecture", "HasArg"),
99                  ('b',"binary", "Melanie::Options::Binary-Only"),
100                  ('c',"component", "Melanie::Options::Component", "HasArg"),
101                  ('C',"carbon-copy", "Melanie::Options::Carbon-Copy", "HasArg"), # Bugs to Cc
102                  ('d',"done","Melanie::Options::Done", "HasArg"), # Bugs fixed
103                  ('m',"reason", "Melanie::Options::Reason", "HasArg"), # Hysterical raisins; -m is old-dinstall option for rejection reason
104                  ('n',"no-action","Melanie::Options::No-Action"),
105                  ('p',"partial", "Melanie::Options::Partial"),
106                  ('s',"suite","Melanie::Options::Suite", "HasArg"),
107                  ('S',"source-only", "Melanie::Options::Source-Only"),
108                  ];
109
110     for i in ["help", "architecture", "binary-only", "component", "carbon-copy", "done", "reason", "no-action", "partial", "source-only" ]:
111         if not Cnf.has_key("Melanie::Options::%s" % (i)):
112             Cnf["Melanie::Options::%s" % (i)] = "";
113     if not Cnf.has_key("Melanie::Options::Suite"):
114         Cnf["Melanie::Options::Suite"] = "unstable";
115
116     arguments = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
117     Options = Cnf.SubTree("Melanie::Options")
118
119     if Options["Help"]:
120         usage();
121
122     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]));
123     db_access.init(Cnf, projectB);
124
125     # Sanity check options
126     if not arguments:
127         utils.fubar("need at least one package name as an argument.");
128     if Options["Architecture"] and Options["Source-Only"]:
129         utils.fubar("can't use -a/--architecutre and -S/--source-only options simultaneously.");
130     if Options["Binary-Only"] and Options["Source-Only"]:
131         utils.fubar("can't use -b/--binary-only and -S/--source-only options simultaneously.");
132     if Options.has_key("Carbon-Copy") and not Options.has_key("Done"):
133         utils.fubar("can't use -C/--carbon-copy without also using -d/--done option.");
134     if Options["Architecture"] and not Options["Partial"]:
135         utils.warn("-a/--architecture implies -p/--partial.");
136         Options["Partial"] = "true";
137
138     # Process -C/--carbon-copy
139     #
140     # Accept 3 types of arguments (space separated):
141     #  1) a number - assumed to be a bug number, i.e. nnnnn@bugs.debian.org
142     #  2) the keyword 'package' - cc's $package@packages.debian.org for every argument
143     #  3) contains a '@' - assumed to be an email address, used unmofidied
144     #
145     carbon_copy = [];
146     for copy_to in string.split(Options.get("Carbon-Copy")):
147         if utils.str_isnum(copy_to):
148             carbon_copy.append(copy_to + "@" + Cnf["Dinstall::BugServer"]);
149         elif copy_to == 'package':
150             for package in arguments:
151                 carbon_copy.append(package + "@" + Cnf["Dinstall::PackagesServer"]);
152                 if Cnf.has_key("Dinstall::TrackingServer"):
153                     carbon_copy.append(package + "@" + Cnf["Dinstall::TrackingServer"]);
154         elif '@' in copy_to:
155             carbon_copy.append(copy_to);
156         else:
157             utils.fubar("Invalid -C/--carbon-copy argument '%s'; not a bug number, 'package' or email address." % (copy_to));
158
159     if Options["Binary-Only"]:
160         field = "b.package";
161     else:
162         field = "s.source";
163     con_packages = "AND %s IN (%s)" % (field, string.join(map(repr, arguments), ", "));
164
165     (con_suites, con_architectures, con_components, check_source) = \
166                  utils.parse_args(Options);
167
168     # Additional suite checks
169     suites = string.split(Options["Suite"]);
170     suites_list = utils.join_with_commas_and(suites);
171     if not Options["No-Action"]:
172         for suite in suites:
173             if suite == "stable":
174                 print "**WARNING** About to remove from the stable suite!"
175                 print "This should only be done just prior to a (point) release and not at"
176                 print "any other time."
177                 game_over();
178             elif suite == "testing":
179                 print "**WARNING About to remove from the testing suite!"
180                 print "There's no need to do this normally as removals from unstable will"
181                 print "propogate to testing automagically."
182                 game_over();
183
184     # Additional architecture checks
185     if Options["Architecture"] and check_source:
186         utils.warn("'source' in -a/--argument makes no sense and is ignored.");
187
188     # Additional component processing
189     over_con_components = string.replace(con_components, "c.id", "component");
190
191     print "Working...",
192     sys.stdout.flush();
193     to_remove = [];
194     maintainers = {};
195
196     # We have 3 modes of package selection: binary-only, source-only
197     # and source+binary.  The first two are trivial and obvious; the
198     # latter is a nasty mess, but very nice from a UI perspective so
199     # we try to support it.
200
201     if Options["Binary-Only"]:
202         # Binary-only
203         q = projectB.query("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));
204         for i in q.getresult():
205             to_remove.append(i);
206     else:
207         # Source-only
208         source_packages = {};
209         q = projectB.query("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));
210         for i in q.getresult():
211             source_packages[i[2]] = i[:2];
212             to_remove.append(i[2:]);
213         if not Options["Source-Only"]:
214             # Source + Binary
215             binary_packages = {};
216             # First get a list of binary package names we suspect are linked to the source
217             q = projectB.query("SELECT DISTINCT package FROM binaries WHERE EXISTS (SELECT s.source, s.version, l.path, f.filename FROM source s, src_associations sa, suite su, files f, location l, component c WHERE binaries.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));
218             for i in q.getresult():
219                 binary_packages[i[0]] = "";
220             # Then parse each .dsc that we found earlier to see what binary packages it thinks it produces
221             for i in source_packages.keys():
222                 filename = string.join(source_packages[i], '/');
223                 try:
224                     dsc = utils.parse_changes(filename);
225                 except utils.cant_open_exc:
226                     utils.warn("couldn't open '%s'." % (filename));
227                     continue;
228                 for package in string.split(dsc.get("binary"), ','):
229                     package = string.strip(package);
230                     binary_packages[package] = "";
231             # Then for each binary package: find any version in
232             # unstable, check the Source: field in the deb matches our
233             # source package and if so add it to the list of packages
234             # to be removed.
235             for package in binary_packages.keys():
236                 q = projectB.query("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));
237                 for i in q.getresult():
238                     filename = string.join(i[:2], '/');
239                     control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(filename)))
240                     source = control.Find("Source", control.Find("Package"));
241                     source = re_strip_source_version.sub('', source);
242                     if source_packages.has_key(source):
243                         to_remove.append(i[2:]);
244     print "done."
245
246     if not to_remove:
247         print "Nothing to do."
248         sys.exit(0);
249
250     # If we don't have a reason; spawn an editor so the user can add one
251     # Write the rejection email out as the <foo>.reason file
252     if not Options["Reason"] and not Options["No-Action"]:
253         temp_filename = tempfile.mktemp();
254         fd = os.open(temp_filename, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700);
255         os.close(fd);
256         editor = os.environ.get("EDITOR","vi")
257         result = os.system("%s %s" % (editor, temp_filename))
258         if result != 0:
259             utils.fubar ("vi invocation failed for `%s'!" % (temp_filename), result)
260         file = utils.open_file(temp_filename);
261         for line in file.readlines():
262             Options["Reason"] = Options["Reason"] + line;
263         os.unlink(temp_filename);
264
265     # Generate the summary of what's to be removed
266     d = {};
267     for i in to_remove:
268         package = i[0];
269         version = i[1];
270         architecture = i[2];
271         maintainer = i[4];
272         maintainers[maintainer] = "";
273         if not d.has_key(package):
274             d[package] = {};
275         if not d[package].has_key(version):
276             d[package][version] = [];
277         if architecture not in d[package][version]:
278             d[package][version].append(architecture);
279
280     maintainer_list = [];
281     for maintainer_id in maintainers.keys():
282         maintainer_list.append(db_access.get_maintainer(maintainer_id));
283     summary = "";
284     packages = d.keys();
285     packages.sort();
286     for package in packages:
287         versions = d[package].keys();
288         versions.sort();
289         for version in versions:
290             summary = summary + "%10s | %10s | %s\n" % (package, version, string.join(d[package][version], ", "));
291     print "Will remove the following packages from %s:" % (suites_list);
292     print
293     print summary
294     print "Maintainer: %s" % string.join(maintainer_list, ", ")
295     if Options["Done"]:
296         print "Will also close bugs: "+Options["Done"];
297     if carbon_copy:
298         print "Will also send CCs to:" + string.join(carbon_copy, ", ")
299     print
300     print "------------------- Reason -------------------"
301     print Options["Reason"];
302     print "----------------------------------------------"
303     print
304
305     # If -n/--no-action, drop out here
306     if Options["No-Action"]:
307         sys.exit(0);
308
309     game_over();
310
311     whoami = utils.whoami();
312     date = commands.getoutput('date -R');
313
314     # Log first; if it all falls apart I want a record that we at least tried.
315     logfile = utils.open_file(Cnf["Melanie::LogFile"], 'a');
316     logfile.write("=========================================================================\n");
317     logfile.write("[Date: %s] [ftpmaster: %s]\n" % (date, whoami));
318     logfile.write("Removed the following packages from %s:\n\n%s" % (suites_list, summary));
319     if Options["Done"]:
320         logfile.write("Closed bugs: %s\n" % (Options["Done"]));
321     logfile.write("\n------------------- Reason -------------------\n%s\n" % (Options["Reason"]));
322     logfile.write("----------------------------------------------\n");
323     logfile.flush();
324
325     dsc_type_id = db_access.get_override_type_id('dsc');
326     deb_type_id = db_access.get_override_type_id('deb');
327
328     # Do the actual deletion
329     print "Deleting...",
330     sys.stdout.flush();
331     projectB.query("BEGIN WORK");
332     for i in to_remove:
333         package = i[0];
334         architecture = i[2];
335         package_id = i[3];
336         for suite_id in suite_ids_list:
337             if architecture == "source":
338                 projectB.query("DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id));
339                 #print "DELETE FROM src_associations WHERE source = %s AND suite = %s" % (package_id, suite_id);
340             else:
341                 projectB.query("DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id));
342                 #print "DELETE FROM bin_associations WHERE bin = %s AND suite = %s" % (package_id, suite_id);
343             # Delete from the override file
344             if not Options["Partial"]:
345                 if architecture == "source":
346                     type_id = dsc_type_id;
347                 else:
348                     type_id = deb_type_id;
349                 projectB.query("DELETE FROM override WHERE package = '%s' AND type = %s AND suite = %s %s" % (package, type_id, suite_id, over_con_components));
350     projectB.query("COMMIT WORK");
351     print "done."
352
353     # Send the bug closing messages
354     if Options["Done"]:
355         Subst = {};
356         Subst["__MELANIE_ADDRESS__"] = Cnf["Melanie::MyEmailAddress"];
357         Subst["__BUG_SERVER__"] = Cnf["Dinstall::BugServer"];
358         bcc = [];
359         if Cnf.Find("Dinstall::Bcc") != "":
360             bcc.append(Cnf["Dinstall::Bcc"]);
361         if Cnf.Find("Melanie::Bcc") != "":
362             bcc.append(Cnf["Melanie::Bcc"]);
363         if bcc:
364             Subst["__BCC__"] = "Bcc: " + string.join(bcc, ", ");
365         else:
366             Subst["__BCC__"] = "X-Filler: 42";
367         Subst["__CC__"] = "X-Melanie: $Revision: 1.28 $";
368         if carbon_copy:
369             Subst["__CC__"] = Subst["__CC__"] + "\nCc: " + string.join(carbon_copy, ", ");
370         Subst["__SUITE_LIST__"] = suites_list;
371         Subst["__SUMMARY__"] = summary;
372         Subst["__ADMIN_ADDRESS__"] = Cnf["Dinstall::MyAdminAddress"];
373         Subst["__DISTRO__"] = Cnf["Dinstall::MyDistribution"];
374         Subst["__WHOAMI__"] = whoami;
375         whereami = utils.where_am_i();
376         Archive = Cnf.SubTree("Archive::%s" % (whereami));
377         Subst["__MASTER_ARCHIVE__"] = Archive["OriginServer"];
378         Subst["__PRIMARY_MIRROR__"] = Archive["PrimaryMirror"];
379         for bug in string.split(Options["Done"]):
380             Subst["__BUG_NUMBER__"] = bug;
381             mail_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/melanie.bug-close");
382             utils.send_mail (mail_message, "")
383
384     logfile.write("=========================================================================\n");
385     logfile.close();
386
387 #######################################################################################
388
389 if __name__ == '__main__':
390     main()
391