]> git.decadent.org.uk Git - dak.git/blob - dak/control_suite.py
Merge remote branch 'drkranz/make-changelog' into merge
[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     Cnf = utils.get_conf()
102
103     try:
104         q = session.execute("SELECT changelog FROM suite WHERE id = :suiteid", \
105                             {'suiteid': suite.suite_id})
106         brit_file = q.fetchone()[0]
107     except:
108         brit_file = None
109
110     if brit_file:
111         brit_file = os.path.join(Cnf['Dir::Root'], brit_file)
112     else:
113         return
114
115     q = session.execute("""SELECT s.source, s.version, sa.id
116                              FROM source s, src_associations sa
117                             WHERE sa.suite = :suiteid
118                               AND sa.source = s.id""", {'suiteid': suite.suite_id})
119
120     for p in q.fetchall():
121         current[p[0]] = p[1]
122     for p in packages.keys():
123         p = p.split()
124         if p[2] == "source":
125             old[p[0]] = p[1]
126
127     new = {}
128     for p in current.keys():
129         if p in old.keys():
130             if apt_pkg.VersionCompare(current[p], old[p]) > 0:
131                 new[p] = [current[p], old[p]]
132         else:
133             new[p] = [current[p], 0]
134
135     query =  "SELECT source, changelog FROM changelogs WHERE"
136     for p in new.keys():
137         query += " source = '%s' AND version > '%s' AND version <= '%s'" \
138                  % (p, new[p][1], new[p][0])
139         query += " AND architecture LIKE '%source%' AND distribution in \
140                   ('unstable', 'experimental', 'testing-proposed-updates') OR"
141     query += " False ORDER BY source, version DESC"
142     q = session.execute(query)
143
144     pu = None
145     brit = utils.open_file(brit_file, 'w')
146
147     for u in q:
148         if pu and pu != u[0]:
149             brit.write("\n")
150         brit.write("%s\n" % u[1])
151         pu = u[0]
152     if q.rowcount: brit.write("\n\n\n")
153
154     for p in list(set(old.keys()).difference(current.keys())):
155         brit.write("REMOVED: %s %s\n" % (p, old[p]))
156
157     brit.flush()
158     brit.close()
159
160 #######################################################################################
161
162 def set_suite(file, suite, session, britney=False):
163     suite_id = suite.suite_id
164     lines = file.readlines()
165
166     # Our session is already in a transaction
167
168     # Build up a dictionary of what is currently in the suite
169     current = {}
170     q = session.execute("""SELECT b.package, b.version, a.arch_string, ba.id
171                              FROM binaries b, bin_associations ba, architecture a
172                             WHERE ba.suite = :suiteid
173                               AND ba.bin = b.id AND b.architecture = a.id""", {'suiteid': suite_id})
174     for i in q.fetchall():
175         key = " ".join(i[:3])
176         current[key] = i[3]
177
178     q = session.execute("""SELECT s.source, s.version, sa.id
179                              FROM source s, src_associations sa
180                             WHERE sa.suite = :suiteid
181                               AND sa.source = s.id""", {'suiteid': suite_id})
182     for i in q.fetchall():
183         key = " ".join(i[:2]) + " source"
184         current[key] = i[2]
185
186     # Build up a dictionary of what should be in the suite
187     desired = {}
188     for line in lines:
189         split_line = line.strip().split()
190         if len(split_line) != 3:
191             utils.warn("'%s' does not break into 'package version architecture'." % (line[:-1]))
192             continue
193         key = " ".join(split_line)
194         desired[key] = ""
195
196     # Check to see which packages need removed and remove them
197     for key in current.keys():
198         if not desired.has_key(key):
199             (package, version, architecture) = key.split()
200             pkid = current[key]
201             if architecture == "source":
202                 session.execute("""DELETE FROM src_associations WHERE id = :pkid""", {'pkid': pkid})
203             else:
204                 session.execute("""DELETE FROM bin_associations WHERE id = :pkid""", {'pkid': pkid})
205             Logger.log(["removed", key, pkid])
206
207     # Check to see which packages need added and add them
208     for key in desired.keys():
209         if not current.has_key(key):
210             (package, version, architecture) = key.split()
211             pkid = get_id (package, version, architecture, session)
212             if not pkid:
213                 continue
214             if architecture == "source":
215                 session.execute("""INSERT INTO src_associations (suite, source)
216                                         VALUES (:suiteid, :pkid)""", {'suiteid': suite_id, 'pkid': pkid})
217             else:
218                 session.execute("""INSERT INTO bin_associations (suite, bin)
219                                         VALUES (:suiteid, :pkid)""", {'suiteid': suite_id, 'pkid': pkid})
220             Logger.log(["added", key, pkid])
221
222     session.commit()
223
224     if britney:
225         britney_changelog(current, suite, session)
226
227 #######################################################################################
228
229 def process_file(file, suite, action, session, britney=False):
230     if action == "set":
231         set_suite(file, suite, session, britney)
232         return
233
234     suite_id = suite.suite_id
235
236     lines = file.readlines()
237
238     # Our session is already in a transaction
239     for line in lines:
240         split_line = line.strip().split()
241         if len(split_line) != 3:
242             utils.warn("'%s' does not break into 'package version architecture'." % (line[:-1]))
243             continue
244
245         (package, version, architecture) = split_line
246
247         pkid = get_id(package, version, architecture, session)
248         if not pkid:
249             continue
250
251         if architecture == "source":
252             # Find the existing association ID, if any
253             q = session.execute("""SELECT id FROM src_associations
254                                     WHERE suite = :suiteid and source = :pkid""",
255                                     {'suiteid': suite_id, 'pkid': pkid})
256             ql = q.fetchall()
257             if len(ql) < 1:
258                 association_id = None
259             else:
260                 association_id = ql[0][0]
261
262             # Take action
263             if action == "add":
264                 if association_id:
265                     utils.warn("'%s_%s_%s' already exists in suite %s." % (package, version, architecture, suite))
266                     continue
267                 else:
268                     session.execute("""INSERT INTO src_associations (suite, source)
269                                             VALUES (:suiteid, :pkid)""",
270                                        {'suiteid': suite_id, 'pkid': pkid})
271             elif action == "remove":
272                 if association_id == None:
273                     utils.warn("'%s_%s_%s' doesn't exist in suite %s." % (package, version, architecture, suite))
274                     continue
275                 else:
276                     session.execute("""DELETE FROM src_associations WHERE id = :pkid""", {'pkid': association_id})
277         else:
278             # Find the existing associations ID, if any
279             q = session.execute("""SELECT id FROM bin_associations
280                                     WHERE suite = :suiteid and bin = :pkid""",
281                                     {'suiteid': suite_id, 'pkid': pkid})
282             ql = q.fetchall()
283             if len(ql) < 1:
284                 association_id = None
285             else:
286                 association_id = ql[0][0]
287
288             # Take action
289             if action == "add":
290                 if association_id:
291                     utils.warn("'%s_%s_%s' already exists in suite %s." % (package, version, architecture, suite))
292                     continue
293                 else:
294                     session.execute("""INSERT INTO bin_associations (suite, bin)
295                                             VALUES (:suiteid, :pkid)""",
296                                        {'suiteid': suite_id, 'pkid': pkid})
297             elif action == "remove":
298                 if association_id == None:
299                     utils.warn("'%s_%s_%s' doesn't exist in suite %s." % (package, version, architecture, suite))
300                     continue
301                 else:
302                     session.execute("""DELETE FROM bin_associations WHERE id = :pkid""", {'pkid': association_id})
303
304     session.commit()
305
306 #######################################################################################
307
308 def get_list(suite, session):
309     suite_id = suite.suite_id
310     # List binaries
311     q = session.execute("""SELECT b.package, b.version, a.arch_string
312                              FROM binaries b, bin_associations ba, architecture a
313                             WHERE ba.suite = :suiteid
314                               AND ba.bin = b.id AND b.architecture = a.id""", {'suiteid': suite_id})
315     for i in q.fetchall():
316         print " ".join(i)
317
318     # List source
319     q = session.execute("""SELECT s.source, s.version
320                              FROM source s, src_associations sa
321                             WHERE sa.suite = :suiteid
322                               AND sa.source = s.id""", {'suiteid': suite_id})
323     for i in q.fetchall():
324         print " ".join(i) + " source"
325
326 #######################################################################################
327
328 def main ():
329     global Logger
330
331     cnf = Config()
332
333     Arguments = [('a',"add","Control-Suite::Options::Add", "HasArg"),
334                  ('b',"britney","Control-Suite::Options::Britney"),
335                  ('h',"help","Control-Suite::Options::Help"),
336                  ('l',"list","Control-Suite::Options::List","HasArg"),
337                  ('r',"remove", "Control-Suite::Options::Remove", "HasArg"),
338                  ('s',"set", "Control-Suite::Options::Set", "HasArg")]
339
340     for i in ["add", "britney", "help", "list", "remove", "set", "version" ]:
341         if not cnf.has_key("Control-Suite::Options::%s" % (i)):
342             cnf["Control-Suite::Options::%s" % (i)] = ""
343
344     try:
345         file_list = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv);
346     except SystemError, e:
347         print "%s\n" % e
348         usage(1)
349     Options = cnf.SubTree("Control-Suite::Options")
350
351     if Options["Help"]:
352         usage()
353
354     session = DBConn().session()
355
356     action = None
357
358     for i in ("add", "list", "remove", "set"):
359         if cnf["Control-Suite::Options::%s" % (i)] != "":
360             suite_name = cnf["Control-Suite::Options::%s" % (i)]
361             suite = get_suite(suite_name, session=session)
362             if suite is None:
363                 utils.fubar("Unknown suite '%s'." % (suite_name))
364             else:
365                 if action:
366                     utils.fubar("Can only perform one action at a time.")
367                 action = i
368
369     # Need an action...
370     if action == None:
371         utils.fubar("No action specified.")
372
373     # Safety/Sanity check
374     # XXX: This should be stored in the database
375     if action == "set" and suite_name not in ["testing"]:
376         utils.fubar("Will not reset suite %s" % (suite_name))
377
378     britney = False
379     if action == "set" and cnf["Control-Suite::Options::Britney"]:
380         britney = True
381
382     if action == "list":
383         get_list(suite, session)
384     else:
385         Logger = daklog.Logger(cnf.Cnf, "control-suite")
386         if file_list:
387             for f in file_list:
388                 process_file(utils.open_file(f), suite, action, session, britney)
389         else:
390             process_file(sys.stdin, suite, action, session, britney)
391         Logger.close()
392
393 #######################################################################################
394
395 if __name__ == '__main__':
396     main()