]> git.decadent.org.uk Git - dak.git/blob - dak/examine_package.py
remove checksums- from .dsc display
[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 escaped_text(s):
137   if use_html:
138     return "<pre>%s</pre>" % (s)
139   else:
140     return s  
141
142 def formatted_text(s):
143   if use_html:
144     return "<pre>%s</pre>" % (html_escape(s))
145   else:
146     return s
147
148 def output_row(s):
149     if use_html:
150         return """<tr><td>"""+s+"""</td></tr>"""
151     else:
152         return s
153
154 def foldable_output(title, elementnameprefix, content):
155     d = {'elementnameprefix':elementnameprefix}
156     if use_html:
157         print """<div id="%(elementnameprefix)s-wrap"><a name="%(elementnameprefix)s" />
158                    <table class="infobox rfc822">"""%d
159     headline(title, bodyelement="%(elementnameprefix)s-body"%d)
160     if use_html:
161         print """    <tbody id="%(elementnameprefix)s-body" class="infobody">"""%d
162     print output_row(content)
163     if use_html:
164         print """</tbody></table></div>"""
165
166 ################################################################################
167
168 def get_depends_parts(depend) :
169     v_match = re_version.match(depend)
170     if v_match:
171         d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
172     else :
173         d_parts = { 'name' : depend , 'version' : '' }
174     return d_parts
175
176 def get_or_list(depend) :
177     or_list = depend.split("|")
178     return or_list
179
180 def get_comma_list(depend) :
181     dep_list = depend.split(",")
182     return dep_list
183
184 def split_depends (d_str) :
185     # creates a list of lists of dictionaries of depends (package,version relation)
186
187     d_str = re_spacestrip.sub('',d_str)
188     depends_tree = []
189     # first split depends string up amongs comma delimiter
190     dep_list = get_comma_list(d_str)
191     d = 0
192     while d < len(dep_list):
193         # put depends into their own list
194         depends_tree.append([dep_list[d]])
195         d += 1
196     d = 0
197     while d < len(depends_tree):
198         k = 0
199         # split up Or'd depends into a multi-item list
200         depends_tree[d] = get_or_list(depends_tree[d][0])
201         while k < len(depends_tree[d]):
202             # split depends into {package, version relation}
203             depends_tree[d][k] = get_depends_parts(depends_tree[d][k])
204             k += 1
205         d += 1
206     return depends_tree
207
208 def read_control (filename):
209     recommends = []
210     depends = []
211     section = ''
212     maintainer = ''
213     arch = ''
214
215     deb_file = daklib.utils.open_file(filename)
216     try:
217         extracts = apt_inst.debExtractControl(deb_file)
218         control = apt_pkg.ParseSection(extracts)
219     except:
220         print formatted_text("can't parse control info")
221         # TV-COMMENT: this will raise exceptions in two lines
222         control = ''
223
224     deb_file.close()
225
226     control_keys = control.keys()
227
228     if control.has_key("Depends"):
229         depends_str = control.Find("Depends")
230         # create list of dependancy lists
231         depends = split_depends(depends_str)
232
233     if control.has_key("Recommends"):
234         recommends_str = control.Find("Recommends")
235         recommends = split_depends(recommends_str)
236
237     if control.has_key("Section"):
238         section_str = control.Find("Section")
239
240         c_match = re_contrib.search(section_str)
241         nf_match = re_nonfree.search(section_str)
242         if c_match :
243             # contrib colour
244             section = colour_output(section_str, 'contrib')
245         elif nf_match :
246             # non-free colour
247             section = colour_output(section_str, 'nonfree')
248         else :
249             # main
250             section = colour_output(section_str, 'main')
251     if control.has_key("Architecture"):
252         arch_str = control.Find("Architecture")
253         arch = colour_output(arch_str, 'arch')
254
255     if control.has_key("Maintainer"):
256         maintainer = control.Find("Maintainer")
257         localhost = re_localhost.search(maintainer)
258         if localhost:
259             #highlight bad email
260             maintainer = colour_output(maintainer, 'maintainer')
261         else:
262             maintainer = escape_if_needed(maintainer)
263
264     return (control, control_keys, section, depends, recommends, arch, maintainer)
265
266 def read_dsc (dsc_filename):
267     dsc = {}
268
269     dsc_file = daklib.utils.open_file(dsc_filename)
270     try:
271         dsc = daklib.utils.parse_changes(dsc_filename)
272     except:
273         return formatted_text("can't parse control info")
274     dsc_file.close()
275
276     filecontents = escape_if_needed(strip_pgp_signature(dsc_filename))
277     keysinorder = []
278     for l in filecontents.split('\n'):
279         m = re.match(r'([-a-zA-Z0-9]*):', l)
280         if m:
281             keysinorder.append(m.group(1))
282
283     if dsc.has_key("build-depends"):
284         builddep = split_depends(dsc["build-depends"])
285         builddepstr = create_depends_string(builddep)
286         dsc['build-depends'] = builddepstr
287
288     if dsc.has_key("build-depends-indep"):
289         builddepindstr = create_depends_string(split_depends(dsc["build-depends-indep"]))
290         dsc['build-depends-indep'] = builddepindstr
291
292     if dsc.has_key("architecture") :
293         if (dsc["architecture"] != "any"):
294             newarch = colour_output(dsc["architecture"], 'arch')
295             dsc['architecture'] = newarch
296
297     if dsc.has_key("files"):
298         dsc["files"] = '\n'+'\n'.join(map(lambda x: ' '+x, dsc["files"].split('\n')))
299
300     keysinorder = filter(lambda x: not x.lower().startswith('checksums-'), keysinorder)
301
302     filecontents = ''.join(map(lambda x: '%s: %s\n'%(x,dsc[x.lower()]), keysinorder))
303     return filecontents
304
305 def create_depends_string (depends_tree):
306     # just look up unstable for now. possibly pull from .changes later
307     suite = "unstable"
308     result = ""
309     comma_count = 1
310     for l in depends_tree:
311         if (comma_count >= 2):
312             result += ", "
313         or_count = 1
314         for d in l:
315             if (or_count >= 2 ):
316                 result += " | "
317             # doesn't do version lookup yet.
318
319             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))
320             ql = q.getresult()
321             if ql:
322                 i = ql[0]
323
324                 adepends = d['name']
325                 if d['version'] != '' :
326                     adepends += " (%s)" % (d['version'])
327                 
328                 if i[2] == "contrib":
329                     result += colour_output(adepends, "contrib")
330                 elif i[2] == "non-free":
331                     result += colour_output(adepends, "nonfree")
332                 else :
333                     result += colour_output(adepends, "main")
334             else:
335                 adepends = d['name']
336                 if d['version'] != '' :
337                     adepends += " (%s)" % (d['version'])
338                 result += colour_output(adepends, "bold")
339             or_count += 1
340         comma_count += 1
341     return result
342
343 def output_deb_info(filename):
344     (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
345
346     if control == '':
347         return formatted_text("no control info")
348     to_print = ""
349     for key in control_keys :
350         output = " " + key + ": "
351         if key == 'Depends':
352             output += create_depends_string(depends)
353         elif key == 'Recommends':
354             output += create_depends_string(recommends)
355         elif key == 'Section':
356             output += section
357         elif key == 'Architecture':
358             output += arch
359         elif key == 'Maintainer':
360             output += maintainer
361         elif key == 'Description':
362             desc = control.Find(key)
363             desc = re_newlinespace.sub('\n ', desc)
364             output += escape_if_needed(desc)
365         else:
366             output += escape_if_needed(control.Find(key))
367         to_print += output + '\n'
368     return escaped_text(to_print)
369
370 def do_command (command, filename, escaped=0):
371     o = os.popen("%s %s" % (command, filename))
372     if escaped:
373         return escaped_text(o.read())
374     else:
375         return formatted_text(o.read())
376
377 def do_lintian (filename):
378     if use_html:
379         return do_command("lintian --show-overrides --color html", filename, 1)
380     else:
381         return do_command("lintian --show-overrides --color always", filename, 1)
382
383 def get_copyright (deb_filename):
384     package = re_package.sub(r'\1', deb_filename)
385     o = os.popen("dpkg-deb -c %s | egrep 'usr(/share)?/doc/[^/]*/copyright' | awk '{print $6}' | head -n 1" % (deb_filename))
386     copyright = o.read()[:-1]
387
388     if copyright == "":
389         return formatted_text("WARNING: No copyright found, please check package manually.")
390
391     doc_directory = re_doc_directory.sub(r'\1', copyright)
392     if package != doc_directory:
393         return formatted_text("WARNING: wrong doc directory (expected %s, got %s)." % (package, doc_directory))
394
395     o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, copyright))
396     copyright = o.read()
397     copyrightmd5 = md5.md5(copyright).hexdigest()
398
399     res = ""
400     if printed_copyrights.has_key(copyrightmd5) and printed_copyrights[copyrightmd5] != "%s (%s)" % (package, deb_filename):
401         res += formatted_text( "NOTE: Copyright is the same as %s.\n" % \
402                                (printed_copyrights[copyrightmd5]))
403     else:
404         printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
405     return res+formatted_text(copyright)
406
407 def check_dsc (dsc_filename):
408     (dsc) = read_dsc(dsc_filename)
409     foldable_output(dsc_filename, "dsc", escaped_text(dsc))
410     foldable_output("lintian check for %s" % dsc_filename, "source-lintian", do_lintian(dsc_filename))
411
412 def check_deb (deb_filename):
413     filename = os.path.basename(deb_filename)
414     packagename = filename.split('_')[0]
415
416     if filename.endswith(".udeb"):
417         is_a_udeb = 1
418     else:
419         is_a_udeb = 0
420
421
422     foldable_output("control file for %s" % (filename), "binary-%s-control"%packagename,
423                     output_deb_info(deb_filename))
424
425     if is_a_udeb:
426         foldable_output("skipping lintian check for udeb", "binary-%s-lintian"%packagename,
427                         "")
428     else:
429         foldable_output("lintian check for %s" % (filename), "binary-%s-lintian"%packagename,
430                         do_lintian(deb_filename))
431
432     foldable_output("contents of %s" % (filename), "binary-%s-contents"%packagename,
433                     do_command("dpkg -c", deb_filename))
434
435     if is_a_udeb:
436         foldable_output("skipping copyright for udeb", "binary-%s-copyright"%packagename,
437                         "")
438     else:
439         foldable_output("copyright of %s" % (filename), "binary-%s-copyright"%packagename,
440                         get_copyright(deb_filename))
441
442     foldable_output("file listing of %s" % (filename),  "binary-%s-file-listing"%packagename,
443                     do_command("ls -l", deb_filename))
444
445 # Read a file, strip the signature and return the modified contents as
446 # a string.
447 def strip_pgp_signature (filename):
448     file = daklib.utils.open_file (filename)
449     contents = ""
450     inside_signature = 0
451     skip_next = 0
452     for line in file.readlines():
453         if line[:-1] == "":
454             continue
455         if inside_signature:
456             continue
457         if skip_next:
458             skip_next = 0
459             continue
460         if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
461             skip_next = 1
462             continue
463         if line.startswith("-----BEGIN PGP SIGNATURE"):
464             inside_signature = 1
465             continue
466         if line.startswith("-----END PGP SIGNATURE"):
467             inside_signature = 0
468             continue
469         contents += line
470     file.close()
471     return contents
472
473 # Display the .changes [without the signature]
474 # TV-COMMENT: M. Ferrari has more formatting ideas
475 def display_changes(changes_filename):
476     foldable_output(changes_filename, "changes", formatted_text(strip_pgp_signature(changes_filename)))
477
478 def check_changes (changes_filename):
479     display_changes(changes_filename)
480
481     changes = daklib.utils.parse_changes (changes_filename)
482     files = daklib.utils.build_file_list(changes)
483     for file in files.keys():
484         if file.endswith(".deb") or file.endswith(".udeb"):
485             check_deb(file)
486         if file.endswith(".dsc"):
487             check_dsc(file)
488         # else: => byhand
489
490 def main ():
491     global Cnf, projectB, db_files, waste, excluded
492
493 #    Cnf = daklib.utils.get_conf()
494
495     Arguments = [('h',"help","Examine-Package::Options::Help"),
496                  ('H',"html-output","Examine-Package::Options::Html-Output"),
497                 ]
498     for i in [ "Help", "Html-Output", "partial-html" ]:
499         if not Cnf.has_key("Examine-Package::Options::%s" % (i)):
500             Cnf["Examine-Package::Options::%s" % (i)] = ""
501
502     args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
503     Options = Cnf.SubTree("Examine-Package::Options")
504
505     if Options["Help"]:
506         usage()
507
508     stdout_fd = sys.stdout
509
510     for file in args:
511         try:
512             if not Options["Html-Output"]:
513                 # Pipe output for each argument through less
514                 less_fd = os.popen("less -R -", 'w', 0)
515                 # -R added to display raw control chars for colour
516                 sys.stdout = less_fd
517             try:
518                 if file.endswith(".changes"):
519                     check_changes(file)
520                 elif file.endswith(".deb") or file.endswith(".udeb"):
521                     check_deb(file)
522                 elif file.endswith(".dsc"):
523                     check_dsc(file)
524                 else:
525                     daklib.utils.fubar("Unrecognised file type: '%s'." % (file))
526             finally:
527                 if not Options["Html-Output"]:
528                     # Reset stdout here so future less invocations aren't FUBAR
529                     less_fd.close()
530                     sys.stdout = stdout_fd
531         except IOError, e:
532             if errno.errorcode[e.errno] == 'EPIPE':
533                 daklib.utils.warn("[examine-package] Caught EPIPE; skipping.")
534                 pass
535             else:
536                 raise
537         except KeyboardInterrupt:
538             daklib.utils.warn("[examine-package] Caught C-c; skipping.")
539             pass
540
541 #######################################################################################
542
543 if __name__ == '__main__':
544     main()
545