]> git.decadent.org.uk Git - dak.git/blob - dak/generate_packages_sources2.py
Pass compression methods to FileWriter.
[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   -s, --suite=SUITE            process this suite
38                                Default: All suites not marked 'untouchable'
39   -f, --force                  Allow processing of untouchable suites
40                                CAREFUL: Only to be used at point release time!
41   -h, --help                   show this help and exit
42
43 SUITE can be a space seperated list, e.g.
44    --suite=unstable testing
45 """
46     sys.exit()
47
48 #############################################################################
49
50 # Here be dragons.
51 _sources_query = R"""
52 SELECT
53
54   (SELECT
55      STRING_AGG(
56        CASE
57          WHEN key = 'Source' THEN E'Package\: '
58          WHEN key = 'Files' THEN E'Files\:\n ' || f.md5sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
59          WHEN key = 'Checksums-Sha1' THEN E'Checksums-Sha1\:\n ' || f.sha1sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
60          WHEN key = 'Checksums-Sha256' THEN E'Checksums-Sha256\:\n ' || f.sha256sum || ' ' || f.size || ' ' || SUBSTRING(f.filename FROM E'/([^/]*)\\Z')
61          ELSE key || E'\: '
62        END || value, E'\n' ORDER BY mk.ordering, mk.key)
63    FROM
64      source_metadata sm
65      JOIN metadata_keys mk ON mk.key_id = sm.key_id
66    WHERE s.id=sm.src_id
67   )
68   ||
69   E'\nDirectory\: pool/' || SUBSTRING(f.filename FROM E'\\A(.*)/[^/]*\\Z')
70   ||
71   E'\nPriority\: ' || pri.priority
72   ||
73   E'\nSection\: ' || sec.section
74
75 FROM
76
77 source s
78 JOIN src_associations sa ON s.id = sa.source
79 JOIN files f ON s.file=f.id
80 JOIN override o ON o.package = s.source
81 JOIN section sec ON o.section = sec.id
82 JOIN priority pri ON o.priority = pri.id
83
84 WHERE
85   sa.suite = :suite
86   AND o.suite = :overridesuite AND o.component = :component AND o.type = :dsc_type
87
88 ORDER BY
89 s.source, s.version
90 """
91
92 def generate_sources(suite_id, component_id):
93     global _sources_query
94     from daklib.filewriter import SourcesFileWriter
95     from daklib.dbconn import Component, DBConn, OverrideType, Suite
96     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
97
98     session = DBConn().session()
99     dsc_type = session.query(OverrideType).filter_by(overridetype='dsc').one().overridetype_id
100
101     suite = session.query(Suite).get(suite_id)
102     component = session.query(Component).get(component_id)
103
104     overridesuite_id = suite.get_overridesuite().suite_id
105
106     writer_args = {
107             'suite': suite.suite_name,
108             'component': component.component_name
109     }
110     if suite.indices_compression is not None:
111         writer_args['compression'] = suite.indices_compression
112     writer = SourcesFileWriter(**writer_args)
113     output = writer.open()
114
115     # run query and write Sources
116     r = session.execute(_sources_query, {"suite": suite_id, "component": component_id, "dsc_type": dsc_type, "overridesuite": overridesuite_id})
117     for (stanza,) in r:
118         print >>output, stanza
119         print >>output, ""
120
121     writer.close()
122
123     message = ["generate sources", suite.suite_name, component.component_name]
124     session.rollback()
125     return (PROC_STATUS_SUCCESS, message)
126
127 #############################################################################
128
129 # Here be large dragons.
130 _packages_query = R"""
131 WITH
132
133   tmp AS (
134     SELECT
135       b.id AS binary_id,
136       b.package AS package,
137       b.version AS version,
138       b.architecture AS architecture,
139       b.source AS source_id,
140       s.source AS source,
141       f.filename AS filename,
142       f.size AS size,
143       f.md5sum AS md5sum,
144       f.sha1sum AS sha1sum,
145       f.sha256sum AS sha256sum
146     FROM
147       binaries b
148       JOIN bin_associations ba ON b.id = ba.bin
149       JOIN files f ON f.id = b.file
150       JOIN location l ON l.id = f.location
151       JOIN source s ON b.source = s.id
152     WHERE
153       (b.architecture = :arch_all OR b.architecture = :arch) AND b.type = :type_name
154       AND ba.suite = :suite
155       AND l.component = :component
156   )
157
158 SELECT
159   (SELECT
160      STRING_AGG(key || E'\: ' || value, E'\n' ORDER BY ordering, key)
161    FROM
162      (SELECT key, ordering,
163         CASE WHEN :include_long_description = 'false' AND key = 'Description'
164           THEN SUBSTRING(value FROM E'\\A[^\n]*')
165           ELSE value
166         END AS value
167       FROM
168         binaries_metadata bm
169         JOIN metadata_keys mk ON mk.key_id = bm.key_id
170       WHERE
171         bm.bin_id = tmp.binary_id
172         AND key != ALL (:metadata_skip)
173      ) AS metadata
174   )
175   || COALESCE(E'\n' || (SELECT
176      STRING_AGG(key || E'\: ' || value, E'\n' ORDER BY key)
177    FROM external_overrides eo
178    WHERE
179      eo.package = tmp.package
180      AND eo.suite = :overridesuite AND eo.component = :component
181   ), '')
182   || E'\nSection\: ' || sec.section
183   || E'\nPriority\: ' || pri.priority
184   || E'\nFilename\: pool/' || tmp.filename
185   || E'\nSize\: ' || tmp.size
186   || E'\nMD5sum\: ' || tmp.md5sum
187   || E'\nSHA1\: ' || tmp.sha1sum
188   || E'\nSHA256\: ' || tmp.sha256sum
189
190 FROM
191   tmp
192   JOIN override o ON o.package = tmp.package
193   JOIN section sec ON sec.id = o.section
194   JOIN priority pri ON pri.id = o.priority
195
196 WHERE
197   (
198       architecture <> :arch_all
199     OR
200       (architecture = :arch_all AND source_id IN (SELECT source_id FROM tmp WHERE architecture <> :arch_all))
201     OR
202       (architecture = :arch_all AND source NOT IN (SELECT DISTINCT source FROM tmp WHERE architecture <> :arch_all))
203   )
204   AND
205     o.type = :type_id AND o.suite = :overridesuite AND o.component = :component
206
207 ORDER BY tmp.source, tmp.package, tmp.version
208 """
209
210 def generate_packages(suite_id, component_id, architecture_id, type_name):
211     global _packages_query
212     from daklib.filewriter import PackagesFileWriter
213     from daklib.dbconn import Architecture, Component, DBConn, OverrideType, Suite
214     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
215
216     session = DBConn().session()
217     arch_all_id = session.query(Architecture).filter_by(arch_string='all').one().arch_id
218     type_id = session.query(OverrideType).filter_by(overridetype=type_name).one().overridetype_id
219
220     suite = session.query(Suite).get(suite_id)
221     component = session.query(Component).get(component_id)
222     architecture = session.query(Architecture).get(architecture_id)
223
224     overridesuite_id = suite.get_overridesuite().suite_id
225     include_long_description = suite.include_long_description
226
227     # We currently filter out the "Tag" line. They are set by external
228     # overrides and NOT by the maintainer. And actually having it set by
229     # maintainer means we output it twice at the moment -> which breaks
230     # dselect.
231     metadata_skip = ["Section", "Priority", "Tag"]
232     if include_long_description:
233         metadata_skip.append("Description-md5")
234
235     writer_args = {
236             'suite': suite.suite_name,
237             'component': component.component_name,
238             'architecture': architecture.arch_string,
239             'debtype': type_name
240     }
241     if suite.indices_compression is not None:
242         writer_args['compression'] = suite.indices_compression
243     writer = PackagesFileWriter(**writer_args)
244     output = writer.open()
245
246     r = session.execute(_packages_query, {"suite": suite_id, "component": component_id,
247         "arch": architecture_id, "type_id": type_id, "type_name": type_name, "arch_all": arch_all_id,
248         "overridesuite": overridesuite_id, "metadata_skip": metadata_skip,
249         "include_long_description": 'true' if include_long_description else 'false'})
250     for (stanza,) in r:
251         print >>output, stanza
252         print >>output, ""
253
254     writer.close()
255
256     message = ["generate-packages", suite.suite_name, component.component_name, architecture.arch_string]
257     session.rollback()
258     return (PROC_STATUS_SUCCESS, message)
259
260 #############################################################################
261
262 _translations_query = """
263 WITH
264   override_suite AS
265     (SELECT
266       s.id AS id,
267       COALESCE(os.id, s.id) AS overridesuite_id
268       FROM suite AS s LEFT JOIN suite AS os ON s.overridesuite = os.suite_name)
269
270 SELECT
271      E'Package\: ' || b.package
272   || E'\nDescription-md5\: ' || bm_description_md5.value
273   || E'\nDescription-en\: ' || bm_description.value
274   || E'\n'
275 FROM binaries b
276   -- join tables for suite and component
277   JOIN bin_associations ba ON b.id = ba.bin
278   JOIN override_suite os ON os.id = ba.suite
279   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')
280
281   -- join tables for Description and Description-md5
282   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')
283   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')
284
285   -- we want to sort by source name
286   JOIN source s ON b.source = s.id
287
288 WHERE ba.suite = :suite AND o.component = :component
289 GROUP BY b.package, bm_description_md5.value, bm_description.value
290 ORDER BY MIN(s.source), b.package, bm_description_md5.value
291 """
292
293 def generate_translations(suite_id, component_id):
294     global _translations_query
295     from daklib.filewriter import TranslationFileWriter
296     from daklib.dbconn import DBConn, Suite, Component
297     from daklib.dakmultiprocessing import PROC_STATUS_SUCCESS
298
299     session = DBConn().session()
300     suite = session.query(Suite).get(suite_id)
301     component = session.query(Component).get(component_id)
302
303     writer_args = {
304             'suite': suite.suite_name,
305             'component': component.component_name,
306             'language': 'en',
307     }
308     if suite.i18n_compression is not None:
309         writer_args['compression'] = suite.i18n_compression
310     writer = TranslationFileWriter(**writer_args)
311     output = writer.open()
312
313     r = session.execute(_translations_query, {"suite": suite_id, "component": component_id})
314     for (stanza,) in r:
315         print >>output, stanza
316
317     writer.close()
318
319     message = ["generate-translations", suite.suite_name, component.component_name]
320     session.rollback()
321     return (PROC_STATUS_SUCCESS, message)
322
323 #############################################################################
324
325 def main():
326     from daklib.config import Config
327     from daklib import daklog
328
329     cnf = Config()
330
331     Arguments = [('h',"help","Generate-Packages-Sources::Options::Help"),
332                  ('s',"suite","Generate-Packages-Sources::Options::Suite"),
333                  ('f',"force","Generate-Packages-Sources::Options::Force"),
334                  ('o','option','','ArbItem')]
335
336     suite_names = apt_pkg.parse_commandline(cnf.Cnf, Arguments, sys.argv)
337     try:
338         Options = cnf.subtree("Generate-Packages-Sources::Options")
339     except KeyError:
340         Options = {}
341
342     if Options.has_key("Help"):
343         usage()
344
345     from daklib.dakmultiprocessing import DakProcessPool, PROC_STATUS_SUCCESS, PROC_STATUS_SIGNALRAISED
346     pool = DakProcessPool()
347
348     logger = daklog.Logger('generate-packages-sources2')
349
350     from daklib.dbconn import Component, DBConn, get_suite, Suite
351     session = DBConn().session()
352     session.execute("SELECT add_missing_description_md5()")
353     session.commit()
354
355     if Options.has_key("Suite"):
356         suites = []
357         for s in suite_names:
358             suite = get_suite(s.lower(), session)
359             if suite:
360                 suites.append(suite)
361             else:
362                 print "I: Cannot find suite %s" % s
363                 logger.log(['Cannot find suite %s' % s])
364     else:
365         suites = session.query(Suite).filter(Suite.untouchable == False).all()
366
367     force = Options.has_key("Force") and Options["Force"]
368
369     component_ids = [ c.component_id for c in session.query(Component).all() ]
370
371     def parse_results(message):
372         # Split out into (code, msg)
373         code, msg = message
374         if code == PROC_STATUS_SUCCESS:
375             logger.log([msg])
376         elif code == PROC_STATUS_SIGNALRAISED:
377             logger.log(['E: Subprocess recieved signal ', msg])
378         else:
379             logger.log(['E: ', msg])
380
381     for s in suites:
382         if s.untouchable and not force:
383             import utils
384             utils.fubar("Refusing to touch %s (untouchable and not forced)" % s.suite_name)
385         for c in component_ids:
386             pool.apply_async(generate_sources, [s.suite_id, c], callback=parse_results)
387             if not s.include_long_description:
388                 pool.apply_async(generate_translations, [s.suite_id, c], callback=parse_results)
389             for a in s.architectures:
390                 if a == 'source':
391                     continue
392                 pool.apply_async(generate_packages, [s.suite_id, c, a.arch_id, 'deb'], callback=parse_results)
393                 pool.apply_async(generate_packages, [s.suite_id, c, a.arch_id, 'udeb'], callback=parse_results)
394
395     pool.close()
396     pool.join()
397
398     # this script doesn't change the database
399     session.close()
400
401     logger.close()
402
403     sys.exit(pool.overall_status())
404
405 if __name__ == '__main__':
406     main()