]> git.decadent.org.uk Git - dak.git/blob - dak/override.py
Merge remote branch 'drkranz/overrides' into merge
[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                check 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             Packages = utils.get_packages_from_ftp(cnf['Dir::Root'], suite, component, arch)
70             while Packages.Step():
71                 package_name = Packages.Section.Find("Package")
72                 dep_list = Packages.Section.Find("Depends")
73                 if dep_list:
74                     if package_name == package:
75                         for d in apt_pkg.ParseDepends(dep_list):
76                             for i in d:
77                                 depends.add(i[0])
78                     else:
79                         for d in apt_pkg.ParseDepends(dep_list):
80                             for i in d:
81                                 if i[0] == package:
82                                     rdepends.add(package_name)
83
84     query = """SELECT o.package, p.level, p.priority
85                FROM override o
86                JOIN suite s ON s.id = o.suite
87                JOIN priority p ON p.id = o.priority
88                WHERE s.suite_name = '%s'
89                AND o.package in ('%s')""" \
90                % (suite, "', '".join(depends.union(rdepends)))
91     packages = session.execute(query)
92
93     excuses = []
94     for p in packages:
95         if p[0] == package or not p[1]:
96             continue
97         if p[0] in depends:
98             if priority.level < p[1]:
99                 excuses.append("%s would have priority %s, its dependency %s has priority %s" \
100                       % (package, priority.priority, p[0], p[2]))
101         if p[0] in rdepends:
102             if priority.level > p[1]:
103                 excuses.append("%s would have priority %s, its reverse dependency %s has priority %s" \
104                       % (package, priority.priority, p[0], p[2]))
105
106     if excuses:
107         for ex in excuses:
108             print ex
109     else:
110         print "Proposed override change complies with Debian Policy"
111
112 def main ():
113     cnf = Config()
114
115     Arguments = [('h',"help","Override::Options::Help"),
116                  ('c',"check","Override::Options::Check"),
117                  ('d',"done","Override::Options::Done", "HasArg"),
118                  ('n',"no-action","Override::Options::No-Action"),
119                  ('s',"suite","Override::Options::Suite", "HasArg"),
120                  ]
121     for i in ["help", "check", "no-action"]:
122         if not cnf.has_key("Override::Options::%s" % (i)):
123             cnf["Override::Options::%s" % (i)] = ""
124     if not cnf.has_key("Override::Options::Suite"):
125         cnf["Override::Options::Suite"] = "unstable"
126
127     arguments = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
128     Options = cnf.SubTree("Override::Options")
129
130     if Options["Help"]:
131         usage()
132
133     session = DBConn().session()
134
135     if not arguments:
136         utils.fubar("package name is a required argument.")
137
138     package = arguments.pop(0)
139     suite = Options["Suite"]
140     if arguments and len(arguments) > 2:
141         utils.fubar("Too many arguments")
142
143     if arguments and len(arguments) == 1:
144         # Determine if the argument is a priority or a section...
145         arg = arguments.pop()
146         q = session.execute("""
147         SELECT ( SELECT COUNT(*) FROM section WHERE section = :arg ) AS secs,
148                ( SELECT COUNT(*) FROM priority WHERE priority = :arg ) AS prios
149                """, {'arg': arg})
150         r = q.fetchall()
151         if r[0][0] == 1:
152             arguments = (arg, ".")
153         elif r[0][1] == 1:
154             arguments = (".", arg)
155         else:
156             utils.fubar("%s is not a valid section or priority" % (arg))
157
158     # Retrieve current section/priority...
159     oldsection, oldsourcesection, oldpriority = None, None, None
160     for packagetype in ['source', 'binary']:
161         eqdsc = '!='
162         if packagetype == 'source':
163             eqdsc = '='
164         q = session.execute("""
165     SELECT priority.priority AS prio, section.section AS sect, override_type.type AS type
166       FROM override, priority, section, suite, override_type
167      WHERE override.priority = priority.id
168        AND override.type = override_type.id
169        AND override_type.type %s 'dsc'
170        AND override.section = section.id
171        AND override.package = :package
172        AND override.suite = suite.id
173        AND suite.suite_name = :suite
174         """ % (eqdsc), {'package': package, 'suite': suite})
175
176         if q.rowcount == 0:
177             continue
178         if q.rowcount > 1:
179             utils.fubar("%s is ambiguous. Matches %d packages" % (package,q.rowcount))
180
181         r = q.fetchone()
182         if packagetype == 'binary':
183             oldsection = r[1]
184             oldpriority = r[0]
185         else:
186             oldsourcesection = r[1]
187             oldpriority = 'source'
188
189     if not oldpriority and not oldsourcesection:
190         utils.fubar("Unable to find package %s" % (package))
191
192     if oldsection and oldsourcesection and oldsection != oldsourcesection:
193         # When setting overrides, both source & binary will become the same section
194         utils.warn("Source is in section '%s' instead of '%s'" % (oldsourcesection, oldsection))
195
196     if not oldsection:
197         oldsection = oldsourcesection
198
199     if not arguments:
200         print "%s is in section '%s' at priority '%s'" % (
201             package, oldsection, oldpriority)
202         sys.exit(0)
203
204     # At this point, we have a new section and priority... check they're valid...
205     newsection, newpriority = arguments
206
207     if newsection == ".":
208         newsection = oldsection
209     if newpriority == ".":
210         newpriority = oldpriority
211
212     s = get_section(newsection, session)
213     if s is None:
214         utils.fubar("Supplied section %s is invalid" % (newsection))
215     newsecid = s.section_id
216
217     p = get_priority(newpriority, session)
218     if p is None:
219         utils.fubar("Supplied priority %s is invalid" % (newpriority))
220     newprioid = p.priority_id
221
222     if newpriority == oldpriority and newsection == oldsection:
223         print "I: Doing nothing"
224         sys.exit(0)
225
226     if oldpriority == 'source' and newpriority != 'source':
227         utils.fubar("Trying to change priority of a source-only package")
228
229     if Options["Check"] and newpriority != oldpriority:
230         check_override_compliance(package, p, suite, cnf, session)
231
232     # If we're in no-action mode
233     if Options["No-Action"]:
234         if newpriority != oldpriority:
235             print "I: Would change priority from %s to %s" % (oldpriority,newpriority)
236         if newsection != oldsection:
237             print "I: Would change section from %s to %s" % (oldsection,newsection)
238         if Options.has_key("Done"):
239             print "I: Would also close bug(s): %s" % (Options["Done"])
240
241         sys.exit(0)
242
243     if newpriority != oldpriority:
244         print "I: Will change priority from %s to %s" % (oldpriority,newpriority)
245
246     if newsection != oldsection:
247         print "I: Will change section from %s to %s" % (oldsection,newsection)
248
249     if not Options.has_key("Done"):
250         pass
251         #utils.warn("No bugs to close have been specified. Noone will know you have done this.")
252     else:
253         print "I: Will close bug(s): %s" % (Options["Done"])
254
255     game_over()
256
257     Logger = daklog.Logger(cnf.Cnf, "override")
258
259     dsc_otype_id = get_override_type('dsc').overridetype_id
260
261     # We're already in a transaction
262     # We're in "do it" mode, we have something to do... do it
263     if newpriority != oldpriority:
264         session.execute("""
265         UPDATE override
266            SET priority = :newprioid
267          WHERE package = :package
268            AND override.type != :otypedsc
269            AND suite = (SELECT id FROM suite WHERE suite_name = :suite)""",
270            {'newprioid': newprioid, 'package': package,
271             'otypedsc':  dsc_otype_id, 'suite': suite})
272
273         Logger.log(["changed priority", package, oldpriority, newpriority])
274
275     if newsection != oldsection:
276         q = session.execute("""
277         UPDATE override
278            SET section = :newsecid
279          WHERE package = :package
280            AND suite = (SELECT id FROM suite WHERE suite_name = :suite)""",
281            {'newsecid': newsecid, 'package': package,
282             'suite': suite})
283
284         Logger.log(["changed section", package, oldsection, newsection])
285
286     session.commit()
287
288     if Options.has_key("Done"):
289         Subst = {}
290         Subst["__OVERRIDE_ADDRESS__"] = cnf["Dinstall::MyEmailAddress"]
291         Subst["__BUG_SERVER__"] = cnf["Dinstall::BugServer"]
292         bcc = []
293         if cnf.Find("Dinstall::Bcc") != "":
294             bcc.append(cnf["Dinstall::Bcc"])
295         if bcc:
296             Subst["__BCC__"] = "Bcc: " + ", ".join(bcc)
297         else:
298             Subst["__BCC__"] = "X-Filler: 42"
299         Subst["__CC__"] = "Cc: " + package + "@" + cnf["Dinstall::PackagesServer"] + "\nX-DAK: dak override"
300         Subst["__ADMIN_ADDRESS__"] = cnf["Dinstall::MyAdminAddress"]
301         Subst["__DISTRO__"] = cnf["Dinstall::MyDistribution"]
302         Subst["__WHOAMI__"] = utils.whoami()
303         Subst["__SOURCE__"] = package
304
305         summary = "Concerning package %s...\n" % (package)
306         summary += "Operating on the %s suite\n" % (suite)
307         if newpriority != oldpriority:
308             summary += "Changed priority from %s to %s\n" % (oldpriority,newpriority)
309         if newsection != oldsection:
310             summary += "Changed section from %s to %s\n" % (oldsection,newsection)
311         Subst["__SUMMARY__"] = summary
312
313         template = os.path.join(cnf["Dir::Templates"], "override.bug-close")
314         for bug in utils.split_args(Options["Done"]):
315             Subst["__BUG_NUMBER__"] = bug
316             mail_message = utils.TemplateSubst(Subst, template)
317             utils.send_mail(mail_message)
318             Logger.log(["closed bug", bug])
319
320     Logger.close()
321
322 #################################################################################
323
324 if __name__ == '__main__':
325     main()