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