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