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