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