]> git.decadent.org.uk Git - dak.git/blob - dak/control_overrides.py
Merge remote-tracking branch 'dktrkranz/fixes'
[dak.git] / dak / control_overrides.py
1 #!/usr/bin/env python
2
3 """ Bulk manipulation of the overrides """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.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 # On 30 Nov 1998, James Troup wrote:
23 #
24 # > James Troup<2> <troup2@debian.org>
25 # >
26 # >    James is a clone of James; he's going to take over the world.
27 # >    After he gets some sleep.
28 #
29 # Could you clone other things too? Sheep? Llamas? Giant mutant turnips?
30 #
31 # Your clone will need some help to take over the world, maybe clone up an
32 # army of penguins and threaten to unleash them on the world, forcing
33 # governments to sway to the new James' will!
34 #
35 # Yes, I can envision a day when James' duplicate decides to take a horrific
36 # vengance on the James that spawned him and unleashes his fury in the form
37 # of thousands upon thousands of chickens that look just like Captin Blue
38 # Eye! Oh the horror.
39 #
40 # Now you'll have to were name tags to people can tell you apart, unless of
41 # course the new clone is truely evil in which case he should be easy to
42 # identify!
43 #
44 # Jason
45 # Chicken. Black. Helicopters.
46 # Be afraid.
47
48 # <Pine.LNX.3.96.981130011300.30365Z-100000@wakko>
49
50 ################################################################################
51
52 import sys, time
53 import apt_pkg
54
55 from daklib.dbconn import *
56 from daklib.config import Config
57 from daklib import utils
58 from daklib import daklog
59 from daklib.regexes import re_comments
60
61 ################################################################################
62
63 Logger = None
64
65 ################################################################################
66
67 def usage (exit_code=0):
68     print """Usage: dak control-overrides [OPTIONS]
69   -h, --help               print this help and exit
70
71   -c, --component=CMPT     list/set overrides by component
72                                   (contrib,*main,non-free)
73   -s, --suite=SUITE        list/set overrides by suite
74                                   (experimental,stable,testing,*unstable)
75   -t, --type=TYPE          list/set overrides by type
76                                   (*deb,dsc,udeb)
77
78   -a, --add                add overrides (changes and deletions are ignored)
79   -S, --set                set overrides
80   -C, --change             change overrides (additions and deletions are ignored)
81   -l, --list               list overrides
82
83   -q, --quiet              be less verbose
84   -n, --no-action          only list the action that would have been done
85
86  starred (*) values are default"""
87     sys.exit(exit_code)
88
89 ################################################################################
90
91 def process_file(file, suite, component, otype, mode, action, session):
92     cnf = Config()
93
94     s = get_suite(suite, session=session)
95     if s is None:
96         utils.fubar("Suite '%s' not recognised." % (suite))
97     suite_id = s.suite_id
98
99     c = get_component(component, session=session)
100     if c is None:
101         utils.fubar("Component '%s' not recognised." % (component))
102     component_id = c.component_id
103
104     o = get_override_type(otype)
105     if o is None:
106         utils.fubar("Type '%s' not recognised. (Valid types are deb, udeb and dsc.)" % (otype))
107     type_id = o.overridetype_id
108
109     # --set is done mostly internal for performance reasons; most
110     # invocations of --set will be updates and making people wait 2-3
111     # minutes while 6000 select+inserts are run needlessly isn't cool.
112
113     original = {}
114     new = {}
115     c_skipped = 0
116     c_added = 0
117     c_updated = 0
118     c_removed = 0
119     c_error = 0
120
121     q = session.execute("""SELECT o.package, o.priority, o.section, o.maintainer, p.priority, s.section
122                            FROM override o, priority p, section s
123                            WHERE o.suite = :suiteid AND o.component = :componentid AND o.type = :typeid
124                              and o.priority = p.id and o.section = s.id""",
125                            {'suiteid': suite_id, 'componentid': component_id, 'typeid': type_id})
126     for i in q.fetchall():
127         original[i[0]] = i[1:]
128
129     start_time = time.time()
130
131     section_cache = get_sections(session)
132     priority_cache = get_priorities(session)
133
134     # Our session is already in a transaction
135
136     for line in file.readlines():
137         line = re_comments.sub('', line).strip()
138         if line == "":
139             continue
140
141         maintainer_override = None
142         if otype == "dsc":
143             split_line = line.split(None, 2)
144             if len(split_line) == 2:
145                 (package, section) = split_line
146             elif len(split_line) == 3:
147                 (package, section, maintainer_override) = split_line
148             else:
149                 utils.warn("'%s' does not break into 'package section [maintainer-override]'." % (line))
150                 c_error += 1
151                 continue
152             priority = "source"
153         else: # binary or udeb
154             split_line = line.split(None, 3)
155             if len(split_line) == 3:
156                 (package, priority, section) = split_line
157             elif len(split_line) == 4:
158                 (package, priority, section, maintainer_override) = split_line
159             else:
160                 utils.warn("'%s' does not break into 'package priority section [maintainer-override]'." % (line))
161                 c_error += 1
162                 continue
163
164         if not section_cache.has_key(section):
165             utils.warn("'%s' is not a valid section. ['%s' in suite %s, component %s]." % (section, package, suite, component))
166             c_error += 1
167             continue
168
169         section_id = section_cache[section]
170
171         if not priority_cache.has_key(priority):
172             utils.warn("'%s' is not a valid priority. ['%s' in suite %s, component %s]." % (priority, package, suite, component))
173             c_error += 1
174             continue
175
176         priority_id = priority_cache[priority]
177
178         if new.has_key(package):
179             utils.warn("Can't insert duplicate entry for '%s'; ignoring all but the first. [suite %s, component %s]" % (package, suite, component))
180             c_error += 1
181             continue
182         new[package] = ""
183
184         if original.has_key(package):
185             (old_priority_id, old_section_id, old_maintainer_override, old_priority, old_section) = original[package]
186             if mode == "add" or old_priority_id == priority_id and \
187                old_section_id == section_id and \
188                old_maintainer_override == maintainer_override:
189                 # If it's unchanged or we're in 'add only' mode, ignore it
190                 c_skipped += 1
191                 continue
192             else:
193                 # If it's changed, delete the old one so we can
194                 # reinsert it with the new information
195                 c_updated += 1
196                 if action:
197                     session.execute("""DELETE FROM override WHERE suite = :suite AND component = :component
198                                                               AND package = :package AND type = :typeid""",
199                                     {'suite': suite_id,  'component': component_id,
200                                      'package': package, 'typeid': type_id})
201
202                 # Log changes
203                 if old_priority_id != priority_id:
204                     Logger.log(["changed priority", package, old_priority, priority])
205                 if old_section_id != section_id:
206                     Logger.log(["changed section", package, old_section, section])
207                 if old_maintainer_override != maintainer_override:
208                     Logger.log(["changed maintainer override", package, old_maintainer_override, maintainer_override])
209                 update_p = 1
210         elif mode == "change":
211             # Ignore additions in 'change only' mode
212             c_skipped += 1
213             continue
214         else:
215             c_added += 1
216             update_p = 0
217
218         if action:
219             if not maintainer_override:
220                 m_o = None
221             else:
222                 m_o = maintainer_override
223             session.execute("""INSERT INTO override (suite, component, type, package,
224                                                      priority, section, maintainer)
225                                              VALUES (:suiteid, :componentid, :typeid,
226                                                      :package, :priorityid, :sectionid,
227                                                      :maintainer)""",
228                               {'suiteid': suite_id, 'componentid': component_id,
229                                'typeid':  type_id,  'package': package,
230                                'priorityid': priority_id, 'sectionid': section_id,
231                                'maintainer': m_o})
232
233         if not update_p:
234             Logger.log(["new override", suite, component, otype, package,priority,section,maintainer_override])
235
236     if mode == "set":
237         # Delete any packages which were removed
238         for package in original.keys():
239             if not new.has_key(package):
240                 if action:
241                     session.execute("""DELETE FROM override
242                                        WHERE suite = :suiteid AND component = :componentid
243                                          AND package = :package AND type = :typeid""",
244                                     {'suiteid': suite_id, 'componentid': component_id,
245                                      'package': package, 'typeid': type_id})
246                 c_removed += 1
247                 Logger.log(["removed override", suite, component, otype, package])
248
249     if action:
250         session.commit()
251
252     if not cnf["Control-Overrides::Options::Quiet"]:
253         print "Done in %d seconds. [Updated = %d, Added = %d, Removed = %d, Skipped = %d, Errors = %d]" % (int(time.time()-start_time), c_updated, c_added, c_removed, c_skipped, c_error)
254
255     Logger.log(["set complete", c_updated, c_added, c_removed, c_skipped, c_error])
256
257 ################################################################################
258
259 def list_overrides(suite, component, otype, session):
260     dat = {}
261     s = get_suite(suite, session)
262     if s is None:
263         utils.fubar("Suite '%s' not recognised." % (suite))
264
265     dat['suiteid'] = s.suite_id
266
267     c = get_component(component, session)
268     if c is None:
269         utils.fubar("Component '%s' not recognised." % (component))
270
271     dat['componentid'] = c.component_id
272
273     o = get_override_type(otype)
274     if o is None:
275         utils.fubar("Type '%s' not recognised. (Valid types are deb, udeb and dsc)" % (otype))
276
277     dat['typeid'] = o.overridetype_id
278
279     if otype == "dsc":
280         q = session.execute("""SELECT o.package, s.section, o.maintainer FROM override o, section s
281                                 WHERE o.suite = :suiteid AND o.component = :componentid
282                                   AND o.type = :typeid AND o.section = s.id
283                              ORDER BY s.section, o.package""", dat)
284         for i in q.fetchall():
285             print utils.result_join(i)
286     else:
287         q = session.execute("""SELECT o.package, p.priority, s.section, o.maintainer, p.level
288                                  FROM override o, priority p, section s
289                                 WHERE o.suite = :suiteid AND o.component = :componentid
290                                   AND o.type = :typeid AND o.priority = p.id AND o.section = s.id
291                              ORDER BY s.section, p.level, o.package""", dat)
292         for i in q.fetchall():
293             print utils.result_join(i[:-1])
294
295 ################################################################################
296
297 def main ():
298     global Logger
299
300     cnf = Config()
301     Arguments = [('a', "add", "Control-Overrides::Options::Add"),
302                  ('c', "component", "Control-Overrides::Options::Component", "HasArg"),
303                  ('h', "help", "Control-Overrides::Options::Help"),
304                  ('l', "list", "Control-Overrides::Options::List"),
305                  ('q', "quiet", "Control-Overrides::Options::Quiet"),
306                  ('s', "suite", "Control-Overrides::Options::Suite", "HasArg"),
307                  ('S', "set", "Control-Overrides::Options::Set"),
308                  ('C', "change", "Control-Overrides::Options::Change"),
309                  ('n', "no-action", "Control-Overrides::Options::No-Action"),
310                  ('t', "type", "Control-Overrides::Options::Type", "HasArg")]
311
312     # Default arguments
313     for i in [ "add", "help", "list", "quiet", "set", "change", "no-action" ]:
314         if not cnf.has_key("Control-Overrides::Options::%s" % (i)):
315             cnf["Control-Overrides::Options::%s" % (i)] = ""
316     if not cnf.has_key("Control-Overrides::Options::Component"):
317         cnf["Control-Overrides::Options::Component"] = "main"
318     if not cnf.has_key("Control-Overrides::Options::Suite"):
319         cnf["Control-Overrides::Options::Suite"] = "unstable"
320     if not cnf.has_key("Control-Overrides::Options::Type"):
321         cnf["Control-Overrides::Options::Type"] = "deb"
322
323     file_list = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
324
325     if cnf["Control-Overrides::Options::Help"]:
326         usage()
327
328     session = DBConn().session()
329
330     mode = None
331     for i in [ "add", "list", "set", "change" ]:
332         if cnf["Control-Overrides::Options::%s" % (i)]:
333             if mode:
334                 utils.fubar("Can not perform more than one action at once.")
335             mode = i
336
337     # Need an action...
338     if mode is None:
339         utils.fubar("No action specified.")
340
341     (suite, component, otype) = (cnf["Control-Overrides::Options::Suite"],
342                                  cnf["Control-Overrides::Options::Component"],
343                                  cnf["Control-Overrides::Options::Type"])
344
345     if mode == "list":
346         list_overrides(suite, component, otype, session)
347     else:
348         if get_suite(suite).untouchable:
349             utils.fubar("%s: suite is untouchable" % suite)
350
351         action = True
352         if cnf["Control-Overrides::Options::No-Action"]:
353             utils.warn("In No-Action Mode")
354             action = False
355
356         Logger = daklog.Logger("control-overrides", mode)
357         if file_list:
358             for f in file_list:
359                 process_file(utils.open_file(f), suite, component, otype, mode, action, session)
360         else:
361             process_file(sys.stdin, suite, component, otype, mode, action, session)
362         Logger.close()
363
364 #######################################################################################
365
366 if __name__ == '__main__':
367     main()