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