2 # -*- coding: latin-1 -*-
4 # Script to automate some parts of checking NEW packages
5 # Copyright (C) 2000, 2001, 2002, 2003, 2006 James Troup <james@nocrew.org>
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.
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.
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
21 ################################################################################
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,
34 ################################################################################
36 import errno, os, pg, re, sys, md5, time
37 import apt_pkg, apt_inst
38 import daklib.database, daklib.utils
40 ################################################################################
42 re_package = re.compile(r"^(.+?)_.*")
43 re_doc_directory = re.compile(r".*/doc/([^/]*).*")
45 re_contrib = re.compile('^contrib/')
46 re_nonfree = re.compile('^non\-free/')
48 re_arch = re.compile("Architecture: .*")
49 re_builddep = re.compile("Build-Depends: .*")
50 re_builddepind = re.compile("Build-Depends-Indep: .*")
52 re_localhost = re.compile("localhost\.localdomain")
53 re_version = re.compile('^(.*)\((.*)\)')
55 re_newlinespace = re.compile('\n')
56 re_spacestrip = re.compile('(\s)')
58 html_escaping = {'"':'"', '&':'&', '<':'<', '>':'>'}
59 re_html_escaping = re.compile('|'.join(map(re.escape, html_escaping.keys())))
61 ################################################################################
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)
70 printed_copyrights = {}
72 # default is to not output html.
75 ################################################################################
77 def usage (exit_code=0):
78 print """Usage: dak examine-package [PACKAGE]...
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
85 PACKAGE can be a .changes, .dsc, .deb or .udeb filename."""
89 ################################################################################
90 # probably xml.sax.saxutils would work as well
93 return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
95 def escape_if_needed(s):
97 return re_html_escaping.sub(html_escaping.get, s)
101 def headline(s, level=2):
103 print "<h%d>%s</h%d>" % (level,html_escape(s),level)
105 print "---- %s ----" % (s)
107 # Colour definitions, 'end' isn't really for use
111 'contrib': "\033[33m",
112 'nonfree': "\033[31m",
116 'maintainer': "\033[32m"}
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>")}
126 def colour_output(s, colour):
128 return ("%s%s%s" % (html_colours[colour][0], html_escape(s), html_colours[colour][1]))
130 return ("%s%s%s" % (ansi_colours[colour], s, ansi_colours['end']))
132 def print_escaped_text(s):
134 print "<pre>%s</pre>" % (s)
138 def print_formatted_text(s):
140 print "<pre>%s</pre>" % (html_escape(s))
144 ################################################################################
146 def get_depends_parts(depend) :
147 v_match = re_version.match(depend)
149 d_parts = { 'name' : v_match.group(1), 'version' : v_match.group(2) }
151 d_parts = { 'name' : depend , 'version' : '' }
154 def get_or_list(depend) :
155 or_list = depend.split("|")
158 def get_comma_list(depend) :
159 dep_list = depend.split(",")
162 def split_depends (d_str) :
163 # creates a list of lists of dictionaries of depends (package,version relation)
165 d_str = re_spacestrip.sub('',d_str)
167 # first split depends string up amongs comma delimiter
168 dep_list = get_comma_list(d_str)
170 while d < len(dep_list):
171 # put depends into their own list
172 depends_tree.append([dep_list[d]])
175 while d < len(depends_tree):
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])
186 def read_control (filename):
193 deb_file = daklib.utils.open_file(filename)
195 extracts = apt_inst.debExtractControl(deb_file)
196 control = apt_pkg.ParseSection(extracts)
198 print_formatted_text("can't parse control info")
199 # TV-COMMENT: this will raise exceptions in two lines
204 control_keys = control.keys()
206 if control.has_key("Depends"):
207 depends_str = control.Find("Depends")
208 # create list of dependancy lists
209 depends = split_depends(depends_str)
211 if control.has_key("Recommends"):
212 recommends_str = control.Find("Recommends")
213 recommends = split_depends(recommends_str)
215 if control.has_key("Section"):
216 section_str = control.Find("Section")
218 c_match = re_contrib.search(section_str)
219 nf_match = re_nonfree.search(section_str)
222 section = colour_output(section_str, 'contrib')
225 section = colour_output(section_str, 'nonfree')
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')
233 if control.has_key("Maintainer"):
234 maintainer = control.Find("Maintainer")
235 localhost = re_localhost.search(maintainer)
238 maintainer = colour_output(maintainer, 'maintainer')
240 maintainer = escape_if_needed(maintainer)
242 return (control, control_keys, section, depends, recommends, arch, maintainer)
244 def read_dsc (dsc_filename):
247 dsc_file = daklib.utils.open_file(dsc_filename)
249 dsc = daklib.utils.parse_changes(dsc_filename)
251 print_formatted_text("can't parse control info")
254 filecontents = escape_if_needed(strip_pgp_signature(dsc_filename))
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)
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)
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)
272 def create_depends_string (depends_tree):
273 # just look up unstable for now. possibly pull from .changes later
277 for l in depends_tree:
278 if (comma_count >= 2):
284 # doesn't do version lookup yet.
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))
292 if d['version'] != '' :
293 adepends += " (%s)" % (d['version'])
295 if i[2] == "contrib":
296 result += colour_output(adepends, "contrib")
297 elif i[2] == "non-free":
298 result += colour_output(adepends, "nonfree")
300 result += colour_output(adepends, "main")
303 if d['version'] != '' :
304 adepends += " (%s)" % (d['version'])
305 result += colour_output(adepends, "bold")
310 def output_deb_info(filename):
311 (control, control_keys, section, depends, recommends, arch, maintainer) = read_control(filename)
315 print_formatted_text("no control info")
317 for key in control_keys :
318 output = " " + key + ": "
320 output += create_depends_string(depends)
321 elif key == 'Recommends':
322 output += create_depends_string(recommends)
323 elif key == 'Section':
325 elif key == 'Architecture':
327 elif key == 'Maintainer':
329 elif key == 'Description':
330 desc = control.Find(key)
331 desc = re_newlinespace.sub('\n ', desc)
332 output += escape_if_needed(desc)
334 output += escape_if_needed(control.Find(key))
335 to_print += output + '\n'
336 print_formatted_text(to_print)
338 def do_command (command, filename):
339 o = os.popen("%s %s" % (command, filename))
340 print_formatted_text(o.read())
342 def do_lintian (filename):
343 # lintian currently does not have html coloring, so dont use color for lintian (yet)
345 do_command("lintian --show-overrides", filename)
347 do_command("lintian --show-overrides --color always", filename)
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]
355 print_formatted_text("WARNING: No copyright found, please check package manually.")
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))
363 o = os.popen("dpkg-deb --fsys-tarfile %s | tar xvOf - %s 2>/dev/null" % (deb_filename, copyright))
365 copyrightmd5 = md5.md5(copyright).hexdigest()
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]))
371 printed_copyrights[copyrightmd5] = "%s (%s)" % (package, deb_filename)
373 print_formatted_text(copyright)
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)
382 def check_deb (deb_filename):
383 filename = os.path.basename(deb_filename)
385 if filename.endswith(".udeb"):
390 headline("control file for %s" % (filename))
391 #do_command ("dpkg -I", deb_filename)
392 output_deb_info(deb_filename)
395 headline("skipping lintian check for µdeb")
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)
403 headline("contents of %s" % (filename))
404 do_command ("dpkg -c", deb_filename)
407 headline("skipping copyright for µdeb")
409 headline("copyright of %s" % (filename))
410 print_copyright(deb_filename)
412 headline("file listing of %s" % (filename))
413 do_command ("ls -l", deb_filename)
415 # Read a file, strip the signature and return the modified contents as
417 def strip_pgp_signature (filename):
418 file = daklib.utils.open_file (filename)
422 for line in file.readlines():
430 if line.startswith("-----BEGIN PGP SIGNED MESSAGE"):
433 if line.startswith("-----BEGIN PGP SIGNATURE"):
436 if line.startswith("-----END PGP SIGNATURE"):
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))
448 def check_changes (changes_filename):
449 display_changes(changes_filename)
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"):
456 if file.endswith(".dsc"):
461 global Cnf, projectB, db_files, waste, excluded
463 # Cnf = daklib.utils.get_conf()
465 Arguments = [('h',"help","Examine-Package::Options::Help"),
466 ('H',"Html-output","Examine-Package::Options::Html-Output"),
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)] = ""
472 args = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
473 Options = Cnf.SubTree("Examine-Package::Options")
478 stdout_fd = sys.stdout
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
488 if file.endswith(".changes"):
490 elif file.endswith(".deb") or file.endswith(".udeb"):
492 elif file.endswith(".dsc"):
495 daklib.utils.fubar("Unrecognised file type: '%s'." % (file))
497 if not Options["Html-Output"]:
498 # Reset stdout here so future less invocations aren't FUBAR
500 sys.stdout = stdout_fd
502 if errno.errorcode[e.errno] == 'EPIPE':
503 daklib.utils.warn("[examine-package] Caught EPIPE; skipping.")
507 except KeyboardInterrupt:
508 daklib.utils.warn("[examine-package] Caught C-c; skipping.")
511 #######################################################################################
513 if __name__ == '__main__':