]> git.decadent.org.uk Git - dak.git/blob - dak/make_suite_file_list.py
56810b29c7a8f8cdde950833e7d9b2aa441920d2
[dak.git] / dak / make_suite_file_list.py
1 #!/usr/bin/env python
2
3 # Generate file lists used by apt-ftparchive to generate Packages and Sources files
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 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 # <elmo> I'm doing it in python btw.. nothing against your monster
23 #        SQL, but the python wins in terms of speed and readiblity
24 # <aj> bah
25 # <aj> you suck!!!!!
26 # <elmo> sorry :(
27 # <aj> you are not!!!
28 # <aj> you mock my SQL!!!!
29 # <elmo> you want have contest of skillz??????
30 # <aj> all your skillz are belong to my sql!!!!
31 # <elmo> yo momma are belong to my python!!!!
32 # <aj> yo momma was SQLin' like a pig last night!
33
34 ################################################################################
35
36 import copy, os, pg, sys
37 import apt_pkg
38 import symlink_dists
39 import daklib.database
40 import daklib.logging
41 import daklib.utils
42
43 ################################################################################
44
45 projectB = None
46 Cnf = None
47 Logger = None
48 Options = None
49
50 ################################################################################
51
52 def Dict(**dict): return dict
53
54 ################################################################################
55
56 def usage (exit_code=0):
57     print """Usage: dak make-suite-file-list [OPTION]
58 Write out file lists suitable for use with apt-ftparchive.
59
60   -a, --architecture=ARCH   only write file lists for this architecture
61   -c, --component=COMPONENT only write file lists for this component
62   -h, --help                show this help and exit
63   -n, --no-delete           don't delete older versions
64   -s, --suite=SUITE         only write file lists for this suite
65
66 ARCH, COMPONENT and SUITE can be space separated lists, e.g.
67     --architecture=\"m68k i386\""""
68     sys.exit(exit_code)
69
70 ################################################################################
71
72 def version_cmp(a, b):
73     return -apt_pkg.VersionCompare(a[0], b[0])
74
75 #####################################################
76
77 def delete_packages(delete_versions, pkg, dominant_arch, suite,
78                     dominant_version, delete_table, delete_col, packages):
79     suite_id = daklib.database.get_suite_id(suite)
80     for version in delete_versions:
81         delete_unique_id = version[1]
82         if not packages.has_key(delete_unique_id):
83             continue
84         delete_version = version[0]
85         delete_id = packages[delete_unique_id]["id"]
86         delete_arch = packages[delete_unique_id]["arch"]
87         if not Cnf.Find("Suite::%s::Untouchable" % (suite)):
88             if Options["No-Delete"]:
89                 print "Would delete %s_%s_%s in %s in favour of %s_%s" % (pkg, delete_arch, delete_version, suite, dominant_version, dominant_arch)
90             else:
91                 Logger.log(["dominated", pkg, delete_arch, delete_version, dominant_version, dominant_arch])
92                 projectB.query("DELETE FROM %s WHERE suite = %s AND %s = %s" % (delete_table, suite_id, delete_col, delete_id))
93             del packages[delete_unique_id]
94         else:
95             if Options["No-Delete"]:
96                 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)
97             else:
98                 Logger.log(["dominated but untouchable", pkg, delete_arch, delete_version, dominant_version, dominant_arch])
99
100 #####################################################
101
102 # Per-suite&pkg: resolve arch-all, vs. arch-any, assumes only one arch-all
103 def resolve_arch_all_vs_any(versions, packages):
104     arch_all_version = None
105     arch_any_versions = copy.copy(versions)
106     for i in arch_any_versions:
107         unique_id = i[1]
108         arch = packages[unique_id]["arch"]
109         if arch == "all":
110             arch_all_versions = [i]
111             arch_all_version = i[0]
112             arch_any_versions.remove(i)
113     # Sort arch: any versions into descending order
114     arch_any_versions.sort(version_cmp)
115     highest_arch_any_version = arch_any_versions[0][0]
116
117     pkg = packages[unique_id]["pkg"]
118     suite = packages[unique_id]["suite"]
119     delete_table = "bin_associations"
120     delete_col = "bin"
121
122     if apt_pkg.VersionCompare(highest_arch_any_version, arch_all_version) < 1:
123         # arch: all dominates
124         delete_packages(arch_any_versions, pkg, "all", suite,
125                         arch_all_version, delete_table, delete_col, packages)
126     else:
127         # arch: any dominates
128         delete_packages(arch_all_versions, pkg, "any", suite,
129                         highest_arch_any_version, delete_table, delete_col,
130                         packages)
131
132 #####################################################
133
134 # Per-suite&pkg&arch: resolve duplicate versions
135 def remove_duplicate_versions(versions, packages):
136     # Sort versions into descending order
137     versions.sort(version_cmp)
138     dominant_versions = versions[0]
139     dominated_versions = versions[1:]
140     (dominant_version, dominant_unqiue_id) = dominant_versions
141     pkg = packages[dominant_unqiue_id]["pkg"]
142     arch = packages[dominant_unqiue_id]["arch"]
143     suite = packages[dominant_unqiue_id]["suite"]
144     if arch == "source":
145         delete_table = "src_associations"
146         delete_col = "source"
147     else: # !source
148         delete_table = "bin_associations"
149         delete_col = "bin"
150     # Remove all but the highest
151     delete_packages(dominated_versions, pkg, arch, suite,
152                     dominant_version, delete_table, delete_col, packages)
153     return [dominant_versions]
154
155 ################################################################################
156
157 def cleanup(packages):
158     # Build up the index used by the clean up functions
159     d = {}
160     for unique_id in packages.keys():
161         suite = packages[unique_id]["suite"]
162         pkg = packages[unique_id]["pkg"]
163         arch = packages[unique_id]["arch"]
164         version = packages[unique_id]["version"]
165         d.setdefault(suite, {})
166         d[suite].setdefault(pkg, {})
167         d[suite][pkg].setdefault(arch, [])
168         d[suite][pkg][arch].append([version, unique_id])
169     # Clean up old versions
170     for suite in d.keys():
171         for pkg in d[suite].keys():
172             for arch in d[suite][pkg].keys():
173                 versions = d[suite][pkg][arch]
174                 if len(versions) > 1:
175                     d[suite][pkg][arch] = remove_duplicate_versions(versions, packages)
176
177     # Arch: all -> any and vice versa
178     for suite in d.keys():
179         for pkg in d[suite].keys():
180             arches = d[suite][pkg]
181             # If we don't have any arch: all; we've nothing to do
182             if not arches.has_key("all"):
183                 continue
184             # Check to see if we have arch: all and arch: !all (ignoring source)
185             num_arches = len(arches.keys())
186             if arches.has_key("source"):
187                 num_arches -= 1
188             # If we do, remove the duplicates
189             if num_arches > 1:
190                 versions = []
191                 for arch in arches.keys():
192                     if arch != "source":
193                         versions.extend(d[suite][pkg][arch])
194                 resolve_arch_all_vs_any(versions, packages)
195
196 ################################################################################
197
198 def write_legacy_mixed_filelist(suite, list, packages, dislocated_files):
199     # Work out the filename
200     filename = os.path.join(Cnf["Dir::Lists"], "%s_-_all.list" % (suite))
201     output = daklib.utils.open_file(filename, "w")
202     # Generate the final list of files
203     files = {}
204     for id in list:
205         path = packages[id]["path"]
206         filename = packages[id]["filename"]
207         file_id = packages[id]["file_id"]
208         if suite == "stable" and dislocated_files.has_key(file_id):
209             filename = dislocated_files[file_id]
210         else:
211             filename = path + filename
212         if files.has_key(filename):
213             daklib.utils.warn("%s (in %s) is duplicated." % (filename, suite))
214         else:
215             files[filename] = ""
216     # Sort the files since apt-ftparchive doesn't
217     keys = files.keys()
218     keys.sort()
219     # Write the list of files out
220     for file in keys:
221         output.write(file+'\n')
222     output.close()
223
224 ############################################################
225
226 def write_filelist(suite, component, arch, type, list, packages, dislocated_files):
227     # Work out the filename
228     if arch != "source":
229         if type == "udeb":
230             arch = "debian-installer_binary-%s" % (arch)
231         elif type == "deb":
232             arch = "binary-%s" % (arch)
233     filename = os.path.join(Cnf["Dir::Lists"], "%s_%s_%s.list" % (suite, component, arch))
234     output = daklib.utils.open_file(filename, "w")
235     # Generate the final list of files
236     files = {}
237     for id in list:
238         path = packages[id]["path"]
239         filename = packages[id]["filename"]
240         file_id = packages[id]["file_id"]
241         pkg = packages[id]["pkg"]
242         if suite == "stable" and dislocated_files.has_key(file_id):
243             filename = dislocated_files[file_id]
244         else:
245             filename = path + filename
246         if files.has_key(pkg):
247             daklib.utils.warn("%s (in %s/%s, %s) is duplicated." % (pkg, suite, component, filename))
248         else:
249             files[pkg] = filename
250     # Sort the files since apt-ftparchive doesn't
251     pkgs = files.keys()
252     pkgs.sort()
253     # Write the list of files out
254     for pkg in pkgs:
255         output.write(files[pkg]+'\n')
256     output.close()
257
258 ################################################################################
259
260 def write_filelists(packages, dislocated_files):
261     # Build up the index to iterate over
262     d = {}
263     for unique_id in packages.keys():
264         suite = packages[unique_id]["suite"]
265         component = packages[unique_id]["component"]
266         arch = packages[unique_id]["arch"]
267         type = packages[unique_id]["type"]
268         d.setdefault(suite, {})
269         d[suite].setdefault(component, {})
270         d[suite][component].setdefault(arch, {})
271         d[suite][component][arch].setdefault(type, [])
272         d[suite][component][arch][type].append(unique_id)
273     # Flesh out the index
274     if not Options["Suite"]:
275         suites = Cnf.SubTree("Suite").List()
276     else:
277         suites = daklib.utils.split_args(Options["Suite"])
278     for suite in [ i.lower() for i in suites ]:
279         d.setdefault(suite, {})
280         if not Options["Component"]:
281             components = Cnf.ValueList("Suite::%s::Components" % (suite))
282         else:
283             components = daklib.utils.split_args(Options["Component"])
284         udeb_components = Cnf.ValueList("Suite::%s::UdebComponents" % (suite))
285         udeb_components = udeb_components
286         for component in components:
287             d[suite].setdefault(component, {})
288             if component in udeb_components:
289                 binary_types = [ "deb", "udeb" ]
290             else:
291                 binary_types = [ "deb" ]
292             if not Options["Architecture"]:
293                 architectures = Cnf.ValueList("Suite::%s::Architectures" % (suite))
294             else:
295                 architectures = daklib.utils.split_args(Options["Architectures"])
296             for arch in [ i.lower() for i in architectures ]:
297                 d[suite][component].setdefault(arch, {})
298                 if arch == "source":
299                     types = [ "dsc" ]
300                 else:
301                     types = binary_types
302                 for type in types:
303                     d[suite][component][arch].setdefault(type, [])
304     # Then walk it
305     for suite in d.keys():
306         if Cnf.has_key("Suite::%s::Components" % (suite)):
307             for component in d[suite].keys():
308                 for arch in d[suite][component].keys():
309                     if arch == "all":
310                         continue
311                     for type in d[suite][component][arch].keys():
312                         list = d[suite][component][arch][type]
313                         # If it's a binary, we need to add in the arch: all debs too
314                         if arch != "source":
315                             archall_suite = Cnf.get("Make-Suite-File-List::ArchAllMap::%s" % (suite))
316                             if archall_suite:
317                                 list.extend(d[archall_suite][component]["all"][type])
318                             elif d[suite][component].has_key("all") and \
319                                      d[suite][component]["all"].has_key(type):
320                                 list.extend(d[suite][component]["all"][type])
321                         write_filelist(suite, component, arch, type, list,
322                                        packages, dislocated_files)
323         else: # legacy-mixed suite
324             list = []
325             for component in d[suite].keys():
326                 for arch in d[suite][component].keys():
327                     for type in d[suite][component][arch].keys():
328                         list.extend(d[suite][component][arch][type])
329             write_legacy_mixed_filelist(suite, list, packages, dislocated_files)
330
331 ################################################################################
332
333 # Want to use stable dislocation support: True or false?
334 def stable_dislocation_p():
335     # If the support is not explicitly enabled, assume it's disabled
336     if not Cnf.FindB("Dinstall::StableDislocationSupport"):
337         return 0
338     # If we don't have a stable suite, obviously a no-op
339     if not Cnf.has_key("Suite::Stable"):
340         return 0
341     # If the suite(s) weren't explicitly listed, all suites are done
342     if not Options["Suite"]:
343         return 1
344     # Otherwise, look in what suites the user specified
345     suites = daklib.utils.split_args(Options["Suite"])
346
347     if "stable" in suites:
348         return 1
349     else:
350         return 0
351
352 ################################################################################
353
354 def do_da_do_da():
355     # If we're only doing a subset of suites, ensure we do enough to
356     # be able to do arch: all mapping.
357     if Options["Suite"]:
358         suites = daklib.utils.split_args(Options["Suite"])
359         for suite in suites:
360             archall_suite = Cnf.get("Make-Suite-File-List::ArchAllMap::%s" % (suite))
361             if archall_suite and archall_suite not in suites:
362                 daklib.utils.warn("Adding %s as %s maps Arch: all from it." % (archall_suite, suite))
363                 suites.append(archall_suite)
364         Options["Suite"] = ",".join(suites)
365     
366     (con_suites, con_architectures, con_components, check_source) = \
367                  daklib.utils.parse_args(Options)
368
369     if stable_dislocation_p():
370         dislocated_files = symlink_dists.find_dislocated_stable(Cnf, projectB)
371     else:
372         dislocated_files = {}
373
374     query = """
375 SELECT b.id, b.package, a.arch_string, b.version, l.path, f.filename, c.name,
376        f.id, su.suite_name, b.type
377   FROM binaries b, bin_associations ba, architecture a, files f, location l,
378        component c, suite su
379   WHERE b.id = ba.bin AND b.file = f.id AND b.architecture = a.id
380     AND f.location = l.id AND l.component = c.id AND ba.suite = su.id
381     %s %s %s""" % (con_suites, con_architectures, con_components)
382     if check_source:
383         query += """
384 UNION
385 SELECT s.id, s.source, 'source', s.version, l.path, f.filename, c.name, f.id,
386        su.suite_name, 'dsc'
387   FROM source s, src_associations sa, files f, location l, component c, suite su
388   WHERE s.id = sa.source AND s.file = f.id AND f.location = l.id
389     AND l.component = c.id AND sa.suite = su.id %s %s""" % (con_suites, con_components)
390     q = projectB.query(query)
391     ql = q.getresult()
392     # Build up the main index of packages
393     packages = {}
394     unique_id = 0
395     for i in ql:
396         (id, pkg, arch, version, path, filename, component, file_id, suite, type) = i
397         # 'id' comes from either 'binaries' or 'source', so it's not unique
398         unique_id += 1
399         packages[unique_id] = Dict(id=id, pkg=pkg, arch=arch, version=version,
400                                    path=path, filename=filename,
401                                    component=component, file_id=file_id,
402                                    suite=suite, type = type)
403     cleanup(packages)
404     write_filelists(packages, dislocated_files)
405
406 ################################################################################
407
408 def main():
409     global Cnf, projectB, Options, Logger
410
411     Cnf = daklib.utils.get_conf()
412     Arguments = [('a', "architecture", "Make-Suite-File-List::Options::Architecture", "HasArg"),
413                  ('c', "component", "Make-Suite-File-List::Options::Component", "HasArg"),
414                  ('h', "help", "Make-Suite-File-List::Options::Help"),
415                  ('n', "no-delete", "Make-Suite-File-List::Options::No-Delete"),
416                  ('s', "suite", "Make-Suite-File-List::Options::Suite", "HasArg")]
417     for i in ["architecture", "component", "help", "no-delete", "suite" ]:
418         if not Cnf.has_key("Make-Suite-File-List::Options::%s" % (i)):
419             Cnf["Make-Suite-File-List::Options::%s" % (i)] = ""
420     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
421     Options = Cnf.SubTree("Make-Suite-File-List::Options")
422     if Options["Help"]:
423         usage()
424
425     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
426     daklib.database.init(Cnf, projectB)
427     Logger = daklib.logging.Logger(Cnf, "make-suite-file-list")
428     do_da_do_da()
429     Logger.close()
430
431 #########################################################################################
432
433 if __name__ == '__main__':
434     main()