]> git.decadent.org.uk Git - dak.git/blob - dak/control_suite.py
control_suite.py: generate changelog for britney runs
[dak.git] / dak / control_suite.py
1 #!/usr/bin/env python
2
3 """ Manipulate suite tags """
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 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 # 8to6Guy: "Wow, Bob, You look rough!"
23 # BTAF: "Mbblpmn..."
24 # BTAF <.oO>: "You moron! This is what you get for staying up all night drinking vodka and salad dressing!"
25 # BTAF <.oO>: "This coffee I.V. drip is barely even keeping me awake! I need something with more kick! But what?"
26 # BTAF: "OMIGOD! I OVERDOSED ON HEROIN"
27 # CoWorker#n: "Give him air!!"
28 # CoWorker#n+1: "We need a syringe full of adrenaline!"
29 # CoWorker#n+2: "Stab him in the heart!"
30 # BTAF: "*YES!*"
31 # CoWorker#n+3: "Bob's been overdosing quite a bit lately..."
32 # CoWorker#n+4: "Third time this week."
33
34 # -- http://www.angryflower.com/8to6.gif
35
36 #######################################################################################
37
38 # Adds or removes packages from a suite.  Takes the list of files
39 # either from stdin or as a command line argument.  Special action
40 # "set", will reset the suite (!) and add all packages from scratch.
41
42 #######################################################################################
43
44 import sys
45 import apt_pkg
46
47 from daklib.config import Config
48 from daklib.dbconn import *
49 from daklib import daklog
50 from daklib import utils
51
52 #######################################################################################
53
54 Logger = None
55
56 ################################################################################
57
58 def usage (exit_code=0):
59     print """Usage: dak control-suite [OPTIONS] [FILE]
60 Display or alter the contents of a suite using FILE(s), or stdin.
61
62   -a, --add=SUITE            add to SUITE
63   -h, --help                 show this help and exit
64   -l, --list=SUITE           list the contents of SUITE
65   -r, --remove=SUITE         remove from SUITE
66   -s, --set=SUITE            set SUITE
67   -b, --britney              generate changelog entry for britney runs"""
68
69     sys.exit(exit_code)
70
71 #######################################################################################
72
73 def get_id(package, version, architecture, session):
74     if architecture == "source":
75         q = session.execute("SELECT id FROM source WHERE source = :package AND version = :version",
76                             {'package': package, 'version': version})
77     else:
78         q = session.execute("""SELECT b.id FROM binaries b, architecture a
79                                 WHERE b.package = :package AND b.version = :version
80                                   AND (a.arch_string = :arch OR a.arch_string = 'all')
81                                   AND b.architecture = a.id""",
82                                {'package': package, 'version': version, 'arch': architecture})
83
84     ql = q.fetchall()
85     if len(ql) < 1:
86         utils.warn("Couldn't find '%s_%s_%s'." % (package, version, architecture))
87         return None
88
89     if len(ql) > 1:
90         utils.warn("Found more than one match for '%s_%s_%s'." % (package, version, architecture))
91         return None
92
93     return ql[0][0]
94
95 #######################################################################################
96
97 def britney_changelog(packages, suite, session):
98
99     old = {}
100     current = {}
101
102     q = session.execute("""SELECT s.source, s.version, sa.id
103                              FROM source s, src_associations sa
104                             WHERE sa.suite = :suiteid
105                               AND sa.source = s.id""", {'suiteid': suite.suite_id})
106
107     for p in q.fetchall():
108         current[p[0]] = p[1]
109     for p in packages.keys():
110         p = p.split()
111         if p[2] == "source":
112             old[p[0]] = p[1]
113
114     new = {}
115     for p in current.keys():
116         if p in old.keys():
117             if apt_pkg.VersionCompare(current[p], old[p]) > 0:
118                 new[p] = [current[p], old[p]]
119         else:
120             new[p] = [current[p], 0]
121
122     query =  "SELECT source, changelog FROM changelogs WHERE"
123     for p in new.keys():
124         query += " source = '%s' AND version > '%s' AND version <= '%s'" \
125                  % (p, new[p][1], new[p][0])
126         query += " AND architecture LIKE '%source%' OR"
127     query += " False ORDER BY source, version DESC"
128     q = session.execute(query)
129
130     pu = None
131     brit = utils.open_file(Config()["Changelogs::Britney"], 'w')
132
133     for u in q:
134         if pu and pu != u[0]:
135             brit.write("\n")
136         brit.write("%s\n" % u[1])
137         pu = u[0]
138     if len(u): brit.write("\n\n\n")
139
140     for p in list(set(old.keys()).difference(current.keys())):
141         brit.write("REMOVED: %s %s\n" % (p, old[p]))
142
143     brit.flush()
144     brit.close()
145
146 #######################################################################################
147
148 def set_suite(file, suite, session, britney=False):
149     suite_id = suite.suite_id
150     lines = file.readlines()
151
152     # Our session is already in a transaction
153
154     # Build up a dictionary of what is currently in the suite
155     current = {}
156     q = session.execute("""SELECT b.package, b.version, a.arch_string, ba.id
157                              FROM binaries b, bin_associations ba, architecture a
158                             WHERE ba.suite = :suiteid
159                               AND ba.bin = b.id AND b.architecture = a.id""", {'suiteid': suite_id})
160     for i in q.fetchall():
161         key = " ".join(i[:3])
162         current[key] = i[3]
163
164     q = session.execute("""SELECT s.source, s.version, sa.id
165                              FROM source s, src_associations sa
166                             WHERE sa.suite = :suiteid
167                               AND sa.source = s.id""", {'suiteid': suite_id})
168     for i in q.fetchall():
169         key = " ".join(i[:2]) + " source"
170         current[key] = i[2]
171
172     # Build up a dictionary of what should be in the suite
173     desired = {}
174     for line in lines:
175         split_line = line.strip().split()
176         if len(split_line) != 3:
177             utils.warn("'%s' does not break into 'package version architecture'." % (line[:-1]))
178             continue
179         key = " ".join(split_line)
180         desired[key] = ""
181
182     # Check to see which packages need removed and remove them
183     for key in current.keys():
184         if not desired.has_key(key):
185             (package, version, architecture) = key.split()
186             pkid = current[key]
187             if architecture == "source":
188                 session.execute("""DELETE FROM src_associations WHERE id = :pkid""", {'pkid': pkid})
189             else:
190                 session.execute("""DELETE FROM bin_associations WHERE id = :pkid""", {'pkid': pkid})
191             Logger.log(["removed", key, pkid])
192
193     # Check to see which packages need added and add them
194     for key in desired.keys():
195         if not current.has_key(key):
196             (package, version, architecture) = key.split()
197             pkid = get_id (package, version, architecture, session)
198             if not pkid:
199                 continue
200             if architecture == "source":
201                 session.execute("""INSERT INTO src_associations (suite, source)
202                                         VALUES (:suiteid, :pkid)""", {'suiteid': suite_id, 'pkid': pkid})
203             else:
204                 session.execute("""INSERT INTO bin_associations (suite, bin)
205                                         VALUES (:suiteid, :pkid)""", {'suiteid': suite_id, 'pkid': pkid})
206             Logger.log(["added", key, pkid])
207
208     session.commit()
209
210     if britney:
211         britney_changelog(current, suite, session)
212
213 #######################################################################################
214
215 def process_file(file, suite, action, session, britney=False):
216     if action == "set":
217         set_suite(file, suite, session, britney)
218         return
219
220     suite_id = suite.suite_id
221
222     lines = file.readlines()
223
224     # Our session is already in a transaction
225     for line in lines:
226         split_line = line.strip().split()
227         if len(split_line) != 3:
228             utils.warn("'%s' does not break into 'package version architecture'." % (line[:-1]))
229             continue
230
231         (package, version, architecture) = split_line
232
233         pkid = get_id(package, version, architecture, session)
234         if not pkid:
235             continue
236
237         if architecture == "source":
238             # Find the existing association ID, if any
239             q = session.execute("""SELECT id FROM src_associations
240                                     WHERE suite = :suiteid and source = :pkid""",
241                                     {'suiteid': suite_id, 'pkid': pkid})
242             ql = q.fetchall()
243             if len(ql) < 1:
244                 association_id = None
245             else:
246                 association_id = ql[0][0]
247
248             # Take action
249             if action == "add":
250                 if association_id:
251                     utils.warn("'%s_%s_%s' already exists in suite %s." % (package, version, architecture, suite))
252                     continue
253                 else:
254                     session.execute("""INSERT INTO src_associations (suite, source)
255                                             VALUES (:suiteid, :pkid)""",
256                                        {'suiteid': suite_id, 'pkid': pkid})
257             elif action == "remove":
258                 if association_id == None:
259                     utils.warn("'%s_%s_%s' doesn't exist in suite %s." % (package, version, architecture, suite))
260                     continue
261                 else:
262                     session.execute("""DELETE FROM src_associations WHERE id = :pkid""", {'pkid': association_id})
263         else:
264             # Find the existing associations ID, if any
265             q = session.execute("""SELECT id FROM bin_associations
266                                     WHERE suite = :suiteid and bin = :pkid""",
267                                     {'suiteid': suite_id, 'pkid': pkid})
268             ql = q.fetchall()
269             if len(ql) < 1:
270                 association_id = None
271             else:
272                 association_id = ql[0][0]
273
274             # Take action
275             if action == "add":
276                 if association_id:
277                     utils.warn("'%s_%s_%s' already exists in suite %s." % (package, version, architecture, suite))
278                     continue
279                 else:
280                     session.execute("""INSERT INTO bin_associations (suite, bin)
281                                             VALUES (:suiteid, :pkid)""",
282                                        {'suiteid': suite_id, 'pkid': pkid})
283             elif action == "remove":
284                 if association_id == None:
285                     utils.warn("'%s_%s_%s' doesn't exist in suite %s." % (package, version, architecture, suite))
286                     continue
287                 else:
288                     session.execute("""DELETE FROM bin_associations WHERE id = :pkid""", {'pkid': association_id})
289
290     session.commit()
291
292 #######################################################################################
293
294 def get_list(suite, session):
295     suite_id = suite.suite_id
296     # List binaries
297     q = session.execute("""SELECT b.package, b.version, a.arch_string
298                              FROM binaries b, bin_associations ba, architecture a
299                             WHERE ba.suite = :suiteid
300                               AND ba.bin = b.id AND b.architecture = a.id""", {'suiteid': suite_id})
301     for i in q.fetchall():
302         print " ".join(i)
303
304     # List source
305     q = session.execute("""SELECT s.source, s.version
306                              FROM source s, src_associations sa
307                             WHERE sa.suite = :suiteid
308                               AND sa.source = s.id""", {'suiteid': suite_id})
309     for i in q.fetchall():
310         print " ".join(i) + " source"
311
312 #######################################################################################
313
314 def main ():
315     global Logger
316
317     cnf = Config()
318
319     Arguments = [('a',"add","Control-Suite::Options::Add", "HasArg"),
320                  ('b',"britney","Control-Suite::Options::Britney"),
321                  ('h',"help","Control-Suite::Options::Help"),
322                  ('l',"list","Control-Suite::Options::List","HasArg"),
323                  ('r',"remove", "Control-Suite::Options::Remove", "HasArg"),
324                  ('s',"set", "Control-Suite::Options::Set", "HasArg")]
325
326     for i in ["add", "britney", "help", "list", "remove", "set", "version" ]:
327         if not cnf.has_key("Control-Suite::Options::%s" % (i)):
328             cnf["Control-Suite::Options::%s" % (i)] = ""
329
330     try:
331         file_list = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv);
332     except SystemError, e:
333         print "%s\n" % e
334         usage(1)
335     Options = cnf.SubTree("Control-Suite::Options")
336
337     if Options["Help"]:
338         usage()
339
340     session = DBConn().session()
341
342     action = None
343
344     for i in ("add", "list", "remove", "set"):
345         if cnf["Control-Suite::Options::%s" % (i)] != "":
346             suite_name = cnf["Control-Suite::Options::%s" % (i)]
347             suite = get_suite(suite_name, session=session)
348             if suite is None:
349                 utils.fubar("Unknown suite '%s'." % (suite_name))
350             else:
351                 if action:
352                     utils.fubar("Can only perform one action at a time.")
353                 action = i
354
355     # Need an action...
356     if action == None:
357         utils.fubar("No action specified.")
358
359     # Safety/Sanity check
360     # XXX: This should be stored in the database
361     if action == "set" and suite_name not in ["testing"]:
362         utils.fubar("Will not reset suite %s" % (suite_name))
363
364     britney = False
365     if action == "set" and cnf["Control-Suite::Options::Britney"]:
366         britney = True
367
368     if action == "list":
369         get_list(suite, session)
370     else:
371         Logger = daklog.Logger(cnf.Cnf, "control-suite")
372         if file_list:
373             for f in file_list:
374                 process_file(utils.open_file(f), suite, action, session, britney)
375         else:
376             process_file(sys.stdin, suite, action, session, britney)
377         Logger.close()
378
379 #######################################################################################
380
381 if __name__ == '__main__':
382     main()