]> git.decadent.org.uk Git - dak.git/blob - dak/make_changelog.py
Merge branch 'merge'
[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 daklib.dbconn import *
58 from daklib import utils
59 from daklib.config import Config
60 from daklib.contents import UnpackedSource
61 from daklib.regexes import re_no_epoch
62
63 ################################################################################
64
65 def usage (exit_code=0):
66     print """Generate changelog between two suites
67
68        Usage:
69        make-changelog -s <suite> -b <base_suite> [OPTION]...
70        make-changelog -e -a <archive>
71
72 Options:
73
74   -h, --help                show this help and exit
75   -s, --suite               suite providing packages to compare
76   -b, --base-suite          suite to be taken as reference for comparison
77   -n, --binnmu              display binNMUs uploads instead of source ones
78
79   -e, --export              export interesting files from source packages
80   -a, --archive             archive to fetch data from
81   -p, --progress            display progress status"""
82
83     sys.exit(exit_code)
84
85 def get_source_uploads(suite, base_suite, session):
86     """
87     Returns changelogs for source uploads where version is newer than base.
88     """
89
90     query = """WITH base AS (
91                  SELECT source, max(version) AS version
92                  FROM source_suite
93                  WHERE suite_name = :base_suite
94                  GROUP BY source
95                  UNION (SELECT source, CAST(0 AS debversion) AS version
96                  FROM source_suite
97                  WHERE suite_name = :suite
98                  EXCEPT SELECT source, CAST(0 AS debversion) AS version
99                  FROM source_suite
100                  WHERE suite_name = :base_suite
101                  ORDER BY source)),
102                cur_suite AS (
103                  SELECT source, max(version) AS version
104                  FROM source_suite
105                  WHERE suite_name = :suite
106                  GROUP BY source)
107                SELECT DISTINCT c.source, c.version, c.changelog
108                FROM changelogs c
109                JOIN base b ON b.source = c.source
110                JOIN cur_suite cs ON cs.source = c.source
111                WHERE c.version > b.version
112                AND c.version <= cs.version
113                AND c.architecture LIKE '%source%'
114                ORDER BY c.source, c.version DESC"""
115
116     return session.execute(query, {'suite': suite, 'base_suite': base_suite})
117
118 def get_binary_uploads(suite, base_suite, session):
119     """
120     Returns changelogs for binary uploads where version is newer than base.
121     """
122
123     query = """WITH base as (
124                  SELECT s.source, max(b.version) AS version, a.arch_string
125                  FROM source s
126                  JOIN binaries b ON b.source = s.id
127                  JOIN bin_associations ba ON ba.bin = b.id
128                  JOIN architecture a ON a.id = b.architecture
129                  WHERE ba.suite = (
130                    SELECT id
131                    FROM suite
132                    WHERE suite_name = :base_suite)
133                  GROUP BY s.source, a.arch_string),
134                cur_suite as (
135                  SELECT s.source, max(b.version) AS version, a.arch_string
136                  FROM source s
137                  JOIN binaries b ON b.source = s.id
138                  JOIN bin_associations ba ON ba.bin = b.id
139                  JOIN architecture a ON a.id = b.architecture
140                  WHERE ba.suite = (
141                    SELECT id
142                    FROM suite
143                    WHERE suite_name = :suite)
144                  GROUP BY s.source, a.arch_string)
145                SELECT DISTINCT c.source, c.version, c.architecture, c.changelog
146                FROM changelogs c
147                JOIN base b on b.source = c.source
148                JOIN cur_suite cs ON cs.source = c.source
149                WHERE c.version > b.version
150                AND c.version <= cs.version
151                AND c.architecture = b.arch_string
152                AND c.architecture = cs.arch_string
153                ORDER BY c.source, c.version DESC, c.architecture"""
154
155     return session.execute(query, {'suite': suite, 'base_suite': base_suite})
156
157 def display_changes(uploads, index):
158     prev_upload = None
159     for upload in uploads:
160         if prev_upload and prev_upload != upload[0]:
161             print
162         print upload[index]
163         prev_upload = upload[0]
164
165 def export_files(session, archive, clpool, progress=False):
166     """
167     Export interesting files from source packages.
168     """
169     pool = os.path.join(archive.path, 'pool')
170
171     sources = {}
172     unpack = {}
173     files = ('changelog', 'copyright', 'NEWS.Debian', 'README.Debian')
174     stats = {'unpack': 0, 'created': 0, 'removed': 0, 'errors': 0, 'files': 0}
175     query = """SELECT DISTINCT s.source, su.suite_name AS suite, s.version, c.name || '/' || f.filename AS filename
176                FROM source s
177                JOIN newest_source n ON n.source = s.source AND n.version = s.version
178                JOIN src_associations sa ON sa.source = s.id
179                JOIN suite su ON su.id = sa.suite
180                JOIN files f ON f.id = s.file
181                JOIN files_archive_map fam ON f.id = fam.file_id AND fam.archive_id = su.archive_id
182                JOIN component c ON fam.component_id = c.id
183                WHERE su.archive_id = :archive_id
184                ORDER BY s.source, suite"""
185
186     for p in session.execute(query, {'archive_id': archive.archive_id}):
187         if not sources.has_key(p[0]):
188             sources[p[0]] = {}
189         sources[p[0]][p[1]] = (re_no_epoch.sub('', p[2]), p[3])
190
191     for p in sources.keys():
192         for s in sources[p].keys():
193             path = os.path.join(clpool, '/'.join(sources[p][s][1].split('/')[:-1]))
194             if not os.path.exists(path):
195                 os.makedirs(path)
196             if not os.path.exists(os.path.join(path, \
197                    '%s_%s.changelog' % (p, sources[p][s][0]))):
198                 if not unpack.has_key(os.path.join(pool, sources[p][s][1])):
199                     unpack[os.path.join(pool, sources[p][s][1])] = (path, set())
200                 unpack[os.path.join(pool, sources[p][s][1])][1].add(s)
201             else:
202                 for file in glob('%s/%s_%s*' % (path, p, sources[p][s][0])):
203                     link = '%s%s' % (s, file.split('%s_%s' \
204                                       % (p, sources[p][s][0]))[1])
205                     try:
206                         os.unlink(os.path.join(path, link))
207                     except OSError:
208                         pass
209                     os.link(os.path.join(path, file), os.path.join(path, link))
210
211     for p in unpack.keys():
212         package = os.path.splitext(os.path.basename(p))[0].split('_')
213         try:
214             unpacked = UnpackedSource(p)
215             tempdir = unpacked.get_root_directory()
216             stats['unpack'] += 1
217             if progress:
218                 if stats['unpack'] % 100 == 0:
219                     sys.stderr.write('%d packages unpacked\n' % stats['unpack'])
220                 elif stats['unpack'] % 10 == 0:
221                     sys.stderr.write('.')
222             for file in files:
223                 for f in glob(os.path.join(tempdir, 'debian', '*%s' % file)):
224                     for s in unpack[p][1]:
225                         suite = os.path.join(unpack[p][0], '%s.%s' \
226                                 % (s, os.path.basename(f)))
227                         version = os.path.join(unpack[p][0], '%s_%s.%s' % \
228                                   (package[0], package[1], os.path.basename(f)))
229                         if not os.path.exists(version):
230                             os.link(f, version)
231                             stats['created'] += 1
232                         try:
233                             os.unlink(suite)
234                         except OSError:
235                             pass
236                         os.link(version, suite)
237                         stats['created'] += 1
238             unpacked.cleanup()
239         except Exception as e:
240             print 'make-changelog: unable to unpack %s\n%s' % (p, e)
241             stats['errors'] += 1
242
243     for root, dirs, files in os.walk(clpool):
244         if len(files):
245             if root.split('/')[-1] not in sources.keys():
246                 if os.path.exists(root):
247                     rmtree(root)
248                     stats['removed'] += 1
249             for file in files:
250                 if os.path.exists(os.path.join(root, file)):
251                     if os.stat(os.path.join(root, file)).st_nlink ==  1:
252                         os.unlink(os.path.join(root, file))
253                         stats['removed'] += 1
254
255     for root, dirs, files in os.walk(clpool):
256         stats['files'] += len(files)
257     print 'make-changelog: file exporting finished'
258     print '  * New packages unpacked: %d' % stats['unpack']
259     print '  * New files created: %d' % stats['created']
260     print '  * New files removed: %d' % stats['removed']
261     print '  * Unpack errors: %d' % stats['errors']
262     print '  * Files available into changelog pool: %d' % stats['files']
263
264 def main():
265     Cnf = utils.get_conf()
266     cnf = Config()
267     Arguments = [('h','help','Make-Changelog::Options::Help'),
268                  ('a','archive','Make-Changelog::Options::Archive','HasArg'),
269                  ('s','suite','Make-Changelog::Options::Suite','HasArg'),
270                  ('b','base-suite','Make-Changelog::Options::Base-Suite','HasArg'),
271                  ('n','binnmu','Make-Changelog::Options::binNMU'),
272                  ('e','export','Make-Changelog::Options::export'),
273                  ('p','progress','Make-Changelog::Options::progress')]
274
275     for i in ['help', 'suite', 'base-suite', 'binnmu', 'export', 'progress']:
276         if not Cnf.has_key('Make-Changelog::Options::%s' % (i)):
277             Cnf['Make-Changelog::Options::%s' % (i)] = ''
278
279     apt_pkg.parse_commandline(Cnf, Arguments, sys.argv)
280     Options = Cnf.subtree('Make-Changelog::Options')
281     suite = Cnf['Make-Changelog::Options::Suite']
282     base_suite = Cnf['Make-Changelog::Options::Base-Suite']
283     binnmu = Cnf['Make-Changelog::Options::binNMU']
284     export = Cnf['Make-Changelog::Options::export']
285     progress = Cnf['Make-Changelog::Options::progress']
286
287     if Options['help'] or not (suite and base_suite) and not export:
288         usage()
289
290     for s in suite, base_suite:
291         if not export and not get_suite(s):
292             utils.fubar('Invalid suite "%s"' % s)
293
294     session = DBConn().session()
295
296     if export:
297         if cnf.exportpath:
298             archive = session.query(Archive).filter_by(archive_name=Options['Archive']).one()
299             exportpath = os.path.join(Cnf['Dir::Export'], cnf.exportpath)
300             export_files(session, archive, exportpath, progress)
301         else:
302             utils.fubar('No changelog export path defined')
303     elif binnmu:
304         display_changes(get_binary_uploads(suite, base_suite, session), 3)
305     else:
306         display_changes(get_source_uploads(suite, base_suite, session), 2)
307
308     session.commit()
309
310 if __name__ == '__main__':
311     main()