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