]> git.decadent.org.uk Git - dak.git/blob - dak/control_suite.py
Merge commit 'mhy/sqlalchemy' 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
68     sys.exit(exit_code)
69
70 #######################################################################################
71
72 def get_id(package, version, architecture, session):
73     if architecture == "source":
74         q = session.execute("SELECT id FROM source WHERE source = :package AND version = :version",
75                             {'package': package, 'version': version})
76     else:
77         q = session.execute("""SELECT b.id FROM binaries b, architecture a
78                                 WHERE b.package = :package AND b.version = :version
79                                   AND (a.arch_string = :arch OR a.arch_string = 'all')
80                                   AND b.architecture = a.id""",
81                                {'package': package, 'version': version, 'arch': architecture})
82
83     ql = q.fetchall()
84     if len(ql) < 1:
85         utils.warn("Couldn't find '%s_%s_%s'." % (package, version, architecture))
86         return None
87
88     if len(ql) > 1:
89         utils.warn("Found more than one match for '%s_%s_%s'." % (package, version, architecture))
90         return None
91
92     return ql[0][0]
93
94 #######################################################################################
95
96 def set_suite(file, suite, session):
97     suite_id = suite.suite_id
98     lines = file.readlines()
99
100     # Our session is already in a transaction
101
102     # Build up a dictionary of what is currently in the suite
103     current = {}
104     q = session.execute("""SELECT b.package, b.version, a.arch_string, ba.id
105                              FROM binaries b, bin_associations ba, architecture a
106                             WHERE ba.suite = :suiteid
107                               AND ba.bin = b.id AND b.architecture = a.id""", {'suiteid': suite_id})
108     for i in q.fetchall():
109         key = " ".join(i[:3])
110         current[key] = i[3]
111
112     q = session.execute("""SELECT s.source, s.version, sa.id
113                              FROM source s, src_associations sa
114                             WHERE sa.suite = :suiteid
115                               AND sa.source = s.id""", {'suiteid': suite_id})
116     for i in q.fetchall():
117         key = " ".join(i[:2]) + " source"
118         current[key] = i[2]
119
120     # Build up a dictionary of what should be in the suite
121     desired = {}
122     for line in lines:
123         split_line = line.strip().split()
124         if len(split_line) != 3:
125             utils.warn("'%s' does not break into 'package version architecture'." % (line[:-1]))
126             continue
127         key = " ".join(split_line)
128         desired[key] = ""
129
130     # Check to see which packages need removed and remove them
131     for key in current.keys():
132         if not desired.has_key(key):
133             (package, version, architecture) = key.split()
134             pkid = current[key]
135             if architecture == "source":
136                 session.execute("""DELETE FROM src_associations WHERE id = :pkid""", {'pkid': pkid})
137             else:
138                 session.execute("""DELETE FROM bin_associations WHERE id = :pkid""", {'pkid': pkid})
139             Logger.log(["removed", key, pkid])
140
141     # Check to see which packages need added and add them
142     for key in desired.keys():
143         if not current.has_key(key):
144             (package, version, architecture) = key.split()
145             pkid = get_id (package, version, architecture, session)
146             if not pkid:
147                 continue
148             if architecture == "source":
149                 session.execute("""INSERT INTO src_associations (suite, source)
150                                         VALUES (:suiteid, :pkid)""", {'suiteid': suite_id, 'pkid': pkid})
151             else:
152                 session.execute("""INSERT INTO bin_associations (suite, bin)
153                                         VALUES (:suiteid, :pkid)""", {'suiteid': suite_id, 'pkid': pkid})
154             Logger.log(["added", key, pkid])
155
156     session.commit()
157
158 #######################################################################################
159
160 def process_file(file, suite, action, session):
161     if action == "set":
162         set_suite(file, suite, session)
163         return
164
165     suite_id = suite.suite_id
166
167     lines = file.readlines()
168
169     # Our session is already in a transaction
170     for line in lines:
171         split_line = line.strip().split()
172         if len(split_line) != 3:
173             utils.warn("'%s' does not break into 'package version architecture'." % (line[:-1]))
174             continue
175
176         (package, version, architecture) = split_line
177
178         pkid = get_id(package, version, architecture, session)
179         if not pkid:
180             continue
181
182         if architecture == "source":
183             # Find the existing association ID, if any
184             q = session.execute("""SELECT id FROM src_associations
185                                     WHERE suite = :suiteid and source = :pkid""",
186                                     {'suiteid': suite_id, 'pkid': pkid})
187             ql = q.fetchall()
188             if len(ql) < 1:
189                 association_id = None
190             else:
191                 association_id = ql[0][0]
192
193             # Take action
194             if action == "add":
195                 if association_id:
196                     utils.warn("'%s_%s_%s' already exists in suite %s." % (package, version, architecture, suite))
197                     continue
198                 else:
199                     session.execute("""INSERT INTO src_associations (suite, source)
200                                             VALUES (:suiteid, :pkid)""",
201                                        {'suiteid': suite_id, 'pkid': pkid})
202             elif action == "remove":
203                 if association_id == None:
204                     utils.warn("'%s_%s_%s' doesn't exist in suite %s." % (package, version, architecture, suite))
205                     continue
206                 else:
207                     session.execute("""DELETE FROM src_associations WHERE id = :pkid""", {'pkid': association_id})
208         else:
209             # Find the existing associations ID, if any
210             q = session.execute("""SELECT id FROM bin_associations
211                                     WHERE suite = :suiteid and bin = :pkid""",
212                                     {'suiteid': suite_id, 'pkid': pkid})
213             ql = q.fetchall()
214             if len(ql) < 1:
215                 association_id = None
216             else:
217                 association_id = ql[0][0]
218
219             # Take action
220             if action == "add":
221                 if association_id:
222                     utils.warn("'%s_%s_%s' already exists in suite %s." % (package, version, architecture, suite))
223                     continue
224                 else:
225                     session.execute("""INSERT INTO bin_associations (suite, bin)
226                                             VALUES (%s, %s)""",
227                                        {'suiteid': suite_id, 'pkid': pkid})
228             elif action == "remove":
229                 if association_id == None:
230                     utils.warn("'%s_%s_%s' doesn't exist in suite %s." % (package, version, architecture, suite))
231                     continue
232                 else:
233                     session.execute("""DELETE FROM bin_associations WHERE id = :pkid""", {'pkid': association_id})
234
235     session.commit()
236
237 #######################################################################################
238
239 def get_list(suite, session):
240     suite_id = suite.suite_id
241     # List binaries
242     q = session.execute("""SELECT b.package, b.version, a.arch_string
243                              FROM binaries b, bin_associations ba, architecture a
244                             WHERE ba.suite = :suiteid
245                               AND ba.bin = b.id AND b.architecture = a.id""", {'suiteid': suite_id})
246     for i in q.fetchall():
247         print " ".join(i)
248
249     # List source
250     q = session.execute("""SELECT s.source, s.version
251                              FROM source s, src_associations sa
252                             WHERE sa.suite = :suiteid
253                               AND sa.source = s.id""", {'suiteid': suite_id})
254     for i in q.fetchall():
255         print " ".join(i) + " source"
256
257 #######################################################################################
258
259 def main ():
260     global Logger
261
262     cnf = Config()
263
264     Arguments = [('a',"add","Control-Suite::Options::Add", "HasArg"),
265                  ('h',"help","Control-Suite::Options::Help"),
266                  ('l',"list","Control-Suite::Options::List","HasArg"),
267                  ('r',"remove", "Control-Suite::Options::Remove", "HasArg"),
268                  ('s',"set", "Control-Suite::Options::Set", "HasArg")]
269
270     for i in ["add", "help", "list", "remove", "set", "version" ]:
271         if not cnf.has_key("Control-Suite::Options::%s" % (i)):
272             cnf["Control-Suite::Options::%s" % (i)] = ""
273
274     try:
275         file_list = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv);
276     except SystemError, e:
277         print "%s\n" % e
278         usage(1)
279     Options = cnf.SubTree("Control-Suite::Options")
280
281     if Options["Help"]:
282         usage()
283
284     session = DBConn().session()
285
286     action = None
287
288     for i in ("add", "list", "remove", "set"):
289         if cnf["Control-Suite::Options::%s" % (i)] != "":
290             suite_name = cnf["Control-Suite::Options::%s" % (i)]
291             suite = get_suite(suite_name, session=session)
292             if suite is None:
293                 utils.fubar("Unknown suite '%s'." % (suite_name))
294             else:
295                 if action:
296                     utils.fubar("Can only perform one action at a time.")
297                 action = i
298
299     # Need an action...
300     if action == None:
301         utils.fubar("No action specified.")
302
303     # Safety/Sanity check
304     # XXX: This should be stored in the database
305     if action == "set" and suite_name not in ["testing", "etch-m68k"]:
306         utils.fubar("Will not reset suite %s" % (suite_name))
307
308     if action == "list":
309         get_list(suite, session)
310     else:
311         Logger = daklog.Logger(cnf.Cnf, "control-suite")
312         if file_list:
313             for f in file_list:
314                 process_file(utils.open_file(f), suite, action, session)
315         else:
316             process_file(sys.stdin, suite, action, session)
317         Logger.close()
318
319 #######################################################################################
320
321 if __name__ == '__main__':
322     main()