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