]> git.decadent.org.uk Git - dak.git/blob - dak/examine_package.py
started nicer NEW .html pages
[dak.git] / dak / examine_package.py
1 #!/usr/bin/env python
2
3 # Script to automate some parts of checking NEW packages
4 # Copyright (C) 2000, 2001, 2002, 2003, 2006  James Troup <james@nocrew.org>
5
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19
20 ################################################################################
21
22 # <Omnic> elmo wrote docs?!!?!?!?!?!?!
23 # <aj> as if he wasn't scary enough before!!
24 # * aj imagines a little red furry toy sitting hunched over a computer
25 #   tapping furiously and giggling to himself
26 # <aj> eventually he stops, and his heads slowly spins around and you
27 #      see this really evil grin and then he sees you, and picks up a
28 #      knife from beside the keyboard and throws it at you, and as you
29 #      breathe your last breath, he starts giggling again
30 # <aj> but i should be telling this to my psychiatrist, not you guys,
31 #      right? :)
32
33 ################################################################################
34
35 import errno, os, pg, re, sys, md5
36 import apt_pkg, apt_inst
37 import daklib.database, daklib.utils, daklib.queue
38
39 ################################################################################
40
41 re_package = re.compile(r"^(.+?)_.*")
42 re_doc_directory = re.compile(r".*/doc/([^/]*).*")
43
44 re_contrib = re.compile('^contrib/')
45 re_nonfree = re.compile('^non\-free/')
46
47 re_arch = re.compile("Architecture: .*")
48 re_builddep = re.compile("Build-Depends: .*")
49 re_builddepind = re.compile("Build-Depends-Indep: .*")
50
51 re_localhost = re.compile("localhost\.localdomain")
52 re_version = re.compile('^(.*)\((.*)\)')
53
54 re_newlinespace = re.compile('\n')
55 re_spacestrip = re.compile('(\s)')
56
57 html_escaping = {'"':'&quot;', '&':'&amp;', '<':'&lt;', '>':'&gt;'}
58 re_html_escaping = re.compile('|'.join(map(re.escape, html_escaping.keys())))
59
60 ################################################################################
61
62 Cnf = None
63 projectB = None
64
65 Cnf = daklib.utils.get_conf()
66 projectB = pg.connect(Cnf["DB::Name"], Cnf["DB::Host"], int(Cnf["DB::Port"]))
67 daklib.database.init(Cnf, projectB)
68
69 printed_copyrights = {}
70
71 # default is to not output html.
72 use_html = 0
73
74 ################################################################################
75
76 def usage (exit_code=0):
77     print """Usage: dak examine-package [PACKAGE]...
78 Check NEW package(s).
79
80   -h, --help                 show this help and exit
81   -H, --html-output          output html page with inspection result
82   -f, --file-name            filename for the html page
83
84 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
85
86     sys.exit(exit_code)
87
88 ################################################################################
89 # probably xml.sax.saxutils would work as well
90
91 def html_escape(s):
92   return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
93
94 def escape_if_needed(s):
95   if use_html:
96     return re_html_escaping.sub(html_escaping.get, s)
97   else:
98     return s
99   
100 def headline(s, level=2, bodyelement=None):
101   if use_html:
102     if bodyelement:
103       print """<thead>
104           <tr><th colspan="2" class="title" onclick="toggle('%(bodyelement)s', 'table-row-group', 'table-row-group')">%(title)s</th></tr>
105         </thead>"""%{"bodyelement":bodyelement,"title":html_escape(s)}
106     else:
107       print "<h%d>%s</h%d>" % (level, html_escape(s), level)
108   else:
109     print "---- %s ----" % (s)
110
111 # Colour definitions, 'end' isn't really for use
112
113 ansi_colours = {
114   'main': "\033[36m",
115   'contrib': "\033[33m",
116   'nonfree': "\033[31m",
117   'arch': "\033[32m",
118   'end': "\033[0m",
119   'bold': "\033[1m",
120   'maintainer': "\033[32m"}
121
122 html_colours = {
123   'main': ('<span style="color: aqua">',"</span>"),
124   'contrib': ('<span style="color: yellow">',"</span>"),
125   'nonfree': ('<span style="color: red">',"</span>"),
126   'arch': ('<span style="color: green">',"</span>"),
127   'bold': ('<span style="font-weight: bold">',"</span>"),
128   'maintainer': ('<span style="color: green">',"</span>")}
129
130 def colour_output(s, colour):
131   if use_html:
132     return ("%s%s%s" % (html_colours[colour][0], html_escape(s), html_colours[colour][1]))
133   else:
134     return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
135
136 def print_escaped_text(s):
137   if use_html:
138     print "<pre>%s</pre>" % (s)
139   else:
140     print s  
141
142 def print_formatted_text(s):
143   if use_html:
144     print "<pre>%s</pre>" % (html_escape(s))
145   else:
146     print s
147
148 ################################################################################
149
150 def get_depends_parts(depend) :
151     v_match = re_version.match(depend)
152     if v_match:
153         d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
154     else :
155         d_parts = { 'name' : depend , 'version' : '' }
156     return d_parts
157
158 def get_or_list(depend) :
159     or_list = depend.split("|")
160     return or_list
161
162 def get_comma_list(depend) :
163     dep_list = depend.split(",")
164     return dep_list
165
166 def split_depends (d_str) :
167     # creates a list of lists of dictionaries of depends (package,version relation)
168
169     d_str = re_spacestrip.sub('',d_str)
170     depends_tree = []
171     # first split depends string up amongs comma delimiter
172     dep_list = get_comma_list(d_str)
173     d = 0
174     while d < len(dep_list):
175         # put depends into their own list
176         depends_tree.append([dep_list[d]])
177         d += 1
178     d = 0
179     while d < len(depends_tree):
180         k = 0
181         # split up Or'd depends into a multi-item list
182         depends_tree[d] = get_or_list(depends_tree[d][0])
183         while k < len(depends_tree[d]):
184             # split depends into {package, version relation}
185             depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
186             k += 1
187         d += 1
188     return depends_tree
189
190 def read_control (filename):
191     recommends = []
192     depends = []
193     section = ''
194     maintainer = ''
195     arch = ''
196
197     deb_file = daklib.utils.open_file(filename)
198     try:
199         extracts = apt_inst.debExtractControl(deb_file)
200         control = apt_pkg.ParseSection(extracts)
201     except:
202         print_formatted_text("can't parse control info")
203         # TV-COMMENT: this will raise exceptions in two lines
204         control = ''
205
206     deb_file.close()
207
208     control_keys = control.keys()
209
210     if control.has_key("Depends"):
211         depends_str = control.Find("Depends")
212         # create list of dependancy lists
213         depends = split_depends(depends_str)
214
215     if control.has_key("Recommends"):
216         recommends_str = control.Find("Recommends")
217         recommends = split_depends(recommends_str)
218
219     if control.has_key("Section"):
220         section_str = control.Find("Section")
221
222         c_match = re_contrib.search(section_str)
223         nf_match = re_nonfree.search(section_str)
224         if c_match :
225             # contrib colour
226             section = colour_output(section_str, 'contrib')
227         elif nf_match :
228             # non-free colour
229             section = colour_output(section_str, 'nonfree')
230         else :
231             # main
232             section = colour_output(section_str, 'main')
233     if control.has_key("Architecture"):
234         arch_str = control.Find("Architecture")
235         arch = colour_output(arch_str, 'arch')
236
237     if control.has_key("Maintainer"):
238         maintainer = control.Find("Maintainer")
239         localhost = re_localhost.search(maintainer)
240         if localhost:
241             #highlight bad email
242             maintainer = colour_output(maintainer, 'maintainer')
243         else:
244             maintainer = escape_if_needed(maintainer)
245
246     return (control, control_keys, section, depends, recommends, arch, maintainer)
247
248 def read_dsc (dsc_filename):
249     dsc = {}
250
251     dsc_file = daklib.utils.open_file(dsc_filename)
252     try:
253         dsc = daklib.utils.parse_changes(dsc_filename)
254     except:
255         print_formatted_text("can't parse control info")
256     dsc_file.close()
257
258     filecontents = escape_if_needed(strip_pgp_signature(dsc_filename))
259
260     if dsc.has_key("build-depends"):
261         builddep = split_depends(dsc["build-depends"])
262         builddepstr = create_depends_string(builddep)
263         filecontents = re_builddep.sub("Build-Depends: "+builddepstr, filecontents)
264
265     if dsc.has_key("build-depends-indep"):
266         builddepindstr = create_depends_string(split_depends(dsc["build-depends-indep"]))
267         filecontents = re_builddepind.sub("Build-Depends-Indep: "+builddepindstr, filecontents)
268
269     if dsc.has_key("architecture") :
270         if (dsc["architecture"] != "any"):
271             newarch = colour_output(dsc["architecture"], 'arch')
272             filecontents = re_arch.sub("Architecture: " + newarch, filecontents)
273
274     return filecontents
275
276 def create_depends_string (depends_tree):
277     # just look up unstable for now. possibly pull from .changes later
278     suite = "unstable"
279     result = ""
280     comma_count = 1
281     for l in depends_tree:
282         if (comma_count >= 2):
283             result += ", "
284         or_count = 1
285         for d in l:
286             if (or_count >= 2 ):
287                 result += " | "
288             # doesn't do version lookup yet.
289
290             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))
291             ql = q.getresult()
292             if ql:
293                 i = ql[0]
294
295                 adepends = d['name']
296                 if d['version'] != '' :
297                     adepends += " (%s)" % (d['version'])
298                 
299                 if i[2] == "contrib":
300                     result += colour_output(adepends, "contrib")
301                 elif i[2] == "non-free":
302                     result += colour_output(adepends, "nonfree")
303                 else :
304                     result += colour_output(adepends, "main")
305             else:
306                 adepends = d['name']
307                 if d['version'] != '' :
308                     adepends += " (%s)" % (d['version'])
309                 result += colour_output(adepends, "bold")
310             or_count += 1
311         comma_count += 1
312     return result
313
314 def output_deb_info(filename):
315     (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
316
317     to_print = ""
318     if control == '':
319         print_formatted_text("no control info")
320     else:
321         for key in control_keys :
322             output = " " + key + ": "
323             if key == 'Depends':
324                 output += create_depends_string(depends)
325             elif key == 'Recommends':
326                 output += create_depends_string(recommends)
327             elif key == 'Section':
328                 output += section
329             elif key == 'Architecture':
330                 output += arch
331             elif key == 'Maintainer':
332                 output += maintainer
333             elif key == 'Description':
334                 desc = control.Find(key)
335                 desc = re_newlinespace.sub('\n ', desc)
336                 output += escape_if_needed(desc)
337             else:
338                 output += escape_if_needed(control.Find(key))
339             to_print += output + '\n'
340         print_escaped_text(to_print)
341
342 def do_command (command, filename, escaped=0):
343     o = os.popen("%s %s" % (command, filename))
344     if escaped:
345         print_escaped_text(o.read())
346     else:
347         print_formatted_text(o.read())
348
349 def do_lintian (filename):
350     if use_html:
351         do_command("lintian --show-overrides --color html", filename, 1)
352     else:
353         do_command("lintian --show-overrides --color always", filename, 1)
354
355 def print_copyright (deb_filename):
356     package = re_package.sub(r'\1', deb_filename)
357     o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
358     copyright = o.read()[:-1]
359
360     if copyright == "":
361         print_formatted_text("WARNING: No copyright found, please check package manually.")
362         return
363
364     doc_directory = re_doc_directory.sub(r'\1', copyright)
365     if package != doc_directory:
366         print_formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
367         return
368
369     o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, copyright))
370     copyright = o.read()
371     copyrightmd5 = md5.md5(copyright).hexdigest()
372
373     if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
374         print_formatted_text( "NOTE: Copyright is the same as %s.\n" % \
375                 (printed_copyrights[copyrightmd5]))
376     else:
377         printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
378
379     print_formatted_text(copyright)
380
381 def check_dsc (dsc_filename):
382     headline(".dsc file for %s" % (dsc_filename))
383     (dsc) = read_dsc(dsc_filename)
384     print_escaped_text(dsc)
385     headline("lintian check for %s" % (dsc_filename))
386     do_lintian(dsc_filename)
387
388 def check_deb (deb_filename):
389     filename = os.path.basename(deb_filename)
390
391     if filename.endswith(".udeb"):
392         is_a_udeb = 1
393     else:
394         is_a_udeb = 0
395
396     headline("control file for %s" % (filename))
397     #do_command ("dpkg -I", deb_filename)
398     output_deb_info(deb_filename)
399
400     if is_a_udeb:
401         headline("skipping lintian check for udeb")
402         print 
403     else:
404         headline("lintian check for %s" % (filename))
405         do_lintian(deb_filename)
406
407     headline("contents of %s" % (filename))
408     do_command ("dpkg -c", deb_filename)
409
410     if is_a_udeb:
411         headline("skipping copyright for udeb")
412     else:
413         headline("copyright of %s" % (filename))
414         print_copyright(deb_filename)
415
416     headline("file listing of %s" % (filename))
417     do_command ("ls -l", deb_filename)
418
419 # Read a file, strip the signature and return the modified contents as
420 # a string.
421 def strip_pgp_signature (filename):
422     file = daklib.utils.open_file (filename)
423     contents = ""
424     inside_signature = 0
425     skip_next = 0
426     for line in file.readlines():
427         if line[:-1] == "":
428             continue
429         if inside_signature:
430             continue
431         if skip_next:
432             skip_next = 0
433             continue
434         if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
435             skip_next = 1
436             continue
437         if line.startswith("-----BEGIN PGP SIGNATURE"):
438             inside_signature = 1
439             continue
440         if line.startswith("-----END PGP SIGNATURE"):
441             inside_signature = 0
442             continue
443         contents += line
444     file.close()
445     return contents
446
447 # Display the .changes [without the signature]
448 def display_changes(changes_filename):
449     if use_html:
450         print """<div id="changes-wrap"><a name="changes" />
451                    <table class="infobox rfc822">"""
452     headline(changes_filename, bodyelement="changes-body")
453     if use_html:
454         print """    <tbody id="changes-body" class="infobody">"""
455         print """<tr><td>"""
456     print_formatted_text(strip_pgp_signature(changes_filename))
457     if use_html:
458         print """</td></tr>"""
459         """ <!--
460         1. Join multiline fields
461         2. s/^\s*\.?//gm
462         3. s#\n#<br/>#g
463         4. s#^\([^ :]*:\)\s*\(.*\)$#<tr><td class="key">\1</td><td class="val">\2</td></tr>#
464         5. Special handling for homepage, distribution, bugs
465         -->
466           <tr><td class="key">Format:</td><td class="val">1.7</td></tr>
467           <tr><td class="key">Date:</td><td class="val">Mon, 24 Dec 2007 15:32:08 -0200</td></tr>
468           <tr><td class="key">Source:</td><td class="val">php-xdebug</td></tr>
469           <tr><td class="key">Binary:</td><td class="val">php5-xdebug</td></tr>
470           <tr><td class="key">Architecture:</td><td class="val">source amd64</td></tr>
471           <tr><td class="key">Version:</td><td class="val">2.0.2-1</td></tr>
472           <tr><td class="key">Distribution:</td><td class="val"><span class="dist-unstable">unstable</span></td></tr>
473           <tr><td class="key">Urgency:</td><td class="val">low</td></tr>
474           <tr><td class="key">Maintainer:</td><td class="val">Marcelo Jorge Vieira (metal) &lt;metal@alucinados.com&gt;</td></tr>
475           <tr><td class="key">Changed-By:</td><td class="val">Marcelo Jorge Vieira (metal) &lt;metal@alucinados.com&gt;</td></tr>
476           <tr><td class="key">Description:</td><td class="val">
477               php5-xdebug - xdebug extension module for PHP5</td></tr>
478           <tr><td class="key">Closes:</td><td class="val"><a href="http://bugs.debian.org/377348">377348</a></td></tr>
479           <tr><td class="key">Changes:</td><td class="val">
480               php-xdebug (2.0.2-1) unstable; urgency=low<br/>
481               <br/>
482               * Initial release (Closes: <a href="http://bugs.debian.org/377348">#377348</a>)</td></tr>
483           <tr><td class="key">Files:</td><td class="val">
484               c6ee78b58a4d70d66f8a70436b2a943c 632 web optional php-xdebug_2.0.2-1.dsc<br/>
485               d3547f74353174884452a51ee9ca687f 279891 web optional php-xdebug_2.0.2.orig.tar.gz<br/>
486               8e7c262113c8ac13f47781e0ac0eb4c3 4107 web optional php-xdebug_2.0.2-1.diff.gz<br/>
487               3c6be09f23931fabf0b3048575390ed3 137930 web optional php5-xdebug_2.0.2-1_amd64.deb</td></tr>
488               """
489         print """</tbody></table></div>"""
490
491 def check_changes (changes_filename):
492     display_changes(changes_filename)
493
494     changes = daklib.utils.parse_changes (changes_filename)
495     files = daklib.utils.build_file_list(changes)
496     for file in files.keys():
497         if file.endswith(".deb") or file.endswith(".udeb"):
498             check_deb(file)
499         if file.endswith(".dsc"):
500             check_dsc(file)
501         # else: => byhand
502
503 def main ():
504     global Cnf, projectB, db_files, waste, excluded
505
506 #    Cnf = daklib.utils.get_conf()
507
508     Arguments = [('h',"help","Examine-Package::Options::Help"),
509                  ('H',"html-output","Examine-Package::Options::Html-Output"),
510                 ]
511     for i in [ "Help", "Html-Output", "partial-html" ]:
512         if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
513             Cnf["Examine-Package::Options::%s" % (i)] = ""
514
515     args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
516     Options = Cnf.SubTree("Examine-Package::Options")
517
518     if Options["Help"]:
519         usage()
520
521     stdout_fd = sys.stdout
522
523     for file in args:
524         try:
525             if not Options["Html-Output"]:
526                 # Pipe output for each argument through less
527                 less_fd = os.popen("less -R -", 'w', 0)
528                 # -R added to display raw control chars for colour
529                 sys.stdout = less_fd
530             try:
531                 if file.endswith(".changes"):
532                     check_changes(file)
533                 elif file.endswith(".deb") or file.endswith(".udeb"):
534                     check_deb(file)
535                 elif file.endswith(".dsc"):
536                     check_dsc(file)
537                 else:
538                     daklib.utils.fubar("Unrecognised file type: '%s'." % (file))
539             finally:
540                 if not Options["Html-Output"]:
541                     # Reset stdout here so future less invocations aren't FUBAR
542                     less_fd.close()
543                     sys.stdout = stdout_fd
544         except IOError, e:
545             if errno.errorcode[e.errno] == 'EPIPE':
546                 daklib.utils.warn("[examine-package] Caught EPIPE; skipping.")
547                 pass
548             else:
549                 raise
550         except KeyboardInterrupt:
551             daklib.utils.warn("[examine-package] Caught C-c; skipping.")
552             pass
553
554 #######################################################################################
555
556 if __name__ == '__main__':
557     main()
558