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