]> git.decadent.org.uk Git - dak.git/blob - dak/override.py
Move common code to the new get_packages_from_ftp()
[dak.git] / dak / override.py
1 #!/usr/bin/env python
2
3 """ Microscopic modification and query tool for overrides in projectb """
4 # Copyright (C) 2004, 2006  Daniel Silverstone <dsilvers@digital-scurf.org>
5
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.
10
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.
15
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
19
20
21 ################################################################################
22 ## So line up your soldiers and she'll shoot them all down
23 ## Coz Alisha Rules The World
24 ## You think you found a dream, then it shatters and it seems,
25 ## That Alisha Rules The World
26 ################################################################################
27
28 import os
29 import sys
30 import apt_pkg
31
32 from daklib.config import Config
33 from daklib.dbconn import *
34 from daklib import daklog
35 from daklib import utils
36
37 ################################################################################
38
39 # Shamelessly stolen from 'dak rm'. Should probably end up in utils.py
40 def game_over():
41     answer = utils.our_raw_input("Continue (y/N)? ").lower()
42     if answer != "y":
43         print "Aborted."
44         sys.exit(1)
45
46
47 def usage (exit_code=0):
48     print """Usage: dak override [OPTIONS] package [section] [priority]
49 Make microchanges or microqueries of the binary overrides
50
51   -h, --help                 show this help and exit
52   -c, --check                chech override compliance
53   -d, --done=BUG#            send priority/section change as closure to bug#
54   -n, --no-action            don't do anything
55   -s, --suite                specify the suite to use
56 """
57     sys.exit(exit_code)
58
59 def check_override_compliance(package, priority, suite, cnf, session):
60     print "Checking compliance with related overrides..."
61
62     depends = set()
63     rdepends = set()
64     components = cnf.ValueList("Suite::%s::Components" % suite)
65     arches = set([x.arch_string for x in get_suite_architectures(suite)])
66     arches -= set(["source", "all"])
67     for arch in arches:
68         for component in components:
69             temp_filename = utils.get_packages_from_ftp(cnf['Dir::Root'], suite, component, arch)
70             packages = utils.open_file(temp_filename)
71             Packages = apt_pkg.ParseTagFile(packages)
72             while Packages.Step():
73                 package_name = Packages.Section.Find("Package")
74                 dep_list = Packages.Section.Find("Depends")
75                 if dep_list:
76                     if package_name == package:
77                         for d in apt_pkg.ParseDepends(dep_list):
78                             for i in d:
79                                 depends.add(i[0])
80                     else:
81                         for d in apt_pkg.ParseDepends(dep_list):
82                             for i in d:
83                                 if i[0] == package:
84                                     rdepends.add(package_name)
85             os.unlink(temp_filename)
86
87     query = """SELECT o.package, p.level, p.priority
88                FROM override o
89                JOIN suite s ON s.id = o.suite
90                JOIN priority p ON p.id = o.priority
91                WHERE s.suite_name = '%s'
92                AND o.package in ('%s')""" \
93                % (suite, "', '".join(depends.union(rdepends)))
94     packages = session.execute(query)
95
96     excuses = []
97     for p in packages:
98         if p[0] == package or not p[1]:
99             continue
100         if p[0] in depends:
101             if priority.level < p[1]:
102                 excuses.append("%s would have priority %s, its dependency %s has priority %s" \
103                       % (package, priority.priority, p[0], p[2]))
104         if p[0] in rdepends:
105             if priority.level > p[1]:
106                 excuses.append("%s would have priority %s, its reverse dependency %s has priority %s" \
107                       % (package, priority.priority, p[0], p[2]))
108
109     if excuses:
110         for ex in excuses:
111             print ex
112     else:
113         print "Proposed override change complies with Debian Policy"
114
115 def main ():
116     cnf = Config()
117
118     Arguments = [('h',"help","Override::Options::Help"),
119                  ('c',"check","Override::Options::Check"),
120                  ('d',"done","Override::Options::Done", "HasArg"),
121                  ('n',"no-action","Override::Options::No-Action"),
122                  ('s',"suite","Override::Options::Suite", "HasArg"),
123                  ]
124     for i in ["help", "check", "no-action"]:
125         if not cnf.has_key("Override::Options::%s" % (i)):
126             cnf["Override::Options::%s" % (i)] = ""
127     if not cnf.has_key("Override::Options::Suite"):
128         cnf["Override::Options::Suite"] = "unstable"
129
130     arguments = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
131     Options = cnf.SubTree("Override::Options")
132
133     if Options["Help"]:
134         usage()
135
136     session = DBConn().session()
137
138     if not arguments:
139         utils.fubar("package name is a required argument.")
140
141     package = arguments.pop(0)
142     suite = Options["Suite"]
143     if arguments and len(arguments) > 2:
144         utils.fubar("Too many arguments")
145
146     if arguments and len(arguments) == 1:
147         # Determine if the argument is a priority or a section...
148         arg = arguments.pop()
149         q = session.execute("""
150         SELECT ( SELECT COUNT(*) FROM section WHERE section = :arg ) AS secs,
151                ( SELECT COUNT(*) FROM priority WHERE priority = :arg ) AS prios
152                """, {'arg': arg})
153         r = q.fetchall()
154         if r[0][0] == 1:
155             arguments = (arg, ".")
156         elif r[0][1] == 1:
157             arguments = (".", arg)
158         else:
159             utils.fubar("%s is not a valid section or priority" % (arg))
160
161     # Retrieve current section/priority...
162     oldsection, oldsourcesection, oldpriority = None, None, None
163     for packagetype in ['source', 'binary']:
164         eqdsc = '!='
165         if packagetype == 'source':
166             eqdsc = '='
167         q = session.execute("""
168     SELECT priority.priority AS prio, section.section AS sect, override_type.type AS type
169       FROM override, priority, section, suite, override_type
170      WHERE override.priority = priority.id
171        AND override.type = override_type.id
172        AND override_type.type %s 'dsc'
173        AND override.section = section.id
174        AND override.package = :package
175        AND override.suite = suite.id
176        AND suite.suite_name = :suite
177         """ % (eqdsc), {'package': package, 'suite': suite})
178
179         if q.rowcount == 0:
180             continue
181         if q.rowcount > 1:
182             utils.fubar("%s is ambiguous. Matches %d packages" % (package,q.rowcount))
183
184         r = q.fetchone()
185         if packagetype == 'binary':
186             oldsection = r[1]
187             oldpriority = r[0]
188         else:
189             oldsourcesection = r[1]
190             oldpriority = 'source'
191
192     if not oldpriority and not oldsourcesection:
193         utils.fubar("Unable to find package %s" % (package))
194
195     if oldsection and oldsourcesection and oldsection != oldsourcesection:
196         # When setting overrides, both source & binary will become the same section
197         utils.warn("Source is in section '%s' instead of '%s'" % (oldsourcesection, oldsection))
198
199     if not oldsection:
200         oldsection = oldsourcesection
201
202     if not arguments:
203         print "%s is in section '%s' at priority '%s'" % (
204             package, oldsection, oldpriority)
205         sys.exit(0)
206
207     # At this point, we have a new section and priority... check they're valid...
208     newsection, newpriority = arguments
209
210     if newsection == ".":
211         newsection = oldsection
212     if newpriority == ".":
213         newpriority = oldpriority
214
215     s = get_section(newsection, session)
216     if s is None:
217         utils.fubar("Supplied section %s is invalid" % (newsection))
218     newsecid = s.section_id
219
220     p = get_priority(newpriority, session)
221     if p is None:
222         utils.fubar("Supplied priority %s is invalid" % (newpriority))
223     newprioid = p.priority_id
224
225     if newpriority == oldpriority and newsection == oldsection:
226         print "I: Doing nothing"
227         sys.exit(0)
228
229     if oldpriority == 'source' and newpriority != 'source':
230         utils.fubar("Trying to change priority of a source-only package")
231
232     if Options["Check"] and newpriority != oldpriority:
233         check_override_compliance(package, p, suite, cnf, session)
234
235     # If we're in no-action mode
236     if Options["No-Action"]:
237         if newpriority != oldpriority:
238             print "I: Would change priority from %s to %s" % (oldpriority,newpriority)
239         if newsection != oldsection:
240             print "I: Would change section from %s to %s" % (oldsection,newsection)
241         if Options.has_key("Done"):
242             print "I: Would also close bug(s): %s" % (Options["Done"])
243
244         sys.exit(0)
245
246     if newpriority != oldpriority:
247         print "I: Will change priority from %s to %s" % (oldpriority,newpriority)
248
249     if newsection != oldsection:
250         print "I: Will change section from %s to %s" % (oldsection,newsection)
251
252     if not Options.has_key("Done"):
253         pass
254         #utils.warn("No bugs to close have been specified. Noone will know you have done this.")
255     else:
256         print "I: Will close bug(s): %s" % (Options["Done"])
257
258     game_over()
259
260     Logger = daklog.Logger(cnf.Cnf, "override")
261
262     dsc_otype_id = get_override_type('dsc').overridetype_id
263
264     # We're already in a transaction
265     # We're in "do it" mode, we have something to do... do it
266     if newpriority != oldpriority:
267         session.execute("""
268         UPDATE override
269            SET priority = :newprioid
270          WHERE package = :package
271            AND override.type != :otypedsc
272            AND suite = (SELECT id FROM suite WHERE suite_name = :suite)""",
273            {'newprioid': newprioid, 'package': package,
274             'otypedsc':  dsc_otype_id, 'suite': suite})
275
276         Logger.log(["changed priority", package, oldpriority, newpriority])
277
278     if newsection != oldsection:
279         q = session.execute("""
280         UPDATE override
281            SET section = :newsecid
282          WHERE package = :package
283            AND suite = (SELECT id FROM suite WHERE suite_name = :suite)""",
284            {'newsecid': newsecid, 'package': package,
285             'suite': suite})
286
287         Logger.log(["changed section", package, oldsection, newsection])
288
289     session.commit()
290
291     if Options.has_key("Done"):
292         Subst = {}
293         Subst["__OVERRIDE_ADDRESS__"] = cnf["Dinstall::MyEmailAddress"]
294         Subst["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
295         bcc = []
296         if cnf.Find("Dinstall::Bcc") != "":
297             bcc.append(cnf["Dinstall::Bcc"])
298         if bcc:
299             Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
300         else:
301             Subst["__BCC__"] = "X-Filler: 42"
302         Subst["__CC__"] = "Cc: " + package + "@" + cnf["Dinstall::PackagesServer"] + "\nX-DAK: dak override"
303         Subst["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
304         Subst["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
305         Subst["__WHOAMI__"] = utils.whoami()
306         Subst["__SOURCE__"] = package
307
308         summary = "Concerning package %s...\n" % (package)
309         summary += "Operating on the %s suite\n" % (suite)
310         if newpriority != oldpriority:
311             summary += "Changed priority from %s to %s\n" % (oldpriority,newpriority)
312         if newsection != oldsection:
313             summary += "Changed section from %s to %s\n" % (oldsection,newsection)
314         Subst["__SUMMARY__"] = summary
315
316         template = os.path.join(cnf["Dir::Templates"], "override.bug-close")
317         for bug in utils.split_args(Options["Done"]):
318             Subst["__BUG_NUMBER__"] = bug
319             mail_message = utils.TemplateSubst(Subst, template)
320             utils.send_mail(mail_message)
321             Logger.log(["closed bug", bug])
322
323     Logger.close()
324
325 #################################################################################
326
327 if __name__ == '__main__':
328     main()