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