]> git.decadent.org.uk Git - dak.git/blob - dak/make_suite_file_list.py
fix typo
[dak.git] / dak / make_suite_file_list.py
1 #!/usr/bin/env python
2
3 """
4 Generate file lists used by apt-ftparchive to generate Packages and Sources files
5 @contact: Debian FTP Master <ftpmaster@debian.org>
6 @copyright: 2000, 2001, 2002, 2003, 2004, 2006  James Troup <james@nocrew.org>
7 @license: GNU General Public License version 2 or later
8 """
9
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
14
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
24 ################################################################################
25
26 # <elmo> I'm doing it in python btw.. nothing against your monster
27 #        SQL, but the python wins in terms of speed and readiblity
28 # <aj> bah
29 # <aj> you suck!!!!!
30 # <elmo> sorry :(
31 # <aj> you are not!!!
32 # <aj> you mock my SQL!!!!
33 # <elmo> you want have contest of skillz??????
34 # <aj> all your skillz are belong to my sql!!!!
35 # <elmo> yo momma are belong to my python!!!!
36 # <aj> yo momma was SQLin' like a pig last night!
37
38 ################################################################################
39
40 import copy
41 import os
42 import sys
43 import apt_pkg
44
45 from daklib.dbconn import *
46 from daklib.config import Config
47 from daklib import daklog
48 from daklib import utils
49
50 ################################################################################
51
52 Logger = None   #: Logger object
53 Options = None  #: Parsed CommandLine arguments
54
55 ################################################################################
56
57 def Dict(**dict): return dict
58
59 ################################################################################
60
61 def usage (exit_code=0):
62     print """Usage: dak make-suite-file-list [OPTION]
63 Write out file lists suitable for use with apt-ftparchive.
64
65   -a, --architecture=ARCH   only write file lists for this architecture
66   -c, --component=COMPONENT only write file lists for this component
67   -f, --force               ignore Untouchable suite directives in dak.conf
68   -h, --help                show this help and exit
69   -n, --no-delete           don't delete older versions
70   -s, --suite=SUITE         only write file lists for this suite
71
72 ARCH, COMPONENT and SUITE can be space separated lists, e.g.
73     --architecture=\"m68k i386\""""
74     sys.exit(exit_code)
75
76 ################################################################################
77
78 def version_cmp(a, b):
79     return -apt_pkg.VersionCompare(a[0], b[0])
80
81 #####################################################
82
83 def delete_packages(delete_versions, pkg, dominant_arch, suite,
84                     dominant_version, delete_table, delete_col, packages, session):
85     suite_o = get_suite(suite.lower(), session)
86     suite_id = suite_o.suite_id
87     for version in delete_versions:
88         delete_unique_id = version[1]
89         if not packages.has_key(delete_unique_id):
90             continue
91         delete_version = version[0]
92         delete_id = packages[delete_unique_id]["sourceid"]
93         delete_arch = packages[delete_unique_id]["arch"]
94         if Options["Force"] or not suite_o.untouchable:
95             if Options["No-Delete"]:
96                 print "Would delete %s_%s_%s in %s in favour of %s_%s" % (pkg, delete_arch, delete_version, suite, dominant_version, dominant_arch)
97             else:
98                 Logger.log(["dominated", pkg, delete_arch, delete_version, dominant_version, dominant_arch])
99                 # TODO: Fix properly
100                 session.execute("DELETE FROM %s WHERE suite = :suiteid AND %s = :delid" % (delete_table, delete_col), {'suiteid': suite_id, 'delid': delete_id})
101             del packages[delete_unique_id]
102         else:
103             if Options["No-Delete"]:
104                 print "Would delete %s_%s_%s in favour of %s_%s, but %s is untouchable" % (pkg, delete_arch, delete_version, dominant_version, dominant_arch, suite)
105             else:
106                 Logger.log(["dominated but untouchable", pkg, delete_arch, delete_version, dominant_version, dominant_arch])
107
108 #####################################################
109
110 def resolve_arch_all_vs_any(versions, packages, session):
111     """ Per-suite&pkg: resolve arch-all, vs. arch-any, assumes only one arch-all """
112     arch_all_version = None
113     arch_any_versions = copy.copy(versions)
114     for i in arch_any_versions:
115         unique_id = i[1]
116         arch = packages[unique_id]["arch"]
117         if arch == "all":
118             arch_all_versions = [i]
119             arch_all_version = i[0]
120             arch_any_versions.remove(i)
121     # Sort arch: any versions into descending order
122     arch_any_versions.sort(version_cmp)
123     highest_arch_any_version = arch_any_versions[0][0]
124
125     pkg = packages[unique_id]["pkg"]
126     suite = packages[unique_id]["suite"]
127     delete_table = "bin_associations"
128     delete_col = "bin"
129
130     if apt_pkg.VersionCompare(highest_arch_any_version, arch_all_version) < 1:
131         # arch: all dominates
132         delete_packages(arch_any_versions, pkg, "all", suite,
133                         arch_all_version, delete_table, delete_col, packages, session)
134     else:
135         # arch: any dominates
136         delete_packages(arch_all_versions, pkg, "any", suite,
137                         highest_arch_any_version, delete_table, delete_col,
138                         packages, session)
139
140 #####################################################
141
142 def remove_duplicate_versions(versions, packages):
143     """ Per-suite&pkg&arch: resolve duplicate versions """
144     # Sort versions into descending order
145     versions.sort(version_cmp)
146     dominant_versions = versions[0]
147     dominated_versions = versions[1:]
148     (dominant_version, dominant_unqiue_id) = dominant_versions
149     pkg = packages[dominant_unqiue_id]["pkg"]
150     arch = packages[dominant_unqiue_id]["arch"]
151     suite = packages[dominant_unqiue_id]["suite"]
152     if arch == "source":
153         delete_table = "src_associations"
154         delete_col = "source"
155     else: # !source
156         delete_table = "bin_associations"
157         delete_col = "bin"
158     # Remove all but the highest
159     delete_packages(dominated_versions, pkg, arch, suite,
160                     dominant_version, delete_table, delete_col, packages)
161     return [dominant_versions]
162
163 ################################################################################
164
165 def cleanup(packages, session):
166     # Build up the index used by the clean up functions
167     d = {}
168     for unique_id in packages.keys():
169         suite = packages[unique_id]["suite"]
170         pkg = packages[unique_id]["pkg"]
171         arch = packages[unique_id]["arch"]
172         version = packages[unique_id]["version"]
173         d.setdefault(suite, {})
174         d[suite].setdefault(pkg, {})
175         d[suite][pkg].setdefault(arch, [])
176         d[suite][pkg][arch].append([version, unique_id])
177     # Clean up old versions
178     for suite in d.keys():
179         for pkg in d[suite].keys():
180             for arch in d[suite][pkg].keys():
181                 versions = d[suite][pkg][arch]
182                 if len(versions) > 1:
183                     d[suite][pkg][arch] = remove_duplicate_versions(versions, packages)
184
185     # Arch: all -> any and vice versa
186     for suite in d.keys():
187         for pkg in d[suite].keys():
188             arches = d[suite][pkg]
189             # If we don't have any arch: all; we've nothing to do
190             if not arches.has_key("all"):
191                 continue
192             # Check to see if we have arch: all and arch: !all (ignoring source)
193             num_arches = len(arches.keys())
194             if arches.has_key("source"):
195                 num_arches -= 1
196             # If we do, remove the duplicates
197             if num_arches > 1:
198                 versions = []
199                 for arch in arches.keys():
200                     if arch != "source":
201                         versions.extend(d[suite][pkg][arch])
202                 resolve_arch_all_vs_any(versions, packages, session)
203
204 ################################################################################
205
206 def write_filelist(suite, component, arch, type, list, packages, dislocated_files):
207     cnf = Config()
208
209     # Work out the filename
210     if arch != "source":
211         if type == "udeb":
212             arch = "debian-installer_binary-%s" % (arch)
213         elif type == "deb":
214             arch = "binary-%s" % (arch)
215     filename = os.path.join(cnf["Dir::Lists"], "%s_%s_%s.list" % (suite, component, arch))
216     output = utils.open_file(filename, "w")
217     # Generate the final list of files
218     files = {}
219     for fileid in list:
220         path = packages[fileid]["path"]
221         filename = packages[fileid]["filename"]
222         file_id = packages[fileid]["file_id"]
223         pkg = packages[fileid]["pkg"]
224         if suite == "stable" and dislocated_files.has_key(file_id):
225             filename = dislocated_files[file_id]
226         else:
227             filename = path + filename
228         if files.has_key(pkg):
229             utils.warn("%s (in %s/%s, %s) is duplicated." % (pkg, suite, component, filename))
230         else:
231             files[pkg] = filename
232     # Sort the files since apt-ftparchive doesn't
233     pkgs = files.keys()
234     pkgs.sort()
235     # Write the list of files out
236     for pkg in pkgs:
237         output.write(files[pkg]+'\n')
238     output.close()
239
240 ################################################################################
241
242 def write_filelists(packages, dislocated_files, session):
243     # Build up the index to iterate over
244     cnf = Config()
245
246     d = {}
247     for unique_id in packages.keys():
248         suite = packages[unique_id]["suite"]
249         component = packages[unique_id]["component"]
250         arch = packages[unique_id]["arch"]
251         packagetype = packages[unique_id]["filetype"]
252         d.setdefault(suite, {})
253         d[suite].setdefault(component, {})
254         d[suite][component].setdefault(arch, {})
255         d[suite][component][arch].setdefault(packagetype, [])
256         d[suite][component][arch][packagetype].append(unique_id)
257     # Flesh out the index
258     if not Options["Suite"]:
259         suites = cnf.SubTree("Suite").List()
260     else:
261         suites = utils.split_args(Options["Suite"])
262     for suite in [ i.lower() for i in suites ]:
263         d.setdefault(suite, {})
264         if not Options["Component"]:
265             components = cnf.ValueList("Suite::%s::Components" % (suite))
266         else:
267             components = utils.split_args(Options["Component"])
268         udeb_components = cnf.ValueList("Suite::%s::UdebComponents" % (suite))
269         for component in components:
270             d[suite].setdefault(component, {})
271             if component in udeb_components:
272                 binary_types = [ "deb", "udeb" ]
273             else:
274                 binary_types = [ "deb" ]
275             if not Options["Architecture"]:
276                 architectures = [ a.arch_string for a in get_suite_architectures(suite, session=session) ]
277             else:
278                 architectures = utils.split_args(Options["Architectures"])
279             for arch in [ i.lower() for i in architectures ]:
280                 d[suite][component].setdefault(arch, {})
281                 if arch == "source":
282                     types = [ "dsc" ]
283                 else:
284                     types = binary_types
285                 for packagetype in types:
286                     d[suite][component][arch].setdefault(packagetype, [])
287     # Then walk it
288     for suite in d.keys():
289         if cnf.has_key("Suite::%s::Components" % (suite)):
290             for component in d[suite].keys():
291                 for arch in d[suite][component].keys():
292                     if arch == "all":
293                         continue
294                     for packagetype in d[suite][component][arch].keys():
295                         filelist = d[suite][component][arch][packagetype]
296                         # If it's a binary, we need to add in the arch: all debs too
297                         if arch != "source":
298                             archall_suite = cnf.get("Make-Suite-File-List::ArchAllMap::%s" % (suite))
299                             if archall_suite:
300                                 filelist.extend(d[archall_suite][component]["all"][packagetype])
301                             elif d[suite][component].has_key("all") and \
302                                      d[suite][component]["all"].has_key(packagetype):
303                                 filelist.extend(d[suite][component]["all"][packagetype])
304                         write_filelist(suite, component, arch, packagetype, filelist,
305                                        packages, dislocated_files)
306         else: # something broken
307             utils.warn("Suite %s has no components." % (suite))
308
309 ################################################################################
310
311 def do_da_do_da():
312     # If we're only doing a subset of suites, ensure we do enough to
313     # be able to do arch: all mapping.
314     if Options["Suite"]:
315         suites = utils.split_args(Options["Suite"])
316         for suite in suites:
317             archall_suite = cnf.get("Make-Suite-File-List::ArchAllMap::%s" % (suite))
318             if archall_suite and archall_suite not in suites:
319                 utils.warn("Adding %s as %s maps Arch: all from it." % (archall_suite, suite))
320                 suites.append(archall_suite)
321         Options["Suite"] = ",".join(suites)
322
323     (con_suites, con_architectures, con_components, check_source) = \
324                  utils.parse_args(Options)
325
326     session = DBConn().session()
327
328     dislocated_files = {}
329
330     # TODO: Fix this properly
331     query_args = {'con_suites': con_suites, 'con_architectures': con_architectures, 'con_components': con_components}
332
333     query = """
334 SELECT b.id, b.package, a.arch_string, b.version, l.path, f.filename, c.name,
335        f.id, su.suite_name, b.type
336   FROM binaries b, bin_associations ba, architecture a, files f, location l,
337        component c, suite su
338   WHERE b.id = ba.bin AND b.file = f.id AND b.architecture = a.id
339     AND f.location = l.id AND l.component = c.id AND ba.suite = su.id
340     %(con_suites)s %(con_architectures)s %(con_components)s""" % query_args
341     if check_source:
342         query += """
343 UNION
344 SELECT s.id, s.source, 'source', s.version, l.path, f.filename, c.name, f.id,
345        su.suite_name, 'dsc'
346   FROM source s, src_associations sa, files f, location l, component c, suite su
347   WHERE s.id = sa.source AND s.file = f.id AND f.location = l.id
348     AND l.component = c.id AND sa.suite = su.id %(con_suites)s %(con_components)s""" % query_args
349
350     # Build up the main index of packages
351     packages = {}
352     unique_id = 0
353
354     q = session.execute(query)
355     for i in q.fetchall():
356         (sourceid, pkg, arch, version, path, filename, component, file_id, suite, filetype) = i
357
358         # 'id' comes from either 'binaries' or 'source', so it's not unique
359         unique_id += 1
360         packages[unique_id] = Dict(sourceid=sourceid, pkg=pkg, arch=arch, version=version,
361                                    path=path, filename=filename,
362                                    component=component, file_id=file_id,
363                                    suite=suite, filetype = filetype)
364     cleanup(packages, session)
365     session.commit()
366     write_filelists(packages, dislocated_files, session)
367
368 ################################################################################
369
370 def main():
371     global Options, Logger
372
373     cnf = Config()
374     Arguments = [('a', "architecture", "Make-Suite-File-List::Options::Architecture", "HasArg"),
375                  ('c', "component", "Make-Suite-File-List::Options::Component", "HasArg"),
376                  ('h', "help", "Make-Suite-File-List::Options::Help"),
377                  ('n', "no-delete", "Make-Suite-File-List::Options::No-Delete"),
378                  ('f', "force", "Make-Suite-File-List::Options::Force"),
379                  ('s', "suite", "Make-Suite-File-List::Options::Suite", "HasArg")]
380     for i in ["architecture", "component", "help", "no-delete", "suite", "force" ]:
381         if not cnf.has_key("Make-Suite-File-List::Options::%s" % (i)):
382             cnf["Make-Suite-File-List::Options::%s" % (i)] = ""
383     apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
384     Options = cnf.SubTree("Make-Suite-File-List::Options")
385     if Options["Help"]:
386         usage()
387
388     DBConn()
389
390     Logger = daklog.Logger(cnf.Cnf, "make-suite-file-list")
391     do_da_do_da()
392     Logger.close()
393
394 #########################################################################################
395
396 if __name__ == '__main__':
397     main()