]> git.decadent.org.uk Git - dak.git/blob - dak/examine_package.py
examine-package: add missing newlines to output
[dak.git] / dak / examine_package.py
1 #!/usr/bin/env python
2
3 """
4 Script to automate some parts of checking NEW packages
5
6 @contact: Debian FTP Master <ftpmaster@debian.org>
7 @copyright: 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.org>
8 @copyright: 2009  Joerg Jaspert <joerg@debian.org>
9 @license: GNU General Public License version 2 or later
10 """
11
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
16
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25
26 ################################################################################
27
28 # <Omnic> elmo wrote docs?!!?!?!?!?!?!
29 # <aj> as if he wasn't scary enough before!!
30 # * aj imagines a little red furry toy sitting hunched over a computer
31 #   tapping furiously and giggling to himself
32 # <aj> eventually he stops, and his heads slowly spins around and you
33 #      see this really evil grin and then he sees you, and picks up a
34 #      knife from beside the keyboard and throws it at you, and as you
35 #      breathe your last breath, he starts giggling again
36 # <aj> but i should be telling this to my psychiatrist, not you guys,
37 #      right? :)
38
39 ################################################################################
40
41 import errno
42 import os
43 import re
44 import sys
45 import md5
46 import apt_pkg
47 import apt_inst
48 import shutil
49 import commands
50
51 from daklib import utils
52 from daklib.dbconn import DBConn, get_binary_from_name_suite
53 from daklib.regexes import html_escaping, re_html_escaping, re_version, re_spacestrip, \
54                            re_contrib, re_nonfree, re_localhost, re_newlinespace, \
55                            re_package, re_doc_directory
56
57 ################################################################################
58
59 Cnf = None
60 Cnf = utils.get_conf()
61
62 printed_copyrights = {}
63 package_relations = {}           #: Store relations of packages for later output
64
65 # default is to not output html.
66 use_html = 0
67
68 ################################################################################
69
70 def usage (exit_code=0):
71     print """Usage: dak examine-package [PACKAGE]...
72 Check NEW package(s).
73
74   -h, --help                 show this help and exit
75   -H, --html-output          output html page with inspection result
76   -f, --file-name            filename for the html page
77
78 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
79
80     sys.exit(exit_code)
81
82 ################################################################################
83 # probably xml.sax.saxutils would work as well
84
85 def escape_if_needed(s):
86     if use_html:
87         return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
88     else:
89         return s
90
91 def headline(s, level=2, bodyelement=None):
92     if use_html:
93         if bodyelement:
94             return """<thead>
95                 <tr><th colspan="2" class="title" onclick="toggle('%(bodyelement)s', 'table-row-group', 'table-row-group')">%(title)s <span class="toggle-msg">(click to toggle)</span></th></tr>
96               </thead>\n"""%{"bodyelement":bodyelement,"title":utils.html_escape(s)}
97         else:
98             return "<h%d>%s</h%d>\n" % (level, utils.html_escape(s), level)
99     else:
100         return "---- %s ----\n" % (s)
101
102 # Colour definitions, 'end' isn't really for use
103
104 ansi_colours = {
105   'main': "\033[36m",
106   'contrib': "\033[33m",
107   'nonfree': "\033[31m",
108   'arch': "\033[32m",
109   'end': "\033[0m",
110   'bold': "\033[1m",
111   'maintainer': "\033[32m"}
112
113 html_colours = {
114   'main': ('<span style="color: aqua">',"</span>"),
115   'contrib': ('<span style="color: yellow">',"</span>"),
116   'nonfree': ('<span style="color: red">',"</span>"),
117   'arch': ('<span style="color: green">',"</span>"),
118   'bold': ('<span style="font-weight: bold">',"</span>"),
119   'maintainer': ('<span style="color: green">',"</span>")}
120
121 def colour_output(s, colour):
122     if use_html:
123         return ("%s%s%s" % (html_colours[colour][0], utils.html_escape(s), html_colours[colour][1]))
124     else:
125         return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
126
127 def escaped_text(s, strip=False):
128     if use_html:
129         if strip:
130             s = s.strip()
131         return "<pre>%s</pre>" % (s)
132     else:
133         return s
134
135 def formatted_text(s, strip=False):
136     if use_html:
137         if strip:
138             s = s.strip()
139         return "<pre>%s</pre>" % (utils.html_escape(s))
140     else:
141         return s
142
143 def output_row(s):
144     if use_html:
145         return """<tr><td>"""+s+"""</td></tr>"""
146     else:
147         return s
148
149 def format_field(k,v):
150     if use_html:
151         return """<tr><td class="key">%s:</td><td class="val">%s</td></tr>"""%(k,v)
152     else:
153         return "%s: %s"%(k,v)
154
155 def foldable_output(title, elementnameprefix, content, norow=False):
156     d = {'elementnameprefix':elementnameprefix}
157     result = ''
158     if use_html:
159         result += """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
160                    <table class="infobox rfc822">\n"""%d
161     result += headline(title, bodyelement="%(elementnameprefix)s-body"%d)
162     if use_html:
163         result += """    <tbody id="%(elementnameprefix)s-body" class="infobody">\n"""%d
164     if norow:
165         result += content + "\n"
166     else:
167         result += output_row(content) + "\n"
168     if use_html:
169         result += """</tbody></table></div>"""
170     return result
171
172 ################################################################################
173
174 def get_depends_parts(depend) :
175     v_match = re_version.match(depend)
176     if v_match:
177         d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
178     else :
179         d_parts = { 'name' : depend , 'version' : '' }
180     return d_parts
181
182 def get_or_list(depend) :
183     or_list = depend.split("|")
184     return or_list
185
186 def get_comma_list(depend) :
187     dep_list = depend.split(",")
188     return dep_list
189
190 def split_depends (d_str) :
191     # creates a list of lists of dictionaries of depends (package,version relation)
192
193     d_str = re_spacestrip.sub('',d_str)
194     depends_tree = []
195     # first split depends string up amongs comma delimiter
196     dep_list = get_comma_list(d_str)
197     d = 0
198     while d < len(dep_list):
199         # put depends into their own list
200         depends_tree.append([dep_list[d]])
201         d += 1
202     d = 0
203     while d < len(depends_tree):
204         k = 0
205         # split up Or'd depends into a multi-item list
206         depends_tree[d] = get_or_list(depends_tree[d][0])
207         while k < len(depends_tree[d]):
208             # split depends into {package, version relation}
209             depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
210             k += 1
211         d += 1
212     return depends_tree
213
214 def read_control (filename):
215     recommends = []
216     depends = []
217     section = ''
218     maintainer = ''
219     arch = ''
220
221     deb_file = utils.open_file(filename)
222     try:
223         extracts = apt_inst.debExtractControl(deb_file)
224         control = apt_pkg.ParseSection(extracts)
225     except:
226         print formatted_text("can't parse control info")
227         deb_file.close()
228         raise
229
230     deb_file.close()
231
232     control_keys = control.keys()
233
234     if control.has_key("Depends"):
235         depends_str = control.Find("Depends")
236         # create list of dependancy lists
237         depends = split_depends(depends_str)
238
239     if control.has_key("Recommends"):
240         recommends_str = control.Find("Recommends")
241         recommends = split_depends(recommends_str)
242
243     if control.has_key("Section"):
244         section_str = control.Find("Section")
245
246         c_match = re_contrib.search(section_str)
247         nf_match = re_nonfree.search(section_str)
248         if c_match :
249             # contrib colour
250             section = colour_output(section_str, 'contrib')
251         elif nf_match :
252             # non-free colour
253             section = colour_output(section_str, 'nonfree')
254         else :
255             # main
256             section = colour_output(section_str, 'main')
257     if control.has_key("Architecture"):
258         arch_str = control.Find("Architecture")
259         arch = colour_output(arch_str, 'arch')
260
261     if control.has_key("Maintainer"):
262         maintainer = control.Find("Maintainer")
263         localhost = re_localhost.search(maintainer)
264         if localhost:
265             #highlight bad email
266             maintainer = colour_output(maintainer, 'maintainer')
267         else:
268             maintainer = escape_if_needed(maintainer)
269
270     return (control, control_keys, section, depends, recommends, arch, maintainer)
271
272 def read_changes_or_dsc (suite, filename):
273     dsc = {}
274
275     dsc_file = utils.open_file(filename)
276     try:
277         dsc = utils.parse_changes(filename, dsc_file=1)
278     except:
279         return formatted_text("can't parse .dsc control info")
280     dsc_file.close()
281
282     filecontents = strip_pgp_signature(filename)
283     keysinorder = []
284     for l in filecontents.split('\n'):
285         m = re.match(r'([-a-zA-Z0-9]*):', l)
286         if m:
287             keysinorder.append(m.group(1))
288
289     for k in dsc.keys():
290         if k in ("build-depends","build-depends-indep"):
291             dsc[k] = create_depends_string(suite, split_depends(dsc[k]))
292         elif k == "architecture":
293             if (dsc["architecture"] != "any"):
294                 dsc['architecture'] = colour_output(dsc["architecture"], 'arch')
295         elif k in ("files","changes","description"):
296             if use_html:
297                 dsc[k] = formatted_text(dsc[k], strip=True)
298             else:
299                 dsc[k] = ('\n'+'\n'.join(map(lambda x: ' '+x, dsc[k].split('\n')))).rstrip()
300         else:
301             dsc[k] = escape_if_needed(dsc[k])
302
303     keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
304
305     filecontents = '\n'.join(map(lambda x: format_field(x,dsc[x.lower()]), keysinorder))+'\n'
306     return filecontents
307
308 def create_depends_string (suite, depends_tree):
309     result = ""
310     if suite == 'experimental':
311         suite_where = "in ('experimental','unstable')"
312     else:
313         suite_where = "= '%s'" % suite
314
315     comma_count = 1
316     session = DBConn().session()
317     for l in depends_tree:
318         if (comma_count >= 2):
319             result += ", "
320         or_count = 1
321         for d in l:
322             if (or_count >= 2 ):
323                 result += " | "
324             # doesn't do version lookup yet.
325
326             res = get_binary_from_name_suite(d['name'], suite_where)
327             if res.rowcount > 0:
328                 i = res.fetchone()
329
330                 adepends = d['name']
331                 if d['version'] != '' :
332                     adepends += " (%s)" % (d['version'])
333
334                 if i[2] == "contrib":
335                     result += colour_output(adepends, "contrib")
336                 elif i[2] == "non-free":
337                     result += colour_output(adepends, "nonfree")
338                 else :
339                     result += colour_output(adepends, "main")
340             else:
341                 adepends = d['name']
342                 if d['version'] != '' :
343                     adepends += " (%s)" % (d['version'])
344                 result += colour_output(adepends, "bold")
345             or_count += 1
346         comma_count += 1
347     return result
348
349 def output_package_relations ():
350     """
351     Output the package relations, if there is more than one package checked in this run.
352     """
353
354     if len(package_relations) < 2:
355         # Only list something if we have more than one binary to compare
356         package_relations.clear()
357         return
358
359     to_print = ""
360     for package in package_relations:
361         for relation in package_relations[package]:
362             to_print += "%-15s: (%s) %s\n" % (package, relation, package_relations[package][relation])
363
364     package_relations.clear()
365     print foldable_output("Package relations", "relations", to_print)
366
367 def output_deb_info(suite, filename, packagename):
368     (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
369
370     if control == '':
371         return formatted_text("no control info")
372     to_print = ""
373     if not package_relations.has_key(packagename):
374         package_relations[packagename] = {}
375     for key in control_keys :
376         if key == 'Depends':
377             field_value = create_depends_string(suite, depends)
378             package_relations[packagename][key] = field_value
379         elif key == 'Recommends':
380             field_value = create_depends_string(suite, recommends)
381             package_relations[packagename][key] = field_value
382         elif key == 'Section':
383             field_value = section
384         elif key == 'Architecture':
385             field_value = arch
386         elif key == 'Maintainer':
387             field_value = maintainer
388         elif key == 'Description':
389             if use_html:
390                 field_value = formatted_text(control.Find(key), strip=True)
391             else:
392                 desc = control.Find(key)
393                 desc = re_newlinespace.sub('\n ', desc)
394                 field_value = escape_if_needed(desc)
395         else:
396             field_value = escape_if_needed(control.Find(key))
397         to_print += " "+format_field(key,field_value)+'\n'
398     return to_print
399
400 def do_command (command, filename, escaped=0):
401     o = os.popen("%s %s" % (command, filename))
402     if escaped:
403         return escaped_text(o.read())
404     else:
405         return formatted_text(o.read())
406
407 def do_lintian (filename):
408     if use_html:
409         return do_command("lintian --show-overrides --color html", filename, 1)
410     else:
411         return do_command("lintian --show-overrides --color always", filename, 1)
412
413 def get_copyright (deb_filename):
414     package = re_package.sub(r'\1', deb_filename)
415     o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
416     cright = o.read()[:-1]
417
418     if cright == "":
419         return formatted_text("WARNING: No copyright found, please check package manually.")
420
421     doc_directory = re_doc_directory.sub(r'\1', cright)
422     if package != doc_directory:
423         return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
424
425     o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, cright))
426     cright = o.read()
427     copyrightmd5 = md5.md5(cright).hexdigest()
428
429     res = ""
430     if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
431         res += formatted_text( "NOTE: Copyright is the same as %s.\n\n" % \
432                                (printed_copyrights[copyrightmd5]))
433     else:
434         printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
435     return res+formatted_text(cright)
436
437 def get_readme_source (dsc_filename):
438     tempdir = utils.temp_dirname()
439     os.rmdir(tempdir)
440
441     cmd = "dpkg-source --no-check --no-copy -x %s %s" % (dsc_filename, tempdir)
442     (result, output) = commands.getstatusoutput(cmd)
443     if (result != 0):
444         res = "How is education supposed to make me feel smarter? Besides, every time I learn something new, it pushes some\n old stuff out of my brain. Remember when I took that home winemaking course, and I forgot how to drive?\n"
445         res += "Error, couldn't extract source, WTF?\n"
446         res += "'dpkg-source -x' failed. return code: %s.\n\n" % (result)
447         res += output
448         return res
449
450     path = os.path.join(tempdir, 'debian/README.source')
451     res = ""
452     if os.path.exists(path):
453         res += do_command("cat", path)
454     else:
455         res += "No README.source in this package\n\n"
456
457     try:
458         shutil.rmtree(tempdir)
459     except OSError, e:
460         if errno.errorcode[e.errno] != 'EACCES':
461             res += "%s: couldn't remove tmp dir %s for source tree." % (dsc_filename, tempdir)
462
463     return res
464
465 def check_dsc (suite, dsc_filename):
466     (dsc) = read_changes_or_dsc(suite, dsc_filename)
467     print foldable_output(dsc_filename, "dsc", dsc, norow=True)
468     print foldable_output("lintian check for %s" % dsc_filename, "source-lintian", do_lintian(dsc_filename))
469     print foldable_output("README.source for %s" % dsc_filename, "source-readmesource", get_readme_source(dsc_filename))
470
471 def check_deb (suite, deb_filename):
472     filename = os.path.basename(deb_filename)
473     packagename = filename.split('_')[0]
474
475     if filename.endswith(".udeb"):
476         is_a_udeb = 1
477     else:
478         is_a_udeb = 0
479
480
481     print foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
482                     output_deb_info(suite, deb_filename, packagename), norow=True)
483
484     if is_a_udeb:
485         print foldable_output("skipping lintian check for udeb", "binary-%s-lintian"%packagename,
486                         "")
487     else:
488         print foldable_output("lintian check for %s" % (filename), "binary-%s-lintian"%packagename,
489                         do_lintian(deb_filename))
490
491     print foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
492                     do_command("dpkg -c", deb_filename))
493
494     if is_a_udeb:
495         print foldable_output("skipping copyright for udeb", "binary-%s-copyright"%packagename,
496                         "")
497     else:
498         print foldable_output("copyright of %s" % (filename), "binary-%s-copyright"%packagename,
499                         get_copyright(deb_filename))
500
501     print foldable_output("file listing of %s" % (filename),  "binary-%s-file-listing"%packagename,
502                     do_command("ls -l", deb_filename))
503
504 # Read a file, strip the signature and return the modified contents as
505 # a string.
506 def strip_pgp_signature (filename):
507     inputfile = utils.open_file (filename)
508     contents = ""
509     inside_signature = 0
510     skip_next = 0
511     for line in inputfile.readlines():
512         if line[:-1] == "":
513             continue
514         if inside_signature:
515             continue
516         if skip_next:
517             skip_next = 0
518             continue
519         if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
520             skip_next = 1
521             continue
522         if line.startswith("-----BEGIN PGP SIGNATURE"):
523             inside_signature = 1
524             continue
525         if line.startswith("-----END PGP SIGNATURE"):
526             inside_signature = 0
527             continue
528         contents += line
529     inputfile.close()
530     return contents
531
532 def display_changes(suite, changes_filename):
533     changes = read_changes_or_dsc(suite, changes_filename)
534     print foldable_output(changes_filename, "changes", changes, norow=True)
535
536 def check_changes (changes_filename):
537     try:
538         changes = utils.parse_changes (changes_filename)
539     except ChangesUnicodeError:
540         utils.warn("Encoding problem with changes file %s" % (changes_filename))
541     display_changes(changes['distribution'], changes_filename)
542
543     files = utils.build_file_list(changes)
544     for f in files.keys():
545         if f.endswith(".deb") or f.endswith(".udeb"):
546             check_deb(changes['distribution'], f)
547         if f.endswith(".dsc"):
548             check_dsc(changes['distribution'], f)
549         # else: => byhand
550
551 def main ():
552     global Cnf, db_files, waste, excluded
553
554 #    Cnf = utils.get_conf()
555
556     Arguments = [('h',"help","Examine-Package::Options::Help"),
557                  ('H',"html-output","Examine-Package::Options::Html-Output"),
558                 ]
559     for i in [ "Help", "Html-Output", "partial-html" ]:
560         if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
561             Cnf["Examine-Package::Options::%s" % (i)] = ""
562
563     args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
564     Options = Cnf.SubTree("Examine-Package::Options")
565
566     if Options["Help"]:
567         usage()
568
569     stdout_fd = sys.stdout
570
571     for f in args:
572         try:
573             if not Options["Html-Output"]:
574                 # Pipe output for each argument through less
575                 less_fd = os.popen("less -R -", 'w', 0)
576                 # -R added to display raw control chars for colour
577                 sys.stdout = less_fd
578             try:
579                 if f.endswith(".changes"):
580                     check_changes(f)
581                 elif f.endswith(".deb") or f.endswith(".udeb"):
582                     # default to unstable when we don't have a .changes file
583                     # perhaps this should be a command line option?
584                     check_deb('unstable', f)
585                 elif f.endswith(".dsc"):
586                     check_dsc('unstable', f)
587                 else:
588                     utils.fubar("Unrecognised file type: '%s'." % (f))
589             finally:
590                 output_package_relations()
591                 if not Options["Html-Output"]:
592                     # Reset stdout here so future less invocations aren't FUBAR
593                     less_fd.close()
594                     sys.stdout = stdout_fd
595         except IOError, e:
596             if errno.errorcode[e.errno] == 'EPIPE':
597                 utils.warn("[examine-package] Caught EPIPE; skipping.")
598                 pass
599             else:
600                 raise
601         except KeyboardInterrupt:
602             utils.warn("[examine-package] Caught C-c; skipping.")
603             pass
604
605 #######################################################################################
606
607 if __name__ == '__main__':
608     main()