]> git.decadent.org.uk Git - dak.git/blob - dak/make_changelog.py
Generate a listing of the exported files
[dak.git] / dak / make_changelog.py
1 #!/usr/bin/env python
2
3 """
4 Generate changelog entry between two suites
5
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2010 Luca Falavigna <dktrkranz@debian.org>
8 @license: GNU General Public License version 2 or later
9 """
10
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
15
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 # GNU General Public License for more details.
20
21 # You should have received a copy of the GNU General Public License
22 # along with this program; if not, write to the Free Software
23 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24
25 ################################################################################
26
27 # <bdefreese> !dinstall
28 # <dak> bdefreese: I guess the next dinstall will be in 0hr 1min 35sec
29 # <bdefreese> Wow I have great timing
30 # <DktrKranz> dating with dinstall, part II
31 # <bdefreese> heh
32 # <Ganneff> dating with that monster? do you have good combat armor?
33 # <bdefreese> +5 Plate :)
34 # <Ganneff> not a good one then
35 # <Ganneff> so you wont even manage to bypass the lesser monster in front, unchecked
36 # <DktrKranz> asbesto belt
37 # <Ganneff> helps only a step
38 # <DktrKranz> the Ultimate Weapon: cron_turned_off
39 # <bdefreese> heh
40 # <Ganneff> thats debadmin limited
41 # <Ganneff> no option for you
42 # <DktrKranz> bdefreese: it seems ftp-masters want dinstall to sexual harass us, are you good in running?
43 # <Ganneff> you can run but you can not hide
44 # <bdefreese> No, I'm old and fat :)
45 # <Ganneff> you can roll but you can not hide
46 # <Ganneff> :)
47 # <bdefreese> haha
48 # <DktrKranz> damn dinstall, you racist bastard
49
50 ################################################################################
51
52 import os
53 import sys
54 import apt_pkg
55 from glob import glob
56 from shutil import rmtree
57 from yaml import safe_dump
58 from daklib.dbconn import *
59 from daklib import utils
60 from daklib.config import Config
61 from daklib.contents import UnpackedSource
62 from daklib.regexes import re_no_epoch
63
64 ################################################################################
65
66 filelist = 'filelist.yaml'
67
68 def usage (exit_code=0):
69     print """Generate changelog between two suites
70
71        Usage:
72        make-changelog -s <suite> -b <base_suite> [OPTION]...
73        make-changelog -e -a <archive>
74
75 Options:
76
77   -h, --help                show this help and exit
78   -s, --suite               suite providing packages to compare
79   -b, --base-suite          suite to be taken as reference for comparison
80   -n, --binnmu              display binNMUs uploads instead of source ones
81
82   -e, --export              export interesting files from source packages
83   -a, --archive             archive to fetch data from
84   -p, --progress            display progress status"""
85
86     sys.exit(exit_code)
87
88 def get_source_uploads(suite, base_suite, session):
89     """
90     Returns changelogs for source uploads where version is newer than base.
91     """
92
93     query = """WITH base AS (
94                  SELECT source, max(version) AS version
95                  FROM source_suite
96                  WHERE suite_name = :base_suite
97                  GROUP BY source
98                  UNION (SELECT source, CAST(0 AS debversion) AS version
99                  FROM source_suite
100                  WHERE suite_name = :suite
101                  EXCEPT SELECT source, CAST(0 AS debversion) AS version
102                  FROM source_suite
103                  WHERE suite_name = :base_suite
104                  ORDER BY source)),
105                cur_suite AS (
106                  SELECT source, max(version) AS version
107                  FROM source_suite
108                  WHERE suite_name = :suite
109                  GROUP BY source)
110                SELECT DISTINCT c.source, c.version, c.changelog
111                FROM changelogs c
112                JOIN base b ON b.source = c.source
113                JOIN cur_suite cs ON cs.source = c.source
114                WHERE c.version > b.version
115                AND c.version <= cs.version
116                AND c.architecture LIKE '%source%'
117                ORDER BY c.source, c.version DESC"""
118
119     return session.execute(query, {'suite': suite, 'base_suite': base_suite})
120
121 def get_binary_uploads(suite, base_suite, session):
122     """
123     Returns changelogs for binary uploads where version is newer than base.
124     """
125
126     query = """WITH base as (
127                  SELECT s.source, max(b.version) AS version, a.arch_string
128                  FROM source s
129                  JOIN binaries b ON b.source = s.id
130                  JOIN bin_associations ba ON ba.bin = b.id
131                  JOIN architecture a ON a.id = b.architecture
132                  WHERE ba.suite = (
133                    SELECT id
134                    FROM suite
135                    WHERE suite_name = :base_suite)
136                  GROUP BY s.source, a.arch_string),
137                cur_suite as (
138                  SELECT s.source, max(b.version) AS version, a.arch_string
139                  FROM source s
140                  JOIN binaries b ON b.source = s.id
141                  JOIN bin_associations ba ON ba.bin = b.id
142                  JOIN architecture a ON a.id = b.architecture
143                  WHERE ba.suite = (
144                    SELECT id
145                    FROM suite
146                    WHERE suite_name = :suite)
147                  GROUP BY s.source, a.arch_string)
148                SELECT DISTINCT c.source, c.version, c.architecture, c.changelog
149                FROM changelogs c
150                JOIN base b on b.source = c.source
151                JOIN cur_suite cs ON cs.source = c.source
152                WHERE c.version > b.version
153                AND c.version <= cs.version
154                AND c.architecture = b.arch_string
155                AND c.architecture = cs.arch_string
156                ORDER BY c.source, c.version DESC, c.architecture"""
157
158     return session.execute(query, {'suite': suite, 'base_suite': base_suite})
159
160 def display_changes(uploads, index):
161     prev_upload = None
162     for upload in uploads:
163         if prev_upload and prev_upload != upload[0]:
164             print
165         print upload[index]
166         prev_upload = upload[0]
167
168 def export_files(session, archive, clpool, progress=False):
169     """
170     Export interesting files from source packages.
171     """
172     pool = os.path.join(archive.path, 'pool')
173
174     sources = {}
175     unpack = {}
176     files = ('changelog', 'copyright', 'NEWS.Debian', 'README.Debian')
177     stats = {'unpack': 0, 'created': 0, 'removed': 0, 'errors': 0, 'files': 0}
178     query = """SELECT DISTINCT s.source, su.suite_name AS suite, s.version, c.name || '/' || f.filename AS filename
179                FROM source s
180                JOIN newest_source n ON n.source = s.source AND n.version = s.version
181                JOIN src_associations sa ON sa.source = s.id
182                JOIN suite su ON su.id = sa.suite
183                JOIN files f ON f.id = s.file
184                JOIN files_archive_map fam ON f.id = fam.file_id AND fam.archive_id = su.archive_id
185                JOIN component c ON fam.component_id = c.id
186                WHERE su.archive_id = :archive_id
187                ORDER BY s.source, suite"""
188
189     for p in session.execute(query, {'archive_id': archive.archive_id}):
190         if not sources.has_key(p[0]):
191             sources[p[0]] = {}
192         sources[p[0]][p[1]] = (re_no_epoch.sub('', p[2]), p[3])
193
194     for p in sources.keys():
195         for s in sources[p].keys():
196             path = os.path.join(clpool, '/'.join(sources[p][s][1].split('/')[:-1]))
197             if not os.path.exists(path):
198                 os.makedirs(path)
199             if not os.path.exists(os.path.join(path, \
200                    '%s_%s_changelog' % (p, sources[p][s][0]))):
201                 if not unpack.has_key(os.path.join(pool, sources[p][s][1])):
202                     unpack[os.path.join(pool, sources[p][s][1])] = (path, set())
203                 unpack[os.path.join(pool, sources[p][s][1])][1].add(s)
204             else:
205                 for file in glob('%s/%s_%s*' % (path, p, sources[p][s][0])):
206                     link = '%s%s' % (s, file.split('%s_%s' \
207                                       % (p, sources[p][s][0]))[1])
208                     try:
209                         os.unlink(os.path.join(path, link))
210                     except OSError:
211                         pass
212                     os.link(os.path.join(path, file), os.path.join(path, link))
213
214     for p in unpack.keys():
215         package = os.path.splitext(os.path.basename(p))[0].split('_')
216         try:
217             unpacked = UnpackedSource(p)
218             tempdir = unpacked.get_root_directory()
219             stats['unpack'] += 1
220             if progress:
221                 if stats['unpack'] % 100 == 0:
222                     sys.stderr.write('%d packages unpacked\n' % stats['unpack'])
223                 elif stats['unpack'] % 10 == 0:
224                     sys.stderr.write('.')
225             for file in files:
226                 for f in glob(os.path.join(tempdir, 'debian', '*%s' % file)):
227                     for s in unpack[p][1]:
228                         suite = os.path.join(unpack[p][0], '%s_%s' \
229                                 % (s, os.path.basename(f)))
230                         version = os.path.join(unpack[p][0], '%s_%s_%s' % \
231                                   (package[0], package[1], os.path.basename(f)))
232                         if not os.path.exists(version):
233                             os.link(f, version)
234                             stats['created'] += 1
235                         try:
236                             os.unlink(suite)
237                         except OSError:
238                             pass
239                         os.link(version, suite)
240                         stats['created'] += 1
241             unpacked.cleanup()
242         except Exception as e:
243             print 'make-changelog: unable to unpack %s\n%s' % (p, e)
244             stats['errors'] += 1
245
246     for root, dirs, files in os.walk(clpool):
247         files = [f for f in files if f != filelist]
248         if len(files):
249             if root != clpool:
250                 if root.split('/')[-1] not in sources.keys():
251                     if os.path.exists(root):
252                         stats['removed'] += len(os.listdir(root))
253                         rmtree(root)
254             for file in files:
255                 if os.path.exists(os.path.join(root, file)):
256                     if os.stat(os.path.join(root, file)).st_nlink ==  1:
257                         stats['removed'] += 1
258                         os.unlink(os.path.join(root, file))
259         stats['files'] += len(files)
260     stats['files'] -= stats['removed']
261
262     print 'make-changelog: file exporting finished'
263     print '  * New packages unpacked: %d' % stats['unpack']
264     print '  * New files created: %d' % stats['created']
265     print '  * New files removed: %d' % stats['removed']
266     print '  * Unpack errors: %d' % stats['errors']
267     print '  * Files available into changelog pool: %d' % stats['files']
268
269 def generate_export_filelist(clpool):
270     clfiles = {}
271     for root, dirs, files in os.walk(clpool):
272         for file in [f for f in files if f != filelist]:
273             clpath = os.path.join(root, file).replace(clpool, '').strip('/')
274             source = clpath.split('/')[2]
275             elements = clpath.split('/')[3].split('_')
276             if source not in clfiles:
277                 clfiles[source] = {}
278             if elements[0] == source:
279                 if elements[1] not in clfiles[source]:
280                     clfiles[source][elements[1]] = []
281                 clfiles[source][elements[1]].append(clpath)
282             else:
283                 if elements[0] not in clfiles[source]:
284                     clfiles[source][elements[0]] = []
285                 clfiles[source][elements[0]].append(clpath)
286     with open(os.path.join(clpool, filelist), 'w+') as fd:
287         safe_dump(clfiles, fd, default_flow_style=False)
288
289 def main():
290     Cnf = utils.get_conf()
291     cnf = Config()
292     Arguments = [('h','help','Make-Changelog::Options::Help'),
293                  ('a','archive','Make-Changelog::Options::Archive','HasArg'),
294                  ('s','suite','Make-Changelog::Options::Suite','HasArg'),
295                  ('b','base-suite','Make-Changelog::Options::Base-Suite','HasArg'),
296                  ('n','binnmu','Make-Changelog::Options::binNMU'),
297                  ('e','export','Make-Changelog::Options::export'),
298                  ('p','progress','Make-Changelog::Options::progress')]
299
300     for i in ['help', 'suite', 'base-suite', 'binnmu', 'export', 'progress']:
301         if not Cnf.has_key('Make-Changelog::Options::%s' % (i)):
302             Cnf['Make-Changelog::Options::%s' % (i)] = ''
303
304     apt_pkg.parse_commandline(Cnf, Arguments, sys.argv)
305     Options = Cnf.subtree('Make-Changelog::Options')
306     suite = Cnf['Make-Changelog::Options::Suite']
307     base_suite = Cnf['Make-Changelog::Options::Base-Suite']
308     binnmu = Cnf['Make-Changelog::Options::binNMU']
309     export = Cnf['Make-Changelog::Options::export']
310     progress = Cnf['Make-Changelog::Options::progress']
311
312     if Options['help'] or not (suite and base_suite) and not export:
313         usage()
314
315     for s in suite, base_suite:
316         if not export and not get_suite(s):
317             utils.fubar('Invalid suite "%s"' % s)
318
319     session = DBConn().session()
320
321     if export:
322         if cnf.exportpath:
323             archive = session.query(Archive).filter_by(archive_name=Options['Archive']).one()
324             exportpath = os.path.join(Cnf['Dir::Export'], cnf.exportpath)
325             export_files(session, archive, exportpath, progress)
326             generate_export_filelist(exportpath)
327         else:
328             utils.fubar('No changelog export path defined')
329     elif binnmu:
330         display_changes(get_binary_uploads(suite, base_suite, session), 3)
331     else:
332         display_changes(get_source_uploads(suite, base_suite, session), 2)
333
334     session.commit()
335
336 if __name__ == '__main__':
337     main()