]> git.decadent.org.uk Git - dak.git/blob - dak/make_suite_file_list.py
Merge commit 'ftpmaster/master' into psycopg2
[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 from daklib import database
39 from daklib import logging
40 from daklib import utils
41
42 ################################################################################
43
44 projectB = None
45 Cnf = None
46 Logger = None
47 Options = None
48
49 ################################################################################
50
51 def Dict(**dict): return dict
52
53 ################################################################################
54
55 def usage (exit_code=0):
56     print """Usage: dak make-suite-file-list [OPTION]
57 Write out file lists suitable for use with apt-ftparchive.
58
59   -a, --architecture=ARCH   only write file lists for this architecture
60   -c, --component=COMPONENT only write file lists for this component
61   -f, --force               ignore Untouchable suite directives in dak.conf
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 = 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)) or Options["Force"]:
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 = utils.open_file(filename, "w")
202     # Generate the final list of files
203     files = {}
204     for fileid in list:
205         path = packages[fileid]["path"]
206         filename = packages[fileid]["filename"]
207         file_id = packages[fileid]["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             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 outfile in keys:
221         output.write(outfile+'\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 = utils.open_file(filename, "w")
235     # Generate the final list of files
236     files = {}
237     for fileid in list:
238         path = packages[fileid]["path"]
239         filename = packages[fileid]["filename"]
240         file_id = packages[fileid]["file_id"]
241         pkg = packages[fileid]["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             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         packagetype = 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(packagetype, [])
272         d[suite][component][arch][packagetype].append(unique_id)
273     # Flesh out the index
274     if not Options["Suite"]:
275         suites = Cnf.SubTree("Suite").List()
276     else:
277         suites = 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 = utils.split_args(Options["Component"])
284         udeb_components = Cnf.ValueList("Suite::%s::UdebComponents" % (suite))
285         for component in components:
286             d[suite].setdefault(component, {})
287             if component in udeb_components:
288                 binary_types = [ "deb", "udeb" ]
289             else:
290                 binary_types = [ "deb" ]
291             if not Options["Architecture"]:
292                 architectures = Cnf.ValueList("Suite::%s::Architectures" % (suite))
293             else:
294                 architectures = utils.split_args(Options["Architectures"])
295             for arch in [ i.lower() for i in architectures ]:
296                 d[suite][component].setdefault(arch, {})
297                 if arch == "source":
298                     types = [ "dsc" ]
299                 else:
300                     types = binary_types
301                 for packagetype in types:
302                     d[suite][component][arch].setdefault(packagetype, [])
303     # Then walk it
304     for suite in d.keys():
305         if Cnf.has_key("Suite::%s::Components" % (suite)):
306             for component in d[suite].keys():
307                 for arch in d[suite][component].keys():
308                     if arch == "all":
309                         continue
310                     for packagetype in d[suite][component][arch].keys():
311                         filelist = d[suite][component][arch][packagetype]
312                         # If it's a binary, we need to add in the arch: all debs too
313                         if arch != "source":
314                             archall_suite = Cnf.get("Make-Suite-File-List::ArchAllMap::%s" % (suite))
315                             if archall_suite:
316                                 filelist.extend(d[archall_suite][component]["all"][packagetype])
317                             elif d[suite][component].has_key("all") and \
318                                      d[suite][component]["all"].has_key(packagetype):
319                                 filelist.extend(d[suite][component]["all"][packagetype])
320                         write_filelist(suite, component, arch, packagetype, filelist,
321                                        packages, dislocated_files)
322         else: # legacy-mixed suite
323             filelist = []
324             for component in d[suite].keys():
325                 for arch in d[suite][component].keys():
326                     for packagetype in d[suite][component][arch].keys():
327                         filelist.extend(d[suite][component][arch][packagetype])
328             write_legacy_mixed_filelist(suite, filelist, packages, dislocated_files)
329
330 ################################################################################
331
332 def do_da_do_da():
333     # If we're only doing a subset of suites, ensure we do enough to
334     # be able to do arch: all mapping.
335     if Options["Suite"]:
336         suites = utils.split_args(Options["Suite"])
337         for suite in suites:
338             archall_suite = Cnf.get("Make-Suite-File-List::ArchAllMap::%s" % (suite))
339             if archall_suite and archall_suite not in suites:
340                 utils.warn("Adding %s as %s maps Arch: all from it." % (archall_suite, suite))
341                 suites.append(archall_suite)
342         Options["Suite"] = ",".join(suites)
343
344     (con_suites, con_architectures, con_components, check_source) = \
345                  utils.parse_args(Options)
346
347     dislocated_files = {}
348
349     query = """
350 SELECT b.id, b.package, a.arch_string, b.version, l.path, f.filename, c.name,
351        f.id, su.suite_name, b.type
352   FROM binaries b, bin_associations ba, architecture a, files f, location l,
353        component c, suite su
354   WHERE b.id = ba.bin AND b.file = f.id AND b.architecture = a.id
355     AND f.location = l.id AND l.component = c.id AND ba.suite = su.id
356     %s %s %s""" % (con_suites, con_architectures, con_components)
357     if check_source:
358         query += """
359 UNION
360 SELECT s.id, s.source, 'source', s.version, l.path, f.filename, c.name, f.id,
361        su.suite_name, 'dsc'
362   FROM source s, src_associations sa, files f, location l, component c, suite su
363   WHERE s.id = sa.source AND s.file = f.id AND f.location = l.id
364     AND l.component = c.id AND sa.suite = su.id %s %s""" % (con_suites, con_components)
365     q = projectB.query(query)
366     ql = q.getresult()
367     # Build up the main index of packages
368     packages = {}
369     unique_id = 0
370     for i in ql:
371         (sourceid, pkg, arch, version, path, filename, component, file_id, suite, filetype) = i
372         # 'id' comes from either 'binaries' or 'source', so it's not unique
373         unique_id += 1
374         packages[unique_id] = Dict(sourceid=sourceid, pkg=pkg, arch=arch, version=version,
375                                    path=path, filename=filename,
376                                    component=component, file_id=file_id,
377                                    suite=suite, filetype = filetype)
378     cleanup(packages)
379     write_filelists(packages, dislocated_files)
380
381 ################################################################################
382
383 def main():
384     global Cnf, projectB, Options, Logger
385
386     Cnf = utils.get_conf()
387     Arguments = [('a', "architecture", "Make-Suite-File-List::Options::Architecture", "HasArg"),
388                  ('c', "component", "Make-Suite-File-List::Options::Component", "HasArg"),
389                  ('h', "help", "Make-Suite-File-List::Options::Help"),
390                  ('n', "no-delete", "Make-Suite-File-List::Options::No-Delete"),
391                  ('f', "force", "Make-Suite-File-List::Options::Force"),
392                  ('s', "suite", "Make-Suite-File-List::Options::Suite", "HasArg")]
393     for i in ["architecture", "component", "help", "no-delete", "suite", "force" ]:
394         if not Cnf.has_key("Make-Suite-File-List::Options::%s" % (i)):
395             Cnf["Make-Suite-File-List::Options::%s" % (i)] = ""
396     apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
397     Options = Cnf.SubTree("Make-Suite-File-List::Options")
398     if Options["Help"]:
399         usage()
400
401     projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
402     database.init(Cnf, projectB)
403     Logger = logging.Logger(Cnf, "make-suite-file-list")
404     do_da_do_da()
405     Logger.close()
406
407 #########################################################################################
408
409 if __name__ == '__main__':
410     main()