]> git.decadent.org.uk Git - dak.git/blob - dak/generate_packages_sources2.py
Merge remote-tracking branch 'nthykier/auto-decruft'
[dak.git] / dak / generate_packages_sources2.py
1 #!/usr/bin/python
2
3 """
4 Generate Packages/Sources files
5
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2011  Ansgar Burchardt <ansgar@debian.org>
8 @copyright: Based on daklib/lists.py and dak/generate_filelist.py:
9             2009-2011  Torsten Werner <twerner@debian.org>
10 @copyright: Based on dak/generate_packages_sources.py:
11             2000, 2001, 2002, 2006  James Troup <james@nocrew.org>
12             2009  Mark Hymers <mhy@debian.org>
13             2010  Joerg Jaspert <joerg@debian.org>
14 @license: GNU General Public License version 2 or later
15 """
16
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26
27 # You should have received a copy of the GNU General Public License
28 # along with this program; if not, write to the Free Software
29 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30
31 import apt_pkg, sys
32
33 def usage():
34     print """Usage: dak generate-packages-sources2 [OPTIONS]
35 Generate the Packages/Sources files
36
37   -a, --archive=ARCHIVE        process suites in ARCHIVE
38   -s, --suite=SUITE            process this suite
39                                Default: All suites not marked 'untouchable'
40   -f, --force                  Allow processing of untouchable suites
41                                CAREFUL: Only to be used at point release time!
42   -h, --help                   show this help and exit
43
44 SUITE can be a space seperated list, e.g.
45    --suite=unstable testing
46 """
47     sys.exit()
48
49 #############################################################################
50
51 # Here be dragons.
52 _sources_query = R"""
53 SELECT
54
55   (SELECT
56      STRING_AGG(
57        CASE
58          WHEN key = 'Source' THEN E'Package\: '
59          WHEN key = 'Files' THEN E'Files\:\n ' || f.md5sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
60          WHEN key = 'Checksums-Sha1' THEN E'Checksums-Sha1\:\n ' || f.sha1sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
61          WHEN key = 'Checksums-Sha256' THEN E'Checksums-Sha256\:\n ' || f.sha256sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
62          ELSE key || E'\: '
63        END || value, E'\n' ORDER BY mk.ordering, mk.key)
64    FROM
65      source_metadata sm
66      JOIN metadata_keys mk ON mk.key_id = sm.key_id
67    WHERE s.id=sm.src_id
68   )
69   ||
70   CASE
71     WHEN src_associations_full.extra_source THEN E'\nExtra-Source-Only\: yes'
72     ELSE ''
73   END
74   ||
75   E'\nDirectory\: pool/' || :component_name || '/' || SUBSTRING(f.filename FROM E'\\A(.*)/[^/]*\\Z')
76   ||
77   E'\nPriority\: ' || COALESCE(pri.priority, 'extra')
78   ||
79   E'\nSection\: ' || COALESCE(sec.section, 'misc')
80
81 FROM
82
83 source s
84 JOIN src_associations_full ON src_associations_full.suite = :suite AND s.id = src_associations_full.source
85 JOIN files f ON s.file=f.id
86 JOIN files_archive_map fam
87   ON fam.file_id = f.id
88      AND fam.archive_id = (SELECT archive_id FROM suite WHERE id = :suite)
89      AND fam.component_id = :component
90 LEFT JOIN override o ON o.package = s.source
91                      AND o.suite = :overridesuite
92                      AND o.component = :component
93                      AND o.type = :dsc_type
94 LEFT JOIN section sec ON o.section = sec.id
95 LEFT JOIN priority pri ON o.priority = pri.id
96
97 WHERE
98   (src_associations_full.extra_source OR o.suite IS NOT NULL)
99
100 ORDER BY
101 s.source, s.version
102 """
103
104 def generate_sources(suite_id, component_id):
105     global _sources_query
106     from daklib.filewriter import SourcesFileWriter
107     from daklib.dbconn import Component, DBConn, OverrideType, Suite
108     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
109
110     session = DBConn().session()
111     dsc_type = session.query(OverrideType).filter_by(overridetype='dsc').one().overridetype_id
112
113     suite = session.query(Suite).get(suite_id)
114     component = session.query(Component).get(component_id)
115
116     overridesuite_id = suite.get_overridesuite().suite_id
117
118     writer_args = {
119             'archive': suite.archive.path,
120             'suite': suite.suite_name,
121             'component': component.component_name
122     }
123     if suite.indices_compression is not None:
124         writer_args['compression'] = suite.indices_compression
125     writer = SourcesFileWriter(**writer_args)
126     output = writer.open()
127
128     # run query and write Sources
129     r = session.execute(_sources_query, {"suite": suite_id, "component": component_id, "component_name": component.component_name, "dsc_type": dsc_type, "overridesuite": overridesuite_id})
130     for (stanza,) in r:
131         print >>output, stanza
132         print >>output, ""
133
134     writer.close()
135
136     message = ["generate sources", suite.suite_name, component.component_name]
137     session.rollback()
138     return (PROC_STATUS_SUCCESS, message)
139
140 #############################################################################
141
142 # Here be large dragons.
143 _packages_query = R"""
144 WITH
145
146   tmp AS (
147     SELECT
148       b.id AS binary_id,
149       b.package AS package,
150       b.version AS version,
151       b.architecture AS architecture,
152       b.source AS source_id,
153       s.source AS source,
154       f.filename AS filename,
155       f.size AS size,
156       f.md5sum AS md5sum,
157       f.sha1sum AS sha1sum,
158       f.sha256sum AS sha256sum
159     FROM
160       binaries b
161       JOIN bin_associations ba ON b.id = ba.bin
162       JOIN files f ON f.id = b.file
163       JOIN files_archive_map fam ON f.id = fam.file_id AND fam.archive_id = :archive_id
164       JOIN source s ON b.source = s.id
165     WHERE
166       (b.architecture = :arch_all OR b.architecture = :arch) AND b.type = :type_name
167       AND ba.suite = :suite
168       AND fam.component_id = :component
169   )
170
171 SELECT
172   (SELECT
173      STRING_AGG(key || E'\: ' || value, E'\n' ORDER BY ordering, key)
174    FROM
175      (SELECT key, ordering,
176         CASE WHEN :include_long_description = 'false' AND key = 'Description'
177           THEN SUBSTRING(value FROM E'\\A[^\n]*')
178           ELSE value
179         END AS value
180       FROM
181         binaries_metadata bm
182         JOIN metadata_keys mk ON mk.key_id = bm.key_id
183       WHERE
184         bm.bin_id = tmp.binary_id
185         AND key != ALL (:metadata_skip)
186      ) AS metadata
187   )
188   || COALESCE(E'\n' || (SELECT
189      STRING_AGG(key || E'\: ' || value, E'\n' ORDER BY key)
190    FROM external_overrides eo
191    WHERE
192      eo.package = tmp.package
193      AND eo.suite = :overridesuite AND eo.component = :component
194   ), '')
195   || E'\nSection\: ' || sec.section
196   || E'\nPriority\: ' || pri.priority
197   || E'\nFilename\: pool/' || :component_name || '/' || tmp.filename
198   || E'\nSize\: ' || tmp.size
199   || E'\nMD5sum\: ' || tmp.md5sum
200   || E'\nSHA1\: ' || tmp.sha1sum
201   || E'\nSHA256\: ' || tmp.sha256sum
202
203 FROM
204   tmp
205   JOIN override o ON o.package = tmp.package
206   JOIN section sec ON sec.id = o.section
207   JOIN priority pri ON pri.id = o.priority
208
209 WHERE
210   (
211       architecture <> :arch_all
212     OR
213       (architecture = :arch_all AND source_id IN (SELECT source_id FROM tmp WHERE architecture <> :arch_all))
214     OR
215       (architecture = :arch_all AND source NOT IN (SELECT DISTINCT source FROM tmp WHERE architecture <> :arch_all))
216   )
217   AND
218     o.type = :type_id AND o.suite = :overridesuite AND o.component = :component
219
220 ORDER BY tmp.source, tmp.package, tmp.version
221 """
222
223 def generate_packages(suite_id, component_id, architecture_id, type_name):
224     global _packages_query
225     from daklib.filewriter import PackagesFileWriter
226     from daklib.dbconn import Architecture, Component, DBConn, OverrideType, Suite
227     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
228
229     session = DBConn().session()
230     arch_all_id = session.query(Architecture).filter_by(arch_string='all').one().arch_id
231     type_id = session.query(OverrideType).filter_by(overridetype=type_name).one().overridetype_id
232
233     suite = session.query(Suite).get(suite_id)
234     component = session.query(Component).get(component_id)
235     architecture = session.query(Architecture).get(architecture_id)
236
237     overridesuite_id = suite.get_overridesuite().suite_id
238     include_long_description = suite.include_long_description
239
240     # We currently filter out the "Tag" line. They are set by external
241     # overrides and NOT by the maintainer. And actually having it set by
242     # maintainer means we output it twice at the moment -> which breaks
243     # dselect.
244     metadata_skip = ["Section", "Priority", "Tag"]
245     if include_long_description:
246         metadata_skip.append("Description-md5")
247
248     writer_args = {
249             'archive': suite.archive.path,
250             'suite': suite.suite_name,
251             'component': component.component_name,
252             'architecture': architecture.arch_string,
253             'debtype': type_name
254     }
255     if suite.indices_compression is not None:
256         writer_args['compression'] = suite.indices_compression
257     writer = PackagesFileWriter(**writer_args)
258     output = writer.open()
259
260     r = session.execute(_packages_query, {"archive_id": suite.archive.archive_id,
261         "suite": suite_id, "component": component_id, 'component_name': component.component_name,
262         "arch": architecture_id, "type_id": type_id, "type_name": type_name, "arch_all": arch_all_id,
263         "overridesuite": overridesuite_id, "metadata_skip": metadata_skip,
264         "include_long_description": 'true' if include_long_description else 'false'})
265     for (stanza,) in r:
266         print >>output, stanza
267         print >>output, ""
268
269     writer.close()
270
271     message = ["generate-packages", suite.suite_name, component.component_name, architecture.arch_string]
272     session.rollback()
273     return (PROC_STATUS_SUCCESS, message)
274
275 #############################################################################
276
277 _translations_query = """
278 WITH
279   override_suite AS
280     (SELECT
281       s.id AS id,
282       COALESCE(os.id, s.id) AS overridesuite_id
283       FROM suite AS s LEFT JOIN suite AS os ON s.overridesuite = os.suite_name)
284
285 SELECT
286      E'Package\: ' || b.package
287   || E'\nDescription-md5\: ' || bm_description_md5.value
288   || E'\nDescription-en\: ' || bm_description.value
289   || E'\n'
290 FROM binaries b
291   -- join tables for suite and component
292   JOIN bin_associations ba ON b.id = ba.bin
293   JOIN override_suite os ON os.id = ba.suite
294   JOIN override o ON b.package = o.package AND o.suite = os.overridesuite_id AND o.type = (SELECT id FROM override_type WHERE type = 'deb')
295
296   -- join tables for Description and Description-md5
297   JOIN binaries_metadata bm_description ON b.id = bm_description.bin_id AND bm_description.key_id = (SELECT key_id FROM metadata_keys WHERE key = 'Description')
298   JOIN binaries_metadata bm_description_md5 ON b.id = bm_description_md5.bin_id AND bm_description_md5.key_id = (SELECT key_id FROM metadata_keys WHERE key = 'Description-md5')
299
300   -- we want to sort by source name
301   JOIN source s ON b.source = s.id
302
303 WHERE ba.suite = :suite AND o.component = :component
304 GROUP BY b.package, bm_description_md5.value, bm_description.value
305 ORDER BY MIN(s.source), b.package, bm_description_md5.value
306 """
307
308 def generate_translations(suite_id, component_id):
309     global _translations_query
310     from daklib.filewriter import TranslationFileWriter
311     from daklib.dbconn import DBConn, Suite, Component
312     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
313
314     session = DBConn().session()
315     suite = session.query(Suite).get(suite_id)
316     component = session.query(Component).get(component_id)
317
318     writer_args = {
319             'archive': suite.archive.path,
320             'suite': suite.suite_name,
321             'component': component.component_name,
322             'language': 'en',
323     }
324     if suite.i18n_compression is not None:
325         writer_args['compression'] = suite.i18n_compression
326     writer = TranslationFileWriter(**writer_args)
327     output = writer.open()
328
329     r = session.execute(_translations_query, {"suite": suite_id, "component": component_id})
330     for (stanza,) in r:
331         print >>output, stanza
332
333     writer.close()
334
335     message = ["generate-translations", suite.suite_name, component.component_name]
336     session.rollback()
337     return (PROC_STATUS_SUCCESS, message)
338
339 #############################################################################
340
341 def main():
342     from daklib.config import Config
343     from daklib import daklog
344
345     cnf = Config()
346
347     Arguments = [('h',"help","Generate-Packages-Sources::Options::Help"),
348                  ('a','archive','Generate-Packages-Sources::Options::Archive','HasArg'),
349                  ('s',"suite","Generate-Packages-Sources::Options::Suite"),
350                  ('f',"force","Generate-Packages-Sources::Options::Force"),
351                  ('o','option','','ArbItem')]
352
353     suite_names = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
354     try:
355         Options = cnf.subtree("Generate-Packages-Sources::Options")
356     except KeyError:
357         Options = {}
358
359     if Options.has_key("Help"):
360         usage()
361
362     from daklib.dakmultiprocessing import DakProcessPool, PROC_STATUS_SUCCESS, PROC_STATUS_SIGNALRAISED
363     pool = DakProcessPool()
364
365     logger = daklog.Logger('generate-packages-sources2')
366
367     from daklib.dbconn import Component, DBConn, get_suite, Suite, Archive
368     session = DBConn().session()
369     session.execute("SELECT add_missing_description_md5()")
370     session.commit()
371
372     if Options.has_key("Suite"):
373         suites = []
374         for s in suite_names:
375             suite = get_suite(s.lower(), session)
376             if suite:
377                 suites.append(suite)
378             else:
379                 print "I: Cannot find suite %s" % s
380                 logger.log(['Cannot find suite %s' % s])
381     else:
382         query = session.query(Suite).filter(Suite.untouchable == False)
383         if 'Archive' in Options:
384             query = query.join(Suite.archive).filter(Archive.archive_name==Options['Archive'])
385         suites = query.all()
386
387     force = Options.has_key("Force") and Options["Force"]
388
389
390     def parse_results(message):
391         # Split out into (code, msg)
392         code, msg = message
393         if code == PROC_STATUS_SUCCESS:
394             logger.log([msg])
395         elif code == PROC_STATUS_SIGNALRAISED:
396             logger.log(['E: Subprocess recieved signal ', msg])
397         else:
398             logger.log(['E: ', msg])
399
400     # Lock tables so that nobody can change things underneath us
401     session.execute("LOCK TABLE src_associations IN SHARE MODE")
402     session.execute("LOCK TABLE bin_associations IN SHARE MODE")
403
404     for s in suites:
405         component_ids = [ c.component_id for c in s.components ]
406         if s.untouchable and not force:
407             import daklib.utils
408             daklib.utils.fubar("Refusing to touch %s (untouchable and not forced)" % s.suite_name)
409         for c in component_ids:
410             pool.apply_async(generate_sources, [s.suite_id, c], callback=parse_results)
411             if not s.include_long_description:
412                 pool.apply_async(generate_translations, [s.suite_id, c], callback=parse_results)
413             for a in s.architectures:
414                 if a == 'source':
415                     continue
416                 pool.apply_async(generate_packages, [s.suite_id, c, a.arch_id, 'deb'], callback=parse_results)
417                 pool.apply_async(generate_packages, [s.suite_id, c, a.arch_id, 'udeb'], callback=parse_results)
418
419     pool.close()
420     pool.join()
421
422     # this script doesn't change the database
423     session.close()
424
425     logger.close()
426
427     sys.exit(pool.overall_status())
428
429 if __name__ == '__main__':
430     main()